package cn.com.countrygarden.bi.main.service.routine.impl;


import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.dao.routine.RoutineManagerMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.ManagerMapForErpMapper;
import cn.com.countrygarden.bi.main.dto.wcx.SelectTreeDTO;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.PageData;
import cn.com.countrygarden.bi.main.model.routine.RoutineManager;
import cn.com.countrygarden.bi.main.service.routine.IRoutineManagerService;
import cn.com.countrygarden.bi.main.util.ExcelCompanyDataUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Transactional
public class RoutineManagerServiceImpl implements IRoutineManagerService {

    @Autowired
    private RoutineManagerMapper routineManagerMapper;
    @Autowired
    private ManagerMapForErpMapper managerMapForErpMapper;

    @Override
    public Result selectList(RoutineManager routineManager, int size, int page) {
        String[] organCodeArr = {};
        if(StringUtils.isNotEmpty(routineManager.getOrganCode())){
            organCodeArr = routineManager.getOrganCode().split(",");
        }
        Page<Object> pageList = PageHelper.startPage(page, size);
        Condition condition=new Condition(RoutineManager.class);
        Example.Criteria criteria = condition.createCriteria();
//        if(StringUtils.isNotEmpty(routineManager.getOrganCode())){
//            criteria.andEqualTo("organCode",routineManager.getOrganCode());
//        }
        if(organCodeArr!=null&&organCodeArr.length>0){
            criteria.andIn("organCode",Arrays.asList(organCodeArr));
        }
        if(StringUtils.isNoneEmpty(routineManager.getOrganName())){
            criteria.andLike("organName","%"+routineManager.getOrganName()+"%");
        }
        if(routineManager.getYear() != null){
            criteria.andEqualTo("year",routineManager.getYear());
        }
        if(routineManager.getMonth() != null){
            criteria.andEqualTo("month",routineManager.getMonth());
        }
        condition.orderBy("sort").asc();
        routineManagerMapper.selectByCondition(condition);
        PageData data=new PageData(pageList);
        data.setData(pageList.getResult());
        return Response.response(data);
    }

    @Override
    public Result queryById(Integer id) {
        return Response.response(routineManagerMapper.selectByPrimaryKey(id));
    }

    @Override
    public Result addOrUpdate(RoutineManager routineManager, AccessToken accessToken) {

        if(routineManager.getId() != null){
//            编辑
            Condition condition = new Condition(RoutineManager.class);
            condition.createCriteria().andEqualTo("organName", routineManager.getOrganName())
                    .andEqualTo("year", routineManager.getYear())
                    .andEqualTo("month",routineManager.getMonth())
                    .andEqualTo("enable",0)
                    .andNotEqualTo("id",routineManager.getId());
            int routineNumbers = routineManagerMapper.selectCountByCondition(condition);
            if(routineNumbers > 0 ){
                return Response.responseFail("该月份下已有相同区域数据，请检查一下数据是否有误。");
            }
            routineManager.setUpdateBy(accessToken.getUserCode());
            routineManager.setUpdateDate(new Date());
            if("合计".equals(routineManager.getOrganName())){
                routineManager.setOrganCode("");
            }
            int update = routineManagerMapper.updateByPrimaryKeySelective(routineManager);
            return update > 0 ? Response.response() : Response.responseFail("编辑数据，请检查填写是否有误。");
        }else{
            Condition condition = new Condition(RoutineManager.class);
            condition.createCriteria().andEqualTo("organName", routineManager.getOrganName())
                    .andEqualTo("year", routineManager.getYear())
                    .andEqualTo("month",routineManager.getMonth())
                    .andEqualTo("enable",0);
            int routineNumbers = routineManagerMapper.selectCountByCondition(condition);
            if(routineNumbers > 0 ){
                return Response.responseFail("该月份下已有相同区域数据，请检查一下数据是否有误。");
            }
//            获取最大排序
            int sort = routineManagerMapper.selecMaxSort(routineManager.getYear(),routineManager.getMonth());
//            新增
            routineManager.setEnable(0);
            routineManager.setSort(++sort);
            routineManager.setCreateBy(accessToken.getUserCode());
            routineManager.setCreateDate(new Date());
            routineManager.setUpdateBy(accessToken.getUserCode());
            routineManager.setUpdateDate(new Date());
            int insert = routineManagerMapper.insert(routineManager);
            return insert > 0 ? Response.response() : Response.responseFail("编辑数据，请检查填写是否有误。");
        }
    }

