com.esd.cs.worker.WorkerController.java Source code

Java tutorial

Introduction

Here is the source code for com.esd.cs.worker.WorkerController.java

Source

/*
 * Copyright (c) 2013 ????www.hrbesd.com. All rights reserved.
 * 
 * HRBESD PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.esd.cs.worker;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.esd.common.util.PaginationRecordsAndNumber;
import com.esd.cs.Constants;
import com.esd.cs.common.CommonUtil;
import com.esd.cs.common.PoiCreateExcel;
import com.esd.hesf.model.AuditParameter;
import com.esd.hesf.model.Company;
import com.esd.hesf.model.CompanyYearWorker;
import com.esd.hesf.model.Worker;
import com.esd.hesf.model.WorkerHandicapLevel;
import com.esd.hesf.model.WorkerHandicapType;
import com.esd.hesf.model.WorkerTemp;
import com.esd.hesf.service.AuditParameterService;
import com.esd.hesf.service.CompanyService;
import com.esd.hesf.service.CompanyYearWorkerService;
import com.esd.hesf.service.WorkerService;
import com.esd.hesf.service.WorkerTempService;
import com.esd.hesf.service.impl.WorkerServiceImpl;

/*
 * ?
 * 
 * @author yuxingliang
 */
@Controller
@RequestMapping(value = "/security/worker")
public class WorkerController {

    private static final Logger logger = LoggerFactory.getLogger(WorkerController.class);
    @Autowired
    private WorkerService workerService;// 

    @Autowired
    private CompanyService companyService;// ?

    @Autowired
    private WorkerTempService wtService; // service?

    @Autowired
    private AuditParameterService auditParameterService;// ?

    @Autowired
    private CompanyYearWorkerService cywService; // ?service?

    @Value("${LoadUpFileMaxSize}")
    String LoadUpFileMaxSize;

    // ??
    static int MAX_HANDICAPCODE = 22;
    // ???
    static int MIN_HANDICAPCODE = 20;

    // ??
    static String LENGTHERROR = "???";

    // ??
    static String BEENHIRED = "?";
    // ??
    static String ILLEGALSTR = "???";

    // ??
    static String LEVELERROR = "???";
    // ??
    static String TYPEERROR = "???";
    // ??
    static String AGEERROR = "";
    static String NAMENULL = "??";
    static String WORDERROR = "excel?!";
    static String CREATEERRORFILE = "?";

    // ?
    static Integer workerCount; // ?
    static Integer currentCount; // ???

    /**
     * ?? ?tabpost?? getpost?
     * 
     * @param request
     * @return
     */
    @RequestMapping(value = "/list/{companyId}/{year}")
    public ModelAndView worker_list(@PathVariable(value = "companyId") Integer companyId,
            @PathVariable(value = "year") String year, HttpServletRequest request) {
        logger.debug("goToWorkerList year:{},companyId:{}", year, companyId);

        request.setAttribute("year", year);
        request.setAttribute("companyId", companyId);
        // ??
        AuditParameter param = auditParameterService.getByYear(year);
        if (param != null) {
            // ?
            request.setAttribute("maleRetirementAge", param.getRetireAgeMale());
            // ?
            request.setAttribute("femaleRetirementAge", param.getRetireAgeFemale());
        } else {
            logger.error("getAuditParameterError");
        }
        logger.debug("goToPage:{}", "??");
        return new ModelAndView("basicInfo/worker_list");
    }

    /**
     * ?? ?????
     * 
     * @param request
     * @return
     */
    @RequestMapping(value = "/list/auditCreate")
    public ModelAndView audit_create_worker_list(HttpServletRequest request, HttpSession session) {
        String year = session.getAttribute(Constants.YEAR).toString();
        logger.debug("goToWorkerList year:{}", year);
        request.setAttribute("year", year);
        // ??
        AuditParameter param = auditParameterService.getByYear(year);
        if (param != null) {
            // ?
            request.setAttribute("maleRetirementAge", param.getRetireAgeMale());
            // ?
            request.setAttribute("femaleRetirementAge", param.getRetireAgeFemale());
        } else {
            logger.error("getAuditParameterError");
        }
        logger.debug("goToPage:{}", "??");
        return new ModelAndView("audit/audit_create_worker_list");
    }

