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

import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.core.ResultCode;
import cn.com.countrygarden.bi.main.dao.experience.WcxExperienceMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.TbHsprCommunityMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.TbSysDepartmentMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.TbSysOrganMapper;
import cn.com.countrygarden.bi.main.dto.experience.WcxEmployeeDto;
import cn.com.countrygarden.bi.main.dto.experience.WcxEmployeeManageDto;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.experience.WcxEmployeesManage;
import cn.com.countrygarden.bi.main.model.experience.WcxEmployeesManageDto;
import cn.com.countrygarden.bi.main.model.experience.WcxPublishMessage;
import cn.com.countrygarden.bi.main.model.twerp.hm.TbHsprCommunity;
import cn.com.countrygarden.bi.main.model.twerp.hm.TbSysDepartment;
import cn.com.countrygarden.bi.main.model.twerp.hm.TbSysOrgan;
import cn.com.countrygarden.bi.main.service.experience.WcxExperienceService;
import cn.com.countrygarden.bi.main.util.*;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@Slf4j
@Service
public class WcxExperienceServiceImpl implements WcxExperienceService {

    @Autowired
    WcxExperienceMapper wcxExperienceMapper;

    @Autowired
    TbSysOrganMapper tbSysOrganMapper;

    @Autowired
    TbSysDepartmentMapper tbSysDepartmentMapper;

    @Autowired
    TbHsprCommunityMapper tbHsprCommunityMapper;


    @Override
    public WcxEmployeesManage queryById(Long id) throws Exception {
        return wcxExperienceMapper.queryById(id);
    }


    @Override
    public List<WcxPublishMessage> queryPublishList(String phone) throws Exception {
        return wcxExperienceMapper.queryPublishList(phone);
    }

    @Override
    public Result findSysDepartment() throws Exception {
        Result result = new Result();

        try {

            List<TbSysDepartment> departmentList = tbSysDepartmentMapper.findSysDepartment(null);
            return result.setResultCode(ResultCode.SUCCESS).setData(departmentList);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return result.setResultCode(ResultCode.FAIL).setResultMsg(e.getMessage()).setData(false);
        }

    }

    @Override
    public List<WcxEmployeesManage> queryPageList(Map<String,Object> params) throws Exception{
        log.info("1、getEmployeesList接口请求参数："+ JSON.toJSONString(params));
        List<WcxEmployeesManage> list = wcxExperienceMapper.list(params);
        log.info("2、getEmployeesList返回结果集："+JSON.toJSONString(list));

        return list;
    }