    @Override
    public Result del(Integer id) {
        return Response.response(routineManagerMapper.deleteByPrimaryKey(Long.valueOf(id)));
    }

    @Override
    public Result queryOrganTree() {
        List<SelectTreeDTO> tree = managerMapForErpMapper.selectOrganTree();
        return Response.response(tree);
    }

    /**
     * 导出数据
     * @param routineManager
     * @return
     */
    @Override
    public List<RoutineManager> selectExcelData(RoutineManager routineManager) {
        return  routineManagerMapper.selectExcelData(routineManager.getOrganName(),routineManager.getYear(),routineManager.getMonth());
    }

    @Override
    public Map<String, Object> importExcel(MultipartFile excelFile, RoutineManager routineManager, AccessToken token) {
//        不含特殊字符的正则
        String reg = "[A-Za-z0-9/\\u4e00-\\u9fa5]+";

        //错误信息excel下载信息
        String errorUrl = "";
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String originalFilename = excelFile.getOriginalFilename();
        if(originalFilename==null){
            resultMap.put("returnCode", 500);
            resultMap.put("returnMsg", "请检查文件名！");
            return resultMap;
        }
        String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
        boolean contains = Arrays.asList(new String[]{"xls", "xlsx"}).contains(fileSuffix);
        if (contains == false) {
            resultMap.put("returnCode", 500);
            resultMap.put("returnMsg", "文件类型不符！");
            return resultMap;
        }
        List<ArrayList<String>> importData = null;
        try {
            importData = ExcelCompanyDataUtil.importData2(excelFile);
        }catch (Exception e){
            e.printStackTrace();
            resultMap.put("returnCode", 500);
            resultMap.put("returnMsg", "导入失败，请检查您的文件！");
            return resultMap;
        }
        if (importData.isEmpty()) {
            resultMap.put("returnCode", 500);
            resultMap.put("returnMsg", "导入文件数据为空，请检查！");
            return resultMap;
        }
        if (importData.size() < 4) {
            resultMap.put("returnCode", 500);
            resultMap.put("returnMsg", "请检查导入文件是否有数据！");
            return resultMap;
        }
        //去掉title
        importData.remove(0);
        importData.remove(0);
        importData.remove(0);
        importData.remove(0);
        if (importData.isEmpty()) {
            resultMap.put("returnCode", 500);
            resultMap.put("returnMsg", "导入文件数据数据行为空，请检查！");
            return resultMap;
        }
        //所有数据
        List<RoutineManager> allList = new ArrayList<>();
        //错误行
        List<ArrayList<String>> errorList = new ArrayList<>();
        Map<Integer, ArrayList<String>> dataMap = new HashMap<>();
        //错误标记  如果有一条数据错误  则不导入数据
        boolean remark=true;
        for (int i = 0; i < importData.size(); i++) {
            ArrayList<String> rowDatas = importData.get(i);
            dataMap.put(i + 1, rowDatas);
        }
        if (remark) {
            int index = 4;
            int num = 1;
            for (Integer key : dataMap.keySet()) {
                index++;
                RoutineManager routine = new RoutineManager();
//                if(StringUtils.isBlank(dataMap.get(key).get(0))&&!"合计".equals(dataMap.get(key).get(1))){
//                    resultMap.put("returnCode", 500);
//                    resultMap.put("returnMsg", dataMap.get(key).get(1)+"区域的区域编号数据不能为空，请检查！");
//                    return resultMap;
//                }
//                routine.setOrganCode(dataMap.get(key).get(0));
                if(StringUtils.isNotBlank(dataMap.get(key).get(1))){
//                    if(!dataMap.get(key).get(1).matches("[A-Za-z0-9/\\u4e00-\\u9fa5]+")){
//                        resultMap.put("returnCode", 500);
//                        resultMap.put("returnMsg", dataMap.get(key).get(1)+"区域名称数据不能有特殊字符，请检查！");
//                        return resultMap;
//                    };
                    routine.setOrganName(dataMap.get(key).get(1));
                }else{
                    resultMap.put("returnCode", 500);
                    resultMap.put("returnMsg", "第"+index+"行区域名称数据不能为空，请检查！");
                    return resultMap;
                }

                routine.setOrderNumber(dataMap.get(key).get(0));

                resultMap = checkData(dataMap.get(key).get(1),dataMap.get(key).get(2),2,index);
                if("500".equals(resultMap.get("returnCode")))return resultMap;
                routine.setOnjobNumber(StringUtils.isNotEmpty(dataMap.get(key).get(2))?Integer.valueOf(dataMap.get(key).get(2)):0);

                resultMap = checkData(dataMap.get(key).get(1),dataMap.get(key).get(3),3, index);
                if("500".equals(resultMap.get("returnCode")))return resultMap;
                routine.setHightManager(StringUtils.isNotEmpty(dataMap.get(key).get(3))?Integer.valueOf(dataMap.get(key).get(3)):0);

                resultMap = checkData(dataMap.get(key).get(1),dataMap.get(key).get(4),4, index);
                if("500".equals(resultMap.get("returnCode")))return resultMap;
                routine.setManager(StringUtils.isNotEmpty(dataMap.get(key).get(4))?Integer.valueOf(dataMap.get(key).get(4)):0);

                resultMap = checkData(dataMap.get(key).get(1),dataMap.get(key).get(5),5, index);
                if("500".equals(resultMap.get("returnCode")))return resultMap;
                routine.setDeputyManager(StringUtils.isNotEmpty(dataMap.get(key).get(5))?Integer.valueOf(dataMap.get(key).get(5)):0);

                resultMap = checkData(dataMap.get(key).get(1),dataMap.get(key).get(6),6, index);
                if("500".equals(resultMap.get("returnCode")))return resultMap;
                routine.setSupervisor(StringUtils.isNotEmpty(dataMap.get(key).get(6))?Integer.valueOf(dataMap.get(key).get(6)):0);

                resultMap = checkData(dataMap.get(key).get(1),dataMap.get(key).get(7),7, index);
                if("500".equals(resultMap.get("returnCode")))return resultMap;
                routine.setDeputySupervisor(StringUtils.isNotEmpty(dataMap.get(key).get(7))?Integer.valueOf(dataMap.get(key).get(7)):0);

                resultMap = checkData(dataMap.get(key).get(1),dataMap.get(key).get(8),8, index);
                if("500".equals(resultMap.get("returnCode")))return resultMap;
                routine.setTrainee(StringUtils.isNotEmpty(dataMap.get(key).get(8))?Integer.valueOf(dataMap.get(key).get(8)):0);

                resultMap = checkData(dataMap.get(key).get(1),dataMap.get(key).get(9),9, index);
                if("500".equals(resultMap.get("returnCode")))return resultMap;
                routine.setFenghuangManager(StringUtils.isNotEmpty(dataMap.get(key).get(9))?Integer.valueOf(dataMap.get(key).get(9)):0);

                resultMap = checkData(dataMap.get(key).get(1),dataMap.get(key).get(10),10, index);
                if("500".equals(resultMap.get("returnCode")))return resultMap;
                routine.setMiddleSchool(StringUtils.isNotEmpty(dataMap.get(key).get(10))?Integer.valueOf(dataMap.get(key).get(10)):0);

                resultMap = checkData(dataMap.get(key).get(1),dataMap.get(key).get(11),11, index);
                if("500".equals(resultMap.get("returnCode")))return resultMap;
                routine.setHighSchool(StringUtils.isNotEmpty(dataMap.get(key).get(11))?Integer.valueOf(dataMap.get(key).get(11)):0);

                resultMap = checkData(dataMap.get(key).get(1),dataMap.get(key).get(12),12, index);
                if("500".equals(resultMap.get("returnCode")))return resultMap;
                routine.setCollege(StringUtils.isNotEmpty(dataMap.get(key).get(12))?Integer.valueOf(dataMap.get(key).get(12)):0);

                resultMap = checkData(dataMap.get(key).get(1),dataMap.get(key).get(13),13, index);
                if("500".equals(resultMap.get("returnCode")))return resultMap;
                routine.setUndergraduateCollege(StringUtils.isNotEmpty(dataMap.get(key).get(13))?Integer.valueOf(dataMap.get(key).get(13)):0);

                resultMap = checkData(dataMap.get(key).get(1),dataMap.get(key).get(14),14, index);
                if("500".equals(resultMap.get("returnCode")))return resultMap;
                routine.setAfter60(StringUtils.isNotEmpty(dataMap.get(key).get(14))?Integer.valueOf(dataMap.get(key).get(14)):0);

                resultMap = checkData(dataMap.get(key).get(1),dataMap.get(key).get(15),15, index);
                if("500".equals(resultMap.get("returnCode")))return resultMap;
                routine.setAfter70(StringUtils.isNotEmpty(dataMap.get(key).get(15))?Integer.valueOf(dataMap.get(key).get(15)):0);

                resultMap = checkData(dataMap.get(key).get(1),dataMap.get(key).get(16),16, index);
                if("500".equals(resultMap.get("returnCode")))return resultMap;
                routine.setAfter80(StringUtils.isNotEmpty(dataMap.get(key).get(16))?Integer.valueOf(dataMap.get(key).get(16)):0);

                resultMap = checkData(dataMap.get(key).get(1),dataMap.get(key).get(17),17, index);
                if("500".equals(resultMap.get("returnCode")))return resultMap;
                routine.setAfter90(StringUtils.isNotEmpty(dataMap.get(key).get(17))?Integer.valueOf(dataMap.get(key).get(17)):0);

                resultMap = checkData(dataMap.get(key).get(1),dataMap.get(key).get(18),18, index);
                if("500".equals(resultMap.get("returnCode")))return resultMap;
                routine.setAfter00(StringUtils.isNotEmpty(dataMap.get(key).get(18))||"-".equals(dataMap.get(key).get(18))?Integer.valueOf(dataMap.get(key).get(18)):0);

                resultMap = checkData(dataMap.get(key).get(1),dataMap.get(key).get(19),19, index);
                if("500".equals(resultMap.get("returnCode")))return resultMap;
                routine.setDimissionNumberMonth(StringUtils.isNotEmpty(dataMap.get(key).get(19))||"-".equals(dataMap.get(key).get(19))?Integer.valueOf(dataMap.get(key).get(19)):0);

//                流失率
                String dimissionNumberTotal = "0.00%";
                if(StringUtils.isNotEmpty(dataMap.get(key).get(20))){
                    try{
                        String str = new BigDecimal(dataMap.get(key).get(20)).toPlainString();
                        BigDecimal bd = new BigDecimal(str).multiply(new BigDecimal(100));
                        bd = bd.setScale(2, RoundingMode.HALF_UP);
                        dimissionNumberTotal = bd+"%";
                    }catch (Exception e){
                        dimissionNumberTotal = dataMap.get(key).get(20);
                    }
                }
                routine.setDimissionNumberTotal(dimissionNumberTotal);

                routine.setYear(routineManager.getYear());
                routine.setMonth(routineManager.getMonth());
                routine.setEnable(0);

                resultMap = checkData(dataMap.get(key).get(1),dataMap.get(key).get(21),21, index);
                if("500".equals(resultMap.get("returnCode")))return resultMap;
                routine.setWastageRateMonth(StringUtils.isNotEmpty(dataMap.get(key).get(21))||"-".equals(dataMap.get(key).get(21))?dataMap.get(key).get(21):"0");

//                成才率
                String wastageRateTotal = "0.00%";
                if(StringUtils.isNotEmpty(dataMap.get(key).get(22))){
                    try{
                        String str = new BigDecimal(dataMap.get(key).get(22)).toPlainString();
                        BigDecimal bd = new BigDecimal(str).multiply(new BigDecimal(100));
                        bd = bd.setScale(2, RoundingMode.HALF_UP);
                        wastageRateTotal = bd+"%";
                    }catch (Exception e){
                        wastageRateTotal = dataMap.get(key).get(20);
                    }
                }
                routine.setWastageRateTotal(wastageRateTotal);

                routine.setSort(num);
                allList.add(routine);
                num++;
            }
            try {
                for(RoutineManager r : allList){
                    addData(r,token);
                }
            } catch (Exception e) {
                resultMap.put("returnCode", 500);
                resultMap.put("returnMsg", "模版数据导入错误！");
                return resultMap;
            }
        }
        resultMap.put("returnCode", 0);
        resultMap.put("returnMsg", "数据上传成功！");
        return resultMap;
    }