    /**
     * ?? 
     * 
     * @param companyId
     * @param request
     * @return
     */
    @RequestMapping(value = "/view/{companyId}/{year}")
    public ModelAndView view(@PathVariable(value = "companyId") String companyId,
            @PathVariable(value = "year") String year, HttpServletRequest request) {
        request.setAttribute("companyId", companyId);
        request.setAttribute("year", year);
        // ??
        AuditParameter param = auditParameterService.getByYear(year);
        if (param != null) {
            // ?
            request.setAttribute("maleRetirementAge", param.getRetireAgeMale());
            // ?
            request.setAttribute("femaleRetirementAge", param.getRetireAgeFemale());
        } else {
            logger.error("getAuditParameterError");
        }
        logger.debug("goToPage:{}", "??Ex");
        return new ModelAndView("basicInfo/worker_simplelist");
    }

    /**
     * ??
     */
    @RequestMapping(value = "/add/{companyId}/{year}", method = RequestMethod.GET)
    public ModelAndView add_worker(@PathVariable(value = "companyId") String companyId,
            @PathVariable(value = "year") String year, HttpServletRequest request) {
        logger.debug("gotoAddWorker,companyId:{},year:{}", companyId, year);

        // ?id
        request.setAttribute("companyId", companyId);
        request.setAttribute("year", year);
        // ??
        AuditParameter auditParam = auditParameterService.getByYear(year);
        request.setAttribute("retireAgeFemale", auditParam.getRetireAgeFemale());// 
        request.setAttribute("retireAgeMale", auditParam.getRetireAgeMale());// 

        logger.info("goToPage:{}", "??");
        return new ModelAndView("basicInfo/add_worker");
    }

    /**
     * ?
     * 
     * @param worker
     * @param request
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public Boolean add_worker(Worker worker, HttpServletRequest request) {
        try {
            Integer companyId = Integer.valueOf(request.getParameter("companyId"));
            String year = request.getParameter("year");
            logger.debug("addWorker--:{},year:{},companyID:{}", worker, year, companyId);

            boolean b = workerService.save(worker, companyId, year);
            logger.debug("addWorker:{},Result:{}", worker, b);
            return b;
        } catch (Exception e) {
            logger.error("addWorkerError:{}", e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    private boolean addWorker(Worker worker, Integer companyId, String year) {
        logger.debug("addWorkerParams:{},companyId:{},year:{}", worker, companyId, year);
        boolean b = workerService.save(worker, companyId, year);
        logger.debug("addWorkerResult:{}", b);
        return b;
    }

    /**
     * ??
     * 
     * @param id
     * @param request
     * @return
     */
    @RequestMapping(value = "/view/{id}", method = RequestMethod.GET)
    public ModelAndView viewWorker(@PathVariable(value = "id") Integer id, HttpServletRequest request) {
        // ?id
        logger.debug("editWorkerParamsID:{}", id);
        Worker w = workerService.getByPrimaryKey(id);
        request.setAttribute("worker", w);
        logger.debug("goToedit_worker{}", w);
        return new ModelAndView("basicInfo/view_worker");
    }

    /**
     * ??
     * 
     * @param id
     * @param request
     * @return
     */
    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public ModelAndView editWorker(@PathVariable(value = "id") Integer id, HttpServletRequest request) {
        // ?id
        logger.debug("editWorkerParamsID:{}", id);
        Worker w = workerService.getByPrimaryKey(id);
        request.setAttribute("worker", w);
        logger.debug("goToedit_worker{}", w);
        return new ModelAndView("basicInfo/edit_worker");
    }

    /**
     * ??
     * 
     * @param worker
     * @param request
     * @return
     */
    @RequestMapping(value = "/importworker/{companyId}/{year}", method = RequestMethod.GET)
    public ModelAndView importworker(@PathVariable(value = "companyId") Integer companyId,
            @PathVariable(value = "year") String year, HttpServletRequest request, HttpSession session) {
        request.setAttribute("companyId", companyId);
        request.setAttribute("year", year);
        logger.debug("goToWorker_import,param:{}", companyId);
        // ??????workerTemp?
        Integer userId = Integer.parseInt(session.getAttribute(Constants.USER_ID).toString());
        wtService.deleteByUserId(userId);
        return new ModelAndView("basicInfo/worker_import");
    }

