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.TbSysOrganMapper;
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.twerp.hm.TbHsprCommunity;
import cn.com.countrygarden.bi.main.model.twerp.hm.TbSysOrgan;
import cn.com.countrygarden.bi.main.service.experience.WcxCustomerService;
import cn.com.countrygarden.bi.main.util.*;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
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 WcxCustomerServiceImpl implements WcxCustomerService {

    @Autowired
    WcxExperienceMapper wcxExperienceMapper;

    @Autowired
    TbSysOrganMapper tbSysOrganMapper;

    @Autowired
    TbHsprCommunityMapper tbHsprCommunityMapper;

    @Override
    public List<WcxEmployeesManage> queryPageList(Map<String,Object> params) throws Exception {

        log.info("1、getCustomerList接口请求参数："+ JSON.toJSONString(params));
        List<WcxEmployeesManage> list = wcxExperienceMapper.list(params);
        log.info("2、getCustomerList返回结果集："+JSON.toJSONString(list));

        return list;

    }

    @Override
    public int count(Map<String, Object> params) throws Exception {
        return wcxExperienceMapper.count(params);
    }

    @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.setOrganCode(dto.getOrganCode());
            manage.setOrganName(dto.getOrganName());
            manage.setCommId(dto.getCommId());
            manage.setCommName(dto.getCommName());
            manage.setClosingTime(dto.getClosingTime());
            manage.setCustomerTag(dto.getCustomerTag());
            manage.setKeyNote(dto.getKeyNote());
            manage.setEducation(dto.getEducation());
            manage.setMarriage(dto.getMarriage());
            manage.setIndustry(dto.getIndustry());
            manage.setOccupation(dto.getOccupation());
            manage.setHobby(dto.getHobby());
            manage.setEffective(dto.getEffective());
            manage.setStatus(manage.getStatus());
            manage.setTygGradeId(dto.getTygGradeId());
            manage.setIdentification("1");
            List<WcxEmployeesManage> isEmployee = wcxExperienceMapper.queryByPhone(dto.getPhone(),"1");
            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(),"0");
            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(),"1");

            if (EmptyUtils.isNotEmpty(isEmployee)){
                throw new Exception("添加的手机已存在,请重新输入");
            }
            //查询是否有员工数据，有则同步
            WcxEmployeesManage wcxEmployeesManage=null;
            List<WcxEmployeesManage> isEmployee2 = wcxExperienceMapper.queryByPhoneOrderByLastUpdate(dto.getPhone(),"0");
            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.setHiredate(dto.getHiredate());
            manage.setMpbs(dto.getMpbs());
            manage.setPositions(dto.getPositions());
            manage.setEducation(dto.getEducation());
            manage.setEffective(dto.getEffective());
            manage.setIdentification("1");
            manage.setEffective(dto.getEffective());
            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;
    }

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

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


    /**
     * @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();
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result importCustomers(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 organName = getDetail(detailList,0); //区域
                String commName = getDetail(detailList,1); //项目
                String closingTime = getDetail(detailList,2); //收楼时间
                String name = getDetail(detailList,3); //姓名
                String phone = getDetail(detailList,4); //电话
                String age = getDetail(detailList,5); //年龄
                String sex = getDetail(detailList,6); //性别
                String customerTag = getDetail(detailList,7);
                String keyNote = getDetail(detailList,8); //重点客户
                String effective = getDetail(detailList,9); //启用/未启用

                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(closingTime)){
                    if (!DateUtil.isLegalDate(closingTime)){
                        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(organName)){
                    TbSysOrgan tbSysOrgan = tbSysOrganMapper.findByOrganNameNew(organName);
                    if (EmptyUtils.isNotEmpty(tbSysOrgan)){
                        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 (EmptyUtils.isNotEmpty(hsprCommunity)){
                        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);
                }

                manage.setClosingTime(closingTime);
                manage.setCustomerTag(customerTag);
                manage.setKeyNote(keyNote);
                manage.setName(name);
                manage.setPhone(phone);
                manage.setAge(age);
                manage.setSex(sex);


                if ("启用".equals(effective)){
                    manage.setEffective("1");
                }else {
                    manage.setEffective("0");
                }
                manage.setIdentification("1"); //客户
                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(),"1");
                    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.setCustomerTag(manage.getCustomerTag());
                        wcxEmployeesManage.setClosingTime(manage.getClosingTime());
                        wcxEmployeesManage.setKeyNote(manage.getKeyNote());
                        wcxEmployeesManage.setSex(manage.getSex());
                        wcxEmployeesManage.setEffective(manage.getEffective());
                        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.batchSaveCustomer(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;
        }
    }

    @Override
    public WcxEmployeesManage selectByByOpenId(String openId, WxMpUser wxMpUser) {
        try{
            List<WcxEmployeesManage> wcxEmployeesManages = wcxExperienceMapper.selectByByOpenId(openId);
            for(int i=0;i<wcxEmployeesManages.size();i++){
                WcxEmployeesManage wcxEmployeesManage = wcxEmployeesManages.get(i);
                String opendId = wcxEmployeesManage.getOpendId();
                String phone = wcxEmployeesManage.getPhone();
                String accessToken = wcxEmployeesManage.getAccessToken();
                String s = genAccessToken(phone, opendId, "wx");
                if(!s.equals(accessToken)){
                    String headImgUrl = wxMpUser.getHeadImgUrl();
                    String nickname = wxMpUser.getNickname();
                    wcxEmployeesManage.setHeadImgurl(headImgUrl);
                    wcxEmployeesManage.setWxName(nickname);
                    wcxEmployeesManage.setAccessToken(s);
                    wcxExperienceMapper.updateAccessToken(wcxEmployeesManage);
                }
            }
            if(wcxEmployeesManages.size()>0){
                return wcxEmployeesManages.get(0);
            }
            return null;
        }catch(Exception e){
            e.printStackTrace();
           throw new RuntimeException(e.getMessage());
        }
    }

    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;
    }
    private String genAccessToken(String phone, String openId, String salt) {
        String accessToken = phone +"_"+openId +"_"+ salt;
        String hashAccessToken = MD5.GetMD5Code(accessToken).toUpperCase();
        return hashAccessToken;
    }
}