    @Override
    public List<WcxEmployeesManageDto> queryList(Map<String,Object> params) throws Exception{
        log.info("1、getEmployeesList接口请求参数："+ JSON.toJSONString(params));
        List<WcxEmployeesManageDto> list = wcxExperienceMapper.list2(params);
        log.info("2、getEmployeesList返回结果集："+JSON.toJSONString(list));
        return list;
    }
    @Override
    public int count(Map<String,Object> params) throws Exception {
        return wcxExperienceMapper.count(params);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int delete(Long id) {
        return wcxExperienceMapper.delete(id);
    }


    @Transactional
    @Override
    public int setEnable(WcxEmployeeDto dto) throws Exception {
        return wcxExperienceMapper.setEnable(dto.getEnabled(),dto.getId());
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public WcxEmployeesManage createOrUpdate(WcxEmployeeManageDto dto, AccessToken accessToken) throws Exception {


        WcxEmployeesManage manage = wcxExperienceMapper.queryById(dto.getId());
        if (EmptyUtils.isNotEmpty(manage)){
            manage.setId(manage.getId());
            manage.setUpdated(new Date());
            manage.setUpdater(EmptyUtils.isNotEmpty(accessToken)?accessToken.getUserCode():null);
            manage.setName(dto.getName());
            manage.setPhone(dto.getPhone());
            manage.setAge(dto.getAge());
            manage.setSex(dto.getSex());
            manage.setIdCard(dto.getIdCard());
            manage.setOrganCode(dto.getOrganCode());
            manage.setCommId(dto.getCommId());
            manage.setDepCode(dto.getDepCode());
            manage.setDepName(dto.getDepName());
            manage.setHiredate(dto.getHiredate());
            manage.setMpbs(dto.getMpbs());
            manage.setPositions(dto.getPositions());
            manage.setEducation(dto.getEducation());
            manage.setEffective(dto.getEffective());
            manage.setStatus(manage.getStatus());
            manage.setIdentification("0");
            manage.setTygGradeId(dto.getTygGradeId());
            List<WcxEmployeesManage> isEmployee = wcxExperienceMapper.queryByPhone(dto.getPhone(),"0");
            if(isEmployee.size()>0){
                for(int i=0;i<isEmployee.size();i++){
                    WcxEmployeesManage wcxEmployeesManage = isEmployee.get(i);
                    boolean equals = wcxEmployeesManage.getId().equals(manage.getId());
                    if(!equals){
                        throw new Exception("手机号码已存在,请重新输入");
                    }
                }
            }
            WcxEmployeesManage wcxEmployeesManage=null;
            List<WcxEmployeesManage> isEmployee2 = wcxExperienceMapper.queryByPhoneOrderByLastUpdate(dto.getPhone(),"1");
            if(isEmployee2.size() >0){
                wcxEmployeesManage = isEmployee2.get(0);
            }
            if(wcxEmployeesManage !=null  ){
                String opendId = wcxEmployeesManage.getOpendId();
                Integer account = wcxEmployeesManage.getAccount();
                Integer isFocusWx = wcxEmployeesManage.getIsFocusWx();
                String wxName = wcxEmployeesManage.getWxName();
                String tygCertificateNumber = wcxEmployeesManage.getTygCertificateNumber();
                String headImgurl = wcxEmployeesManage.getHeadImgurl();
                manage.setAccount(account);
                manage.setOpendId(opendId);
                manage.setIsFocusWx(isFocusWx);
                manage.setWxName(wxName);
                manage.setTygCertificateNumber(tygCertificateNumber);
                manage.setHeadImgurl(headImgurl);
            }
            wcxExperienceMapper.update(manage);
        }else {

            List<WcxEmployeesManage> isEmployee = wcxExperienceMapper.queryByPhone(dto.getPhone(),"0");

            if (EmptyUtils.isNotEmpty(isEmployee)){
                throw new Exception("添加的手机已存在,请重新输入");
            }
            //查询是否有员工数据，有则同步
            WcxEmployeesManage wcxEmployeesManage=null;
            List<WcxEmployeesManage> isEmployee2 = wcxExperienceMapper.queryByPhoneOrderByLastUpdate(dto.getPhone(),"1");
            if(isEmployee2.size() >0){
                wcxEmployeesManage = isEmployee2.get(0);
            }
            manage = new WcxEmployeesManage();
            BeanUtil.copyProperties(dto,manage);
            manage.setCreated(new Date());
            manage.setCreater(EmptyUtils.isNotEmpty(accessToken)?accessToken.getUserCode():null);
            manage.setUpdated(new Date());
            manage.setUpdater(EmptyUtils.isNotEmpty(accessToken)?accessToken.getUserCode():null);
            manage.setVersion(0L);
            manage.setDeleted(0);
            manage.setName(dto.getName());
            manage.setPhone(dto.getPhone());
            manage.setAge(dto.getAge());
            manage.setSex(dto.getSex());
            manage.setIdCard(dto.getIdCard());
            manage.setOrganCode(dto.getOrganCode());
            manage.setCommId(dto.getCommId());
            manage.setDepCode(dto.getDepCode());
            manage.setDepName(dto.getDepName());
            manage.setHiredate(dto.getHiredate());
            manage.setMpbs(dto.getMpbs());
            manage.setPositions(dto.getPositions());
            manage.setEducation(dto.getEducation());
            manage.setEffective(dto.getEffective());
            manage.setIdentification("0");
            manage.setStatus("0");
            if(wcxEmployeesManage !=null  ){
                String opendId = wcxEmployeesManage.getOpendId();
                Integer account = wcxEmployeesManage.getAccount();
                Integer isFocusWx = wcxEmployeesManage.getIsFocusWx();
                String wxName = wcxEmployeesManage.getWxName();
                String tygCertificateNumber = wcxEmployeesManage.getTygCertificateNumber();
                String headImgurl = wcxEmployeesManage.getHeadImgurl();
                manage.setAccount(account);
                manage.setOpendId(opendId);
                manage.setIsFocusWx(isFocusWx);
                manage.setWxName(wxName);
                manage.setTygCertificateNumber(tygCertificateNumber);
                manage.setHeadImgurl(headImgurl);
            }else{
                manage.setAccount(0);
                manage.setOpendId(null);
                manage.setIsFocusWx(1);
                manage.setWxName(null);
                manage.setTygCertificateNumber(null);
                manage.setHeadImgurl(null);
            }
            wcxExperienceMapper.save(manage);
        }
        return manage;
    }

    @Override
    public void downloadEmployeeTemplate(HttpServletRequest request, HttpServletResponse response) throws Exception {
        OutputStream output;
        Workbook workBook = null;
        String fileName =  File.separator + "employee.xlsx";
        workBook = getWorkbook(fileName);
        //导出
        exportExcel(response, workBook, "员工数据导入模板.xlsx");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result importEmployees(InputStream inputStream, String originalFilename,String fileType,AccessToken accessToken) throws Exception {

        Result result = new Result();

        try {

            List<WcxEmployeesManage> manageList = new ArrayList<WcxEmployeesManage>();
            List<List<String>> manageDetails = new ArrayList<List<String>>();
            if (".xls".equals(fileType)){
                manageDetails = ExcelUtils.readExcel(inputStream, 3);
            }else {
                manageDetails = ExcelUtils.readExcel(inputStream,3,0,null);
            }

            if (EmptyUtils.isEmpty(manageDetails)){
                result.setResultCode(ResultCode.FAIL).setResultMsg("导入模板数据为空,请检查！").setData(false);
                return result;
            }

            log.info("1、importEmployees 导入模板数据："+JSON.toJSONString(manageDetails));


            StringBuffer returnMsg = new StringBuffer();

            for (int i = 0;i < manageDetails.size();i++){
                List<String> detailList =manageDetails.get(i);
                WcxEmployeesManage manage = new WcxEmployeesManage();
                String rowNumDetail = String.valueOf(i + 4);

                String depName = getDetail(detailList,0); //总部/中心部门
                String organName =  getDetail(detailList,1); //区域
                String commName =  getDetail(detailList,2); //项目
                String name =  getDetail(detailList,3); //姓名
                String phone =  getDetail(detailList,4); //电话
                String age =  getDetail(detailList,5); //年龄
                String sex =  getDetail(detailList,6); //性别
                String hiredate =  getDetail(detailList,7); //入职时间
                String mpbs =  getDetail(detailList,8); //MPBS分类
                String positions =  getDetail(detailList,9); //职级
                String education =  getDetail(detailList,10); //学历
                String effective =  getDetail(detailList,11); //启用/未启用

                if (StringUtils.isBlank(name)){
                    returnMsg.append("员工用户管理列表 ||第" + rowNumDetail + "行【姓名不能为空】\r\n");
                }

                if (StringUtils.isBlank(phone)){
                    returnMsg.append("员工用户管理列表 ||第" + rowNumDetail + "行【电话不能为空】\r\n");
                }

                if (phone.length()!=11){
                    returnMsg.append("员工用户管理列表 ||第" + rowNumDetail + "行【手机号应为11位数】\r\n");
                }

                boolean isMatch = NumberUtil.isMobile(phone.replaceAll(" +",""));
                if (!isMatch){
                    returnMsg.append("员工用户管理列表 ||第" + rowNumDetail + "行【手机号" + phone + "是不合法】\r\n");
                }

                if (StringUtils.isNotBlank(age)){
                    Pattern pattern = Pattern.compile("[0-9]*");
                    if (!pattern.matcher(age).matches()){
                        returnMsg.append("员工用户管理列表 ||第" + rowNumDetail + "行【年龄不合法】\r\n");
                    }
                    if (age.length() > 3){
                        returnMsg.append("员工用户管理列表 ||第" + rowNumDetail + "行【年龄不合法】\r\n");
                    }
                }

                if (StringUtils.isNotBlank(hiredate)){
                    if (!DateUtil.isLegalDate(hiredate)){
                        returnMsg.append("员工用户管理列表 ||第" + rowNumDetail + "行【入职时间格式必须为“YYYY-MM-dd】\r\n");
                    }
                }

//                if (StringUtils.isNotBlank(StringUtils.trimToEmpty(sex))){
//                    if(!"女".equals(sex) || "男".equals(sex)){
//                        returnMsg.append("员工用户管理列表 ||第" + rowNumDetail + "行【性别输入有误】\r\n");
//                    }
//                }

                manage.setDeleted(0);
                manage.setVersion(0L);
                manage.setCreated(new Date());
                manage.setCreater(EmptyUtils.isNotEmpty(accessToken)?accessToken.getUserCode():null);
                manage.setUpdated(new Date());
                manage.setUpdater(EmptyUtils.isNotEmpty(accessToken)?accessToken.getUserCode():null);

                if (StringUtils.isNotBlank(depName)){
                    List<TbSysDepartment> tbSysDepartments = tbSysDepartmentMapper.findSysDepartment(depName);
                    if (EmptyUtils.isNotEmpty(tbSysDepartments)){
                        TbSysDepartment department = tbSysDepartments.get(0);
                        manage.setDepCode(department.getDepCode());
                        manage.setDepName(depName);
                    }else {
                        manage.setDepCode(null);
                        manage.setDepName(depName);
                        //returnMsg.append("员工用户管理列表 ||第" + rowNumDetail + "行【该总部/中心部门不存在,请检查】\r\n");
                    }
                }else{
                    manage.setDepCode(null);
                    manage.setDepName(null);
                }

                if (StringUtils.isNotBlank(organName)){
                    TbSysOrgan tbSysOrgan = tbSysOrganMapper.findByOrganNameNew(organName);
                    if (tbSysOrgan!=null){
                        manage.setOrganCode(tbSysOrgan.getOrganCode());
                        manage.setOrganName(organName);
                    }else {
                        manage.setOrganCode(null);
                        manage.setOrganName(organName);
                        //returnMsg.append("员工用户管理列表 ||第" + rowNumDetail + "行【区域不存在,请检查】\r\n");
                    }
                }else {
                    manage.setOrganCode(null);
                    manage.setOrganName(null);
                }


                if (StringUtils.isNotBlank(commName)){
                    TbHsprCommunity hsprCommunity = tbHsprCommunityMapper.findHSPRCommByName(commName);
                    if (hsprCommunity!=null){
                        manage.setCommId(hsprCommunity.getCommid());
                        manage.setCommName(commName);
                    }else {
                        manage.setCommId(null);
                        manage.setCommName(commName);
                        //returnMsg.append("员工用户管理列表 ||第" + rowNumDetail + "行【项目不存在,请检查】\r\n");
                    }
                }else {
                    manage.setCommId(null);
                    manage.setCommName(null);
                }

                if ("启用".equals(effective)){
                    manage.setEffective("1");
                }else {
                    manage.setEffective("0");
                }

                manage.setName(name);
                manage.setPhone(phone);
                manage.setAge(age);
                manage.setSex(sex);
                manage.setHiredate(hiredate);
                manage.setMpbs(mpbs);
                manage.setPositions(positions);
                manage.setEducation(education);
                manage.setIdentification("0"); //员工
                manage.setStatus("0");
                manageList.add(manage);
            }

            if(returnMsg.length()>0) {
                result.setResultCode(ResultCode.FAIL).setResultMsg(returnMsg.toString()).setData(false);
                return result;
            }

            List<WcxEmployeesManage> manages = new ArrayList<WcxEmployeesManage>();
            if (CollectionUtils.isNotEmpty(manageList)){

                for (WcxEmployeesManage manage : manageList){

                    List<WcxEmployeesManage> employeesManageList = wcxExperienceMapper.queryByPhone(manage.getPhone(),"0");
                    if (EmptyUtils.isNotEmpty(employeesManageList)){
                        WcxEmployeesManage employeesManage = employeesManageList.get(0);
                        WcxEmployeesManage wcxEmployeesManage = new WcxEmployeesManage();
                        BeanUtil.copyProperties(manage,wcxEmployeesManage);
                        wcxEmployeesManage.setId(employeesManage.getId());
                        wcxEmployeesManage.setVersion(employeesManage.getVersion()+1);
                        wcxEmployeesManage.setStatus(employeesManage.getStatus());
                        wcxEmployeesManage.setIsLogin(employeesManage.getIsLogin());
                        wcxEmployeesManage.setUpdater(accessToken.getUserCode());
                        wcxEmployeesManage.setUpdated(new Date());
                        wcxEmployeesManage.setEffective(manage.getEffective());
                        wcxEmployeesManage.setSex(manage.getSex());
                        wcxEmployeesManage.setDepCode(manage.getDepCode());
                        wcxEmployeesManage.setDepName(manage.getDepName());
                        wcxEmployeesManage.setOrganCode(manage.getOrganCode());
                        wcxEmployeesManage.setOrganName(manage.getOrganName());
                        wcxEmployeesManage.setCommId(manage.getCommId());
                        wcxEmployeesManage.setCommName(manage.getCommName());
                        wcxExperienceMapper.update(wcxEmployeesManage);
                    }else {
                        manages.add(manage);
                    }
                }

                if (manages!=null && manages.size()>0){
                    wcxExperienceMapper.batchSave(manages);
                }
            }

            return result.setResultCode(ResultCode.SUCCESS);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            result.setResultCode(ResultCode.FAIL).setResultMsg(e.getMessage()).setData(false);
            return result;
        }

    }

    /**
     * @Description: 获取工作簿
     * @Params: [fileName]
     * @return: org.apache.poi.ss.usermodel.Workbook
     * @Author: SignV
     * @Date: 2018/9/25
     */
    private Workbook getWorkbook(String fileName) {
        try {
            File file = ResourceUtils.getFile("classpath:excel" + File.separator + "experience" + File.separator + fileName);
            InputStream inputStream = new FileInputStream(file);
            // 获取模板
            return new XSSFWorkbook(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @Description: 导出EXCEL
     * @Params: [response, workBook, fileName]
     * @return: void
     * @Author: SignV
     * @Date: 2018/9/25
     */
    private void exportExcel(HttpServletResponse response, Workbook workBook, String fileName) {
        try {
            response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("gbk"), "ISO-8859-1"));
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            response.setContentType("application/vnd.ms-excel");
            OutputStream output = response.getOutputStream();
            workBook.write(output);
            output.flush();
            workBook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String getDetail(List<String> detailList,int index){
        String result = "";
        if (detailList.size() >index){
            result = "".equals(detailList.get(index).replace("-",""))?"":detailList.get(index);
        }
        return result;
    }
}