    private Result addData(RoutineManager routine, AccessToken token) {
        int num = 0;
        if(routine!=null){
            if(StringUtils.isBlank(routine.getOrganName())) new Result().setData("操作失败");
            routineManagerMapper.deleteOne(routine.getOrganName(),routine.getYear(),routine.getMonth());
            routine.setCreateBy(token.getUserCode());
            routine.setCreateDate(new Date());
            num = routineManagerMapper.insert(routine);

        }
        return new Result().setData(num>0 ? "操作成功！" : "操作失败");
    }

    private Map<String, Object> checkData(String organName, String str, int i, int index) {
        //        数字正则
        String num = "[0-9]+";
        Map<String, Object> resultMap = new HashMap<String, Object>();
//        为空，则默认为0
        if(StringUtils.isBlank(str)){
            resultMap.put("returnCode", 0);
            return resultMap;
        }

        if (!str.matches(num)){
            resultMap.put("returnCode", "500");
            switch (i){
                case 2:
                   resultMap.put("returnMsg", "第"+index+"行的在职人数数据不是整数，请检查！");
                   break;
                case 3:
                   resultMap.put("returnMsg", "第"+index+"行的高级经理数据不是整数，请检查！");
                   break;
                case 4:
                   resultMap.put("returnMsg", "第"+index+"行的经理数据不是整数，请检查！");
                   break;
                case 5:
                   resultMap.put("returnMsg", "第"+index+"行的副经理数据不是整数，请检查！");
                   break;
                case 6:
                   resultMap.put("returnMsg", "第"+index+"行的主管数据不是整数，请检查！");
                   break;
                case 7:
                   resultMap.put("returnMsg", "第"+index+"行的副主管数据不是整数，请检查！");
                   break;
                case 8:
                   resultMap.put("returnMsg", "第"+index+"行的见习数据不是整数，请检查！");
                   break;
                case 9:
                   resultMap.put("returnMsg", "第"+index+"行的凤凰管家数据不是整数，请检查！");
                   break;
                case 10:
                   resultMap.put("returnMsg", "第"+index+"行的初中及以下数据不是整数，请检查！");
                   break;
                case 11:
                   resultMap.put("returnMsg", "第"+index+"行的高中/中专/技校数据不是整数，请检查！");
                   break;
                case 12:
                   resultMap.put("returnMsg", "第"+index+"行的大专数据不是整数，请检查！");
                   break;
                case 13:
                   resultMap.put("returnMsg", "第"+index+"行的本科及以上数据不是整数，请检查！");
                   break;
                case 14:
                   resultMap.put("returnMsg", "第"+index+"行的60后数据不是整数，请检查！");
                   break;
                case 15:
                   resultMap.put("returnMsg", "第"+index+"行的70后数据不是整数，请检查！");
                   break;
                case 16:
                   resultMap.put("returnMsg", "第"+index+"行的80后数据不是整数，请检查！");
                   break;
                case 17:
                   resultMap.put("returnMsg", "第"+index+"行的90后数据不是整数，请检查！");
                   break;
                case 18:
                   resultMap.put("returnMsg", "第"+index+"行的00后数据不是整数，请检查！");
                   break;
                case 19:
                   resultMap.put("returnMsg", "第"+index+"行的流失人数数据不是整数，请检查！");
                   break;
                case 20:
                   resultMap.put("returnMsg", "第"+index+"行的流失率数据不是数字，请检查！");
                   break;
                case 21:
                   resultMap.put("returnMsg", "第"+index+"行的成才人数数据不是整数，请检查！");
                   break;
            }
            return resultMap;
        }else {
            resultMap.put("returnCode", 0);
            return resultMap;
        }
    }

    /**
     * 判断字符串是否是数字
     * @param str
     * @return
     */
    private boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("^[0-9]+(.[0-9]+)?$");
        Matcher isNum = pattern.matcher(str);
        if( !isNum.matches() ){
            return false;
        }
        return true;
    }

}