    /**
     * ?
     * 
     * @param worker
     * @param request
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ResponseBody
    public Boolean edit_worker(Worker worker, HttpServletRequest request) {
        logger.debug("editWorker:{}", worker);
        boolean b = workerService.update(worker);
        logger.debug("editWorkerResult:{}", b);
        return b;
    }

    /**
     * ? ??? ??
     * 
     * @param worker
     * @param request
     * @return
     */
    @RequestMapping(value = "/updata", method = RequestMethod.POST)
    @ResponseBody
    public Boolean edit_worker_up(Worker worker, HttpServletRequest request) {
        logger.debug("editUpdata:{}", worker);
        Integer companyId = Integer.valueOf(request.getParameter("companyId"));

        return editWorkerUp(worker, companyId, worker.getWorkerBirthYear());
    }

    /**
     * ??????
     * 
     * @param worker
     * @param companyId
     * @param year
     * @return
     */
    private boolean editWorkerUp(Worker worker, Integer companyId, String year) {
        boolean workerUpDataStatus = false, companyUpdataStatus = false;
        logger.debug("upWorker:{},companyId:{}", worker, companyId);
        try {
            // ?????
            Worker w = workerService.getByWorkerHandicapCode(worker.getWorkerHandicapCode());
            if (w == null) {
                logger.error("UpWorkerError:{},info:{}", "notWorkerHandicapCode", worker);
                return false;
            }
            // set?
            worker.setVersion(w.getVersion());
            // id
            worker.setId(w.getId());
            // ?
            workerUpDataStatus = workerService.update(worker);
            logger.debug("workerUpDataResult:{}", workerUpDataStatus);
            if (workerUpDataStatus) {
                // ????
                Company c = companyService.getByPrimaryKey(companyId);
                if (c != null) {
                    companyUpdataStatus = workerService.changeCompany(worker.getId(), c.getId(), year,
                            worker.getCurrentJob());
                    if (companyUpdataStatus) {
                        logger.debug("workerUpDataGetCompanyResult:{}", companyUpdataStatus);
                    } else {
                        logger.error("workerUpDataGetCompanyResult:{}", companyUpdataStatus);
                    }
                } else {
                    logger.error("upWorkerError:{}", "noGetCompany");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("workerUpdataError:{}", e.getMessage());
        }
        return workerUpDataStatus && companyUpdataStatus;
    }

    /**
     * ?
     * 
     * @param id
     * @param request
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public Boolean delete_worker(@RequestParam(value = "params[]") Integer params[],
            @RequestParam(value = "companyId") Integer companyId, @RequestParam(value = "year") String year,
            HttpServletRequest request) {

        logger.debug("deleteWorkerParamsID:{},years:{},companyId:{}", params, year, companyId);
        try {
            for (int i = 0; i < params.length; i++) {
                boolean b = companyService.deleteWorkerFromCompany(year, companyId, params[i]);
                logger.debug("delete_worker:{},result:{}", params[i], b);
                if (b = false) {

                    logger.error("deleteWorkerError:{},result:{}", params[i], "error");
                    return false;
                }
            }
        } catch (Exception e) {
            logger.error("delete_worker{}", e.getMessage());
        }
        return true;
    }

    /**
     * ?
     * 
     * @param request
     * @param response
     * @return
     */
    public Map<String, String> importfile(String upLoadPath, HttpServletRequest request,
            HttpServletResponse response) {
        // ???
        // String fileType = "xls";
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 
        factory.setSizeThreshold(5 * 1024);
        // 
        factory.setRepository(new File(upLoadPath));
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        Map<String, String> result = new HashMap<String, String>();

        if (LoadUpFileMaxSize != null && !StringUtils.equals(LoadUpFileMaxSize.trim(), "")) {
            // ?
            fileUpload.setSizeMax(Integer.valueOf(LoadUpFileMaxSize) * 1024 * 1024);
        }
        try {
            // ?
            List<FileItem> items = fileUpload.parseRequest(request);
            for (FileItem item : items) {
                // ?
                if (!item.isFormField()) {
                    // ??
                    String fileName = item.getName();
                    // ??
                    String fileEnd = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                    // ??
                    String uuid = UUID.randomUUID().toString();
                    // 
                    StringBuffer sbRealPath = new StringBuffer();
                    sbRealPath.append(upLoadPath).append(uuid).append(".").append(fileEnd);
                    // 
                    File file = new File(sbRealPath.toString());
                    item.write(file);

                    logger.info("?,filePath" + file.getPath());
                    // 
                    result.put("filePath", file.getPath());

                    // form??
                } else {
                    // item.getFieldName():??keyitem.getString()??value
                    result.put(item.getFieldName(), item.getString());
                }
            }
        } catch (Exception e) {

            // ???
            result.put("fileError", ",??" + LoadUpFileMaxSize + "M!");
            logger.error("uplaodWorkerFileError:{}", e.getMessage());
            return result;
        }
        return result;
    }

    // /**
    // * ????
    // */
    // @RequestMapping(value = "/getDealedProgress", method = RequestMethod.GET)
    // @ResponseBody
    // public Integer getDealProgress(HttpSession session) {
    // Integer userId
    // =Integer.parseInt(session.getAttribute(Constants.USER_ID).toString());
    // int currentCount = wtService.getCountByCheck(null, userId,null);
    // System.out.println(currentCount);
    // System.out.println(workerCount);
    // //?
    // if (workerCount == null) {
    // workerCount = Integer.MAX_VALUE;
    // }
    // int rate = currentCount * 100 / workerCount;
    // return rate;
    // }

    /**
     * ????
     */
    @RequestMapping(value = "/getDealedProgress", method = RequestMethod.GET)
    @ResponseBody
    public Integer getDealProgress(HttpSession session) {
        if (currentCount == null) {
            currentCount = 0;
        }
        System.out.println(currentCount + "-----------" + workerCount);
        // ?
        if (workerCount == null) {
            workerCount = Integer.MAX_VALUE;
        }
        int rate = currentCount * 100 / workerCount;
        return rate;
    }

    /**
     * ?
     */
    @RequestMapping(value = "/importworker", method = RequestMethod.POST)
    public ModelAndView importworker(HttpServletRequest request, HttpServletResponse response,
            HttpSession session) {
        Integer userId = Integer.parseInt(session.getAttribute(Constants.USER_ID).toString());
        // ??????workerTemp?
        wtService.deleteByUserId(userId);
        logger.debug("importWorker:{}");
        // ?
        String upload = "upload";
        String workerFolder = "worker";
        String url = request.getServletContext().getRealPath("/");
        String upLoadPath = url + upload + File.separator + workerFolder + File.separator;
        File uploadPath = new File(url + "upload");
        File tempPath = new File(uploadPath + File.separator + workerFolder);
        //  
        if (!uploadPath.exists()) {
            logger.debug(upload + " Does not exist,Create " + upload + " Folder");
            uploadPath.mkdir();
        }
        if (!tempPath.exists()) {
            logger.debug(workerFolder + " Does not exist,Create " + workerFolder + " Folder");
            tempPath.mkdir();
        }

        // 
        Map<String, String> paramMap = importfile(upLoadPath, request, response);
        String fileError = paramMap.get("fileError");// ?
        if (fileError != null) {
            // ?
            request.setAttribute("errorInfo", fileError);
            return new ModelAndView("basicInfo/worker_importInfo");
        }
        // ??
        String filePath = paramMap.get("filePath");// 
        Integer companyId = Integer.valueOf(paramMap.get("companyId"));// companyID
        String year = paramMap.get("year");// 
        AuditParameter auditParameter = auditParameterService.getByYear(year);
        // ??

        // List<Worker> workerErrorList = new ArrayList<Worker>();// ?
        // List<Worker> workerCorrectList = new ArrayList<Worker>();// ?
        List<Worker> list = null;

        if (fileError == null) {
            try {
                File f = new File(filePath);
                // ?excel
                list = WorkerUtil.parse(f, 0);
                // ??
                workerCount = list.size();
                if (list == null || list.size() <= 0) {
                    // excel??
                    logger.error("importWorkerError:{}", WORDERROR);
                    request.setAttribute("errorInfo", WORDERROR);
                    // ??
                    return new ModelAndView("basicInfo/worker_importInfo");
                }
                for (int i = 0; i < list.size(); i++) {
                    // 
                    WorkerTemp t = new WorkerTemp();
                    t.setUserId(userId);
                    // false--????
                    t.setIsOk(false);
                    Worker w = null;
                    // ??
                    currentCount = i + 1;
                    try {
                        Worker worker = list.get(i);
                        // 
                        String workerHandicapCode = worker.getWorkerHandicapCode();
                        // ??
                        String workerName = worker.getWorkerName().replace(" ", "");// 
                        w = new Worker();
                        w.setWorkerName(worker.getWorkerName());
                        w.setWorkerHandicapCode(workerHandicapCode);
                        // 
                        t.setWorkerName(workerName);
                        t.setWorkerHandicapCode(workerHandicapCode);
                        // 1.???
                        if (StringUtils.isEmpty(workerName) || StringUtils.equals(workerName, "null")) {
                            // ?
                            w.setRemark(NAMENULL);
                            // workerErrorList.add(w);
                            t.setRemark(NAMENULL);
                            wtService.save(t);
                            logger.error("impoerWorkerError:{},info:{}", w, NAMENULL);
                            continue;
                        }
                        // 2.??
                        if (workerName.length() > 20) {
                            // ?
                            w.setRemark("???");
                            // workerErrorList.add(w);
                            t.setRemark("???");
                            wtService.save(t);
                            logger.error("impoerWorkerError:{},info:{}", w, "???");
                            continue;
                        }
                        // 3.???
                        if (StringUtils.isBlank(workerHandicapCode)
                                || StringUtils.equals(workerHandicapCode, "null")) {
                            // ?
                            w.setRemark(LENGTHERROR);
                            // workerErrorList.add(w);
                            t.setRemark(LENGTHERROR);
                            wtService.save(t);
                            logger.error("impoerWorkerError:{},info:{}", w, LENGTHERROR);
                            continue;
                        }
                        // ??
                        workerHandicapCode.replace(" ", "");// 
                        // 4.??
                        if (workerHandicapCode.length() < MIN_HANDICAPCODE
                                || workerHandicapCode.length() > MAX_HANDICAPCODE) {
                            // ?
                            w.setRemark(LENGTHERROR);
                            // workerErrorList.add(w);
                            t.setRemark(LENGTHERROR);
                            wtService.save(t);
                            logger.error("impoerWorkerError:{},info:{}", w, LENGTHERROR);
                            continue;
                        }
                        // 5.????
                        if (CommonUtil.chineseValid(workerHandicapCode)) {
                            // ?
                            w.setRemark(ILLEGALSTR);
                            // workerErrorList.add(w);
                            t.setRemark(ILLEGALSTR);
                            wtService.save(t);
                            logger.error("impoerWorkerError:{},info:{}", w, LENGTHERROR);
                            continue;
                        }
                        // 6.20??
                        String handicapStr = workerHandicapCode.substring(0, 19);
                        if (!handicapStr.matches("\\d+")) {
                            w.setRemark("???20??");
                            // workerErrorList.add(w);
                            t.setRemark("???20??");
                            wtService.save(t);
                            logger.error("impoerWorkerError:{},info:{}", w, TYPEERROR);
                            continue;
                        }
                        // 7.
                        String handicapTypeStr = workerHandicapCode.substring(18, 19);
                        boolean ishandicapType = handicapTypeStr.matches("\\d+");// true,??
                        // 8.?
                        if (ishandicapType) {
                            int handicapType = Integer.valueOf(handicapTypeStr);
                            if (handicapType > 7 || handicapType == 0) {
                                w.setRemark(TYPEERROR);
                                // workerErrorList.add(w);
                                t.setRemark(TYPEERROR);
                                wtService.save(t);
                                logger.error("impoerWorkerError:{},info:{}", w, TYPEERROR);
                                continue;
                            }
                        }

                        // 9.??
                        String handicapLevelStr = workerHandicapCode.substring(19, 20);
                        boolean ishandicapLevel = handicapLevelStr.matches("\\d+");// true,??
                        if (ishandicapLevel) {
                            int handicapLevel = Integer.valueOf(handicapLevelStr);
                            if (handicapLevel > 4 || handicapLevel == 0) {
                                w.setRemark(LEVELERROR);
                                // workerErrorList.add(w);
                                t.setRemark(LEVELERROR);
                                wtService.save(t);
                                logger.error("impoerWorkerError:{},info:{}", w, LEVELERROR);
                                continue;
                            }
                        }

                        // 10.?
                        List<String> ageResult = new WorkerUtil().ageVerifi(workerHandicapCode, auditParameter);
                        if (ageResult != null) {
                            String ageErrorInfo = "" + ageResult.get(0).toString()
                                    + "," + ageResult.get(1).toString() + ""
                                    + ageResult.get(2).toString();
                            w.setRemark(ageErrorInfo);
                            // workerErrorList.add(w);
                            t.setRemark(ageErrorInfo);
                            wtService.save(t);
                            logger.error("impoerWorkerError:{},info:{}", w, ageErrorInfo);
                            continue;
                        }

                        // 11.????
                        List<Map<String, String>> validateList = validateOrganizationCode(
                                workerHandicapCode.substring(0, 18), year);
                        Map<String, String> validateResult = validateList.get(0);
                        logger.debug("LineNumber:{},validataType:{}", i, validateResult.get("type"));
                        // 12.? ?
                        if (StringUtils.equals(validateResult.get("type"), "1")) {
                            // ?
                            String errinfo = "?" + validateList.get(1).get("companyName")
                                    + " ?????"
                                    + validateList.get(1).get("companyCode");
                            w.setRemark(errinfo);
                            // workerErrorList.add(w);
                            t.setRemark(errinfo);
                            wtService.save(t);
                            logger.error("impoerWorkerError:{},info:{}", w, errinfo);
                            continue;
                        }
                        // .???? ? ??
                        if (StringUtils.equals(validateResult.get("type"), "2")
                                || StringUtils.equals(validateResult.get("type"), "3")) {
                            Worker workerUp = new Worker();
                            workerUp.setWorkerName(worker.getWorkerName());
                            workerUp.setWorkerHandicapCode(workerHandicapCode);

                            Worker workerCorrect = WorkerUtil.assembly(workerUp);
                            // workerCorrectList.add(workerCorrect);
                            // ??? 
                            t.setWorkerName(workerCorrect.getWorkerName());
                            t.setWorkerHandicapCode(workerCorrect.getWorkerHandicapCode());
                            t.setIsOk(true);
                            t.setWorkerBirth(workerCorrect.getWorkerBirth());
                            t.setWorkerBirthYear(workerCorrect.getWorkerBirthYear());
                            t.setWorkerGender(workerCorrect.getWorkerGender());
                            t.setWorkerHandicapLevel(workerCorrect.getWorkerHandicapLevel().getId());
                            t.setWorkerHandicapType(workerCorrect.getWorkerHandicapType().getId());
                            t.setWorkerIdCard(workerCorrect.getWorkerIdCard());
                            // , ??, ?id??
                            if (StringUtils.equals(validateResult.get("type"), "2")) {
                                t.setPreId(Integer.parseInt(validateResult.get("workerId").toString()));
                            }
                            wtService.save(t);
                            continue;
                        }
                    } catch (Exception e) {
                        w.setRemark("");
                        // workerErrorList.add(w);
                        t.setRemark("");
                        wtService.save(t);
                        logger.error("impoerWorkerUpError:{}", "false");
                    }
                }
                // ?

                // ??
                List<WorkerTemp> workerErrorList = wtService.getByCheck(false, userId);// ?
                if (workerErrorList.size() != 0) {
                    String errorFilePath = upLoadPath + companyId + ".xls";
                    // ??
                    if (PoiCreateExcel.createExcel(errorFilePath, workerErrorList)) {
                        logger.debug("upLoadErrorListCreateSuccess!");
                        String destPath = request.getLocalAddr() + ":" + request.getLocalPort()
                                + request.getContextPath();
                        // ?
                        request.setAttribute("errorFilePath", "http://" + destPath + "/" + upload + "/"
                                + workerFolder + "/" + companyId + ".xls");//
                    } else {
                        logger.error("upLoadErrorListCreateError");
                        request.setAttribute("errorInfo", CREATEERRORFILE);
                    }
                }
                // 
                f.delete();

                // int totalLength = wtService.getCountByCheck(null, userId,
                // null);
                // int succesLength = wtService.getCountByCheck(true, userId,
                // null);
                // int errorLength = totalLength - succesLength;
                int totalLength = 0;
                int succesLength = 0;
                int errorLength = 0;
                // ??
                if (workerErrorList != null) {
                    errorLength = workerErrorList.size();
                }
                // // ??
                if (list != null) {
                    totalLength = list.size();
                    succesLength = totalLength - errorLength;
                }
                request.setAttribute("totalLength", totalLength);// ?
                request.setAttribute("errorLength", errorLength);// ?
                request.setAttribute("succesLength", succesLength);// ??
                // request.setAttribute("workerCorrectList", workerCorrectList);
                // //?, ???
                // // ??
                request.setAttribute("errorInfo", "null");// ??
                request.setAttribute("companyId", companyId);// ??iD
                request.setAttribute("year", year);// 

                logger.debug("totalLength:{}", totalLength);// ?
                logger.debug("errorLength:{}", errorLength);// ?
                logger.debug("succesLength:{}", succesLength);// ??

                // ?
                list.clear();
                list = null;
                workerErrorList.clear();// ?
                workerErrorList = null;

            } catch (IllegalStateException e) {
                e.printStackTrace();
                logger.error("importWorkerError:{}", e.getMessage());
            } catch (IOException e) {
                logger.error("importWorkerError:{}", e.getMessage());
            }
        }

        // ??
        return new ModelAndView("basicInfo/worker_importInfo");
    }

    /**
     * ? ?????
     * 
     * @param param
     * @param request
     * @return
     */
    @RequestMapping(value = "/validate_workerHandicapCode")
    @ResponseBody
    public List<Map<String, String>> validate_companyOrganizationCode(
            @RequestParam(value = "workerIdCard") String workerIdCard, @RequestParam(value = "year") String year,
            HttpServletRequest request) {

        logger.debug("validate_workerHandicapCodeworkerIdCard:{},year:{}", workerIdCard, year);
        // ?  ??
        // 1.? ?????? 2.?? ?id?? 3.?
        logger.debug("validate_workerIdCardParams:{}", workerIdCard);
        return validateOrganizationCode(workerIdCard, year);
    }

    /**
     * ??
     * 
     * @param workerIdCard
     * @return
     */
    private List<Map<String, String>> validateOrganizationCode(String workerIdCard, String year) {
        logger.debug("validateOrganizationCode:{},year:{}", workerIdCard, year);
        try {
            List<Map<String, String>> list = new ArrayList<Map<String, String>>();
            Map<String, String> paramsMap = new HashMap<String, String>();
            Company company = workerService.retrieveCompanyByWorker(year, workerIdCard);
            // ? ?
            if (company != null) {
                paramsMap.put("type", "1");
                Map<String, String> companyMap = new HashMap<String, String>();
                companyMap.put("companyName", company.getCompanyName());
                companyMap.put("companyCode", company.getCompanyCode());
                companyMap.put("companyTaxCode", company.getCompanyTaxCode());
                list.add(paramsMap);
                list.add(companyMap);
                logger.debug("validate_workerHandicapCodeResult:{},company:{}",
                        "type:1??",
                        company.getCompanyName() + "  " + company.getCompanyCode());
                return list;
            } else {

                Worker w = workerService.getByWorkerIdCard(workerIdCard);
                logger.error("workerIdCard:{},obg:{}" + workerIdCard, w);
                // ????
                if (w != null) {
                    logger.debug("validateWorkerHandicapCodeResult:{}", "type:2?" + w.getWorkerName()
                            + "????");
                    paramsMap.put("type", "2");
                    paramsMap.put("workerId", w.getId().toString());
                    paramsMap.put("workerName", w.getWorkerName()); // ??
                    paramsMap.put("careerCard", w.getCareerCard()); // ??
                    paramsMap.put("phone", w.getPhone()); // ??
                    paramsMap.put("remark", w.getRemark()); // 
                    list.add(paramsMap);
                    return list;
                    // ??.
                } else {
                    logger.debug("validateWorkerHandicapCodeResult:{}", "type:3???");
                    paramsMap.put("type", "3");
                    list.add(paramsMap);
                    return list;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("{}", e.getMessage());

            return null;
        }

    }

    /**
     * ??
     * 
     * @param companyId
     * @param year
     * @param request
     * @return
     */
    @RequestMapping(value = "/determineimport", method = RequestMethod.POST)
    @ResponseBody
    public Boolean importworker1(@RequestParam(value = "companyId") Integer companyId,
            @RequestParam(value = "year") String year, HttpServletRequest request, HttpSession session) {
        // ?ID
        Integer userId = Integer.parseInt(session.getAttribute(Constants.USER_ID).toString());
        // ???
        int totalWorkers = wtService.getCountByCheck(true, userId);
        // 1K , 
        int circulationTimes = 1;
        if (totalWorkers != 1000) {
            circulationTimes = (totalWorkers / 1000) > 1 ? ((totalWorkers / 1000) + 1) : 1;
        }
        // , ??
        PaginationRecordsAndNumber<WorkerTemp, Number> workerTempList = null;
        WorkerTemp t = new WorkerTemp();
        t.setIsOk(true);
        t.setUserId(userId);
        boolean bl = true;
        for (int k = 0; k < circulationTimes; k++) {
            int page = k + 1; // 
            workerTempList = null;
            workerTempList = wtService.getPaginationRecords(t, page, 1000);
            if (workerTempList == null) {
                break;
            }
            if (workerTempList.getRecords() == null) {
                break;
            }
            if (workerTempList.getRecords().size() < 1) {
                break;
            }
            // ?1000????
            Iterator<WorkerTemp> iterator = workerTempList.getRecords().iterator();
            while (iterator.hasNext()) {
                WorkerTemp wt = iterator.next();
                // ?id, , ???
                if (wt.getPreId() != null && wt.getPreId() > 0) {
                    Worker w = workerService.getByPrimaryKey(wt.getPreId());
                    w.setWorkerName(wt.getWorkerName());
                    if (!workerService.update(w)) {
                        bl = false;
                    }
                    CompanyYearWorker cyw = new CompanyYearWorker();
                    cyw.setCompanyId(companyId);
                    cyw.setYear(year);
                    cyw.setCurrentJob(Constants.NOTYET);
                    cyw.setWorkerId(w.getId());
                    cyw.setUserId(userId);
                    if (!cywService.save(cyw)) {
                        bl = false;
                    }
                    continue;
                }
                // ?, ?worker, ???
                Worker worker = new Worker();
                worker.setWorkerName(wt.getWorkerName());
                worker.setWorkerGender(wt.getWorkerGender());
                worker.setWorkerBirth(wt.getWorkerBirth());
                worker.setWorkerBirthYear(wt.getWorkerBirthYear());
                worker.setWorkerIdCard(wt.getWorkerIdCard());
                worker.setWorkerHandicapCode(wt.getWorkerHandicapCode());
                worker.setWorkerHandicapLevel(new WorkerHandicapLevel(wt.getWorkerHandicapLevel()));
                worker.setWorkerHandicapType(new WorkerHandicapType(wt.getWorkerHandicapType()));
                worker.setRemark(wt.getRemark());
                worker.setUserId(userId);
                if (!workerService.save(worker, companyId, year)) {
                    bl = false;
                }
            }
        }
        return bl;
        // int start = 0;
        // boolean b = true;
        // logger.debug("importWorkerparamsCode:{},companyId:{},year:{}",
        // paramsCode, companyId, year);
        // try {
        // for (int i = 0; i < paramsCode.length; i++) {
        // // ??
        // String workerHandicapCode = paramsCode[i].toString();
        // // ??
        // String workerHandicapName = paramsName[i].toString();
        //
        // // ????
        // List<Map<String, String>> validateList = validateOrganizationCode(
        // workerHandicapCode.substring(0, 18), year);
        // Map<String, String> validateResult = validateList.get(0);
        //
        // // ? ?
        // if (StringUtils.equals(validateResult.get("type"), "1")) {
        // logger.error("importWorkerError:{}", "?");
        // b = false;
        // break;
        // }
        // // ????
        // if (StringUtils.equals(validateResult.get("type"), "2")) {
        // Worker workerUp = new Worker();
        // workerUp.setWorkerName(workerHandicapName);
        // workerUp.setWorkerHandicapCode(workerHandicapCode);
        // // ??
        // if (editWorkerUp(WorkerUtil.assembly(workerUp), companyId,
        // year)) {
        // logger.debug("impoerWorkerUp:{}", "success");
        // } else {
        // logger.error("importWorkerError:{}", "upData");
        // b = false;
        // break;
        // }
        // continue;
        // }
        // // ? ??
        // if (StringUtils.equals(validateResult.get("type"), "3")) {
        // Worker workerUp = new Worker();
        // workerUp.setWorkerName(workerHandicapName);
        // workerUp.setWorkerHandicapCode(workerHandicapCode);
        // // ? 
        // if (addWorker(WorkerUtil.assembly(workerUp), companyId,
        // year)) {
        // logger.debug("importWorkerAddResult:{}", "success");
        // } else {
        // logger.error("importWorkerError:{}", "save");
        // b = false;
        // break;
        // }
        // }
        // }
        // } catch (Exception e) {
        // e.printStackTrace();
        // logger.error("delete_worker{}", e.getMessage());
        // }
        // return b;
    }

}