package com.bonus.boot.manager.basic.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.bonus.boot.manager.basic.dao.PersonnelLibraryDao;
import com.bonus.boot.manager.basic.entity.PersonnelLibraryBean;
import com.bonus.boot.manager.basic.entity.PersonnelReservationBean;
import com.bonus.boot.manager.basic.service.ImportExcelService;
import com.bonus.boot.manager.manager.model.SysType;
import com.bonus.boot.manager.manager.utils.DateTimeHelper;
import com.bonus.boot.manager.manager.utils.StringHelper;
import com.bonus.boot.manager.manager.utils.UserUtil;
import com.bonus.boot.manager.physical.entity.CountImportBean;
import com.bonus.boot.manager.physical.entity.NegativeResultBean;
import com.bonus.boot.manager.positive.dao.NegativeResultDao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 *
 *
 * @author makejava
 * @since 2023-16-19 13:57:46
 */
@Service("ImportExcelService")
public class ImportExcelServiceImpl implements ImportExcelService {
    static final String MOBILE_RULE = "^1[3-9]\\d{9}$";
    @Resource
    private PersonnelLibraryDao dao;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    @Resource
    private NegativeResultDao negativeResultDao;


    @Override
    public String saveExcelInfo(List<JSONObject> lstObj) {
        PersonnelLibraryBean  bean=new PersonnelLibraryBean();
        String res = "";
        int team =1;
        int i = 1;
        String personName = "";
        String phone = "";
        String idNumber = "";
        String department = "";
        String personType = "";
        String specJob = "";
        String sex = "";
        try {
            if (lstObj != null && lstObj.size() > 0) {
                for (JSONObject obj : lstObj) {
                    i++;
                    personName = obj.getString("personName").trim();
                    phone = obj.getString("phone").trim();
                    idNumber = obj.getString("idNumber").trim();
                    department = obj.getString("department").trim();
//                    specJob = obj.getString("specJob").trim();
                    //通过部门名称寻找部门id
                    if (StringHelper.isEmpty(idNumber) ||  "0.0".equals(idNumber.trim())) {
                        res += "第" + i + "行" + personName + "行身份证为空;";
                        team = 2;
                    } else if (idNumber.length() != 18) {
                        res += "第" + i + "行" + personName + "行身份证格式错误;";
                        team = 2;
                    }else {
                        sex=getSexByIdcard(idNumber);
                        bean.setSex(sex);
                        int age = countAge(idNumber);
                        bean.setAge(age);
                    }
                    if(!department.isEmpty()) {
                        String departmentName = dao.getdepartmentName(department);
                        if (StringHelper.isEmpty(departmentName) ||  "0.0".equals(departmentName.trim())) {
                            team = 2;
                            res += "第" + i + "行" + personName + "部门名称有误，请检查";
                            System.out.println(res);
                        } else {
                            bean.setDepartment(departmentName + "");
                        }
                    }
//                    if(!"".equals(specJob)) {
//                        String specJobid = dao.getspecJobName(specJob);
//                        if (StringUtils.isEmpty(specJobid )) {
//                            team = 2;
//                            res += "第" + i + personName + "特殊岗位有误，请检查";
//                            System.out.println(res);
//                            break;
//                        } else {
//                            bean.setSpecialPost(specJobid+"");
//                        }
//                    }
                    personType = obj.getString("personType");
                    String peronid= ChangepersonType(personType);
                    if(!peronid.equals("0")){
                        bean.setPersonType(peronid);
                    }else{
                        System.out.println(res);
                        res += "第" + i + "行" + personName+"用工形式有误，请检查" ;
                        System.out.println(res);
                    }

                    //身份证校验

                    bean.setPersonName(personName);
                    bean.setPhone(phone);
                    bean.setIdNumber(idNumber);
                    bean.setPassword(passwordEncoder.encode("YNsbd@123456"));
                    if(bean.getSpecialPost()=="" ||bean.getSpecialPost()==null){
                        bean.setSpecialPost(0+"");
                    }
                    if(team!=2){
                    //    查询通过身份证去查询
                        int sum = dao.getinfoByidcard(phone);
                        if(sum>0){
                            dao.updatephyInfo(bean);
                        }  else{
                            dao.updatePersonExport(bean);
                        }
                        res = "导入成功";
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

    @Override
    public String savenegativeResult(List<JSONObject> lstObj) {
        StringBuffer res = new StringBuffer();
        List<SysType> getIllnessType = negativeResultDao.getIllnessType(null);

        List<SysType> abnormalStatisticsList = new ArrayList<>();
        String dataYear = DateTimeHelper.getYear(new Date());
        try {
            if (lstObj != null && lstObj.size() > 0) {
                for (JSONObject obj : lstObj) {
                    NegativeResultBean bean  =  new NegativeResultBean();
                    bean.setPhyNumber(obj.getString("phyNumber"));
                    bean.setPhyName(obj.getString("phyName"));
                    bean.setProfilePosition(obj.getString("profilePosition"));
                    bean.setPhySex(obj.getString("phySex"));
                    bean.setPhyOle(obj.getString("phyOle"));
                    bean.setPhyUnit(obj.getString("phyUnit"));
                    bean.setTeamId(obj.getString("teamId"));
                    bean.setTeamName(obj.getString("teamName"));
                    bean.setTeamDepart(obj.getString("teamDepart"));
                    bean.setSignDate(obj.getString("signDate"));
                    bean.setMasResult(obj.getString("masResult"));
                    String concWord = changeView(obj.getString("concWord"));
                    bean.setConcWord(concWord);
                    bean.setGenerRecom(obj.getString("generRecom"));
                    bean.setDataYear(DateTimeHelper.getYear(new Date()));
                    bean.setHospitalId(UserUtil.getLoginUser().getHospitalId());
                    bean.setId(UUID.randomUUID().toString().replace("-",""));
                    if(StringHelper.isEmpty(obj.getString("phyNumber"))
                            ||StringHelper.isEmpty(obj.getString("phyName"))
                            ||StringHelper.isEmpty(obj.getString("profilePosition"))
                            ||StringHelper.isEmpty(obj.getString("phySex"))
                            ||StringHelper.isEmpty(obj.getString("phyOle"))
                            ||StringHelper.isEmpty(obj.getString("phyUnit"))
                            ||StringHelper.isEmpty(obj.getString("teamId"))
                            ||StringHelper.isEmpty(obj.getString("teamName"))
                            ||StringHelper.isEmpty(obj.getString("teamDepart"))
                            ||StringHelper.isEmpty(obj.getString("signDate"))
                            ||containsChineseCharacters(obj.getString("signDate"))
                            ||StringHelper.isEmpty(obj.getString("masResult"))
                            ||StringHelper.isEmpty(obj.getString("concWord"))
                            ||StringHelper.isEmpty(obj.getString("generRecom"))
                            ||((obj.getString("signDate")+"").indexOf("1900")!=-1) || ((obj.getString("signDate")+"").indexOf("1899")!=-1)){
                        res.append("行号："+obj.getString("id")+"数据，"+obj.getString("phyName")+"数据异常或为空，导入失败！<br>");
                        continue;
                    }

                    CountImportBean b = new CountImportBean();
                    b.setOld(Integer.parseInt(obj.getString("phyOle")));
                    b.setSex(obj.getString("phySex"));
                    b.setName(obj.getString("phyName"));
                    b.setPhyNumber(obj.getString("phyNumber"));
                    b.setTeamName(obj.getString("teamName"));
                    b.setTeamId(obj.getString("teamId"));
                    b.setDataYear(dataYear);
                    b.setHospitalId(UserUtil.getLoginUser().getHospitalId());
                    b.setId(UUID.randomUUID().toString().replace("-",""));
                    for (SysType bb : getIllnessType) {
                        String[] arrays = bb.getIllnessKeyword().split(";");
                        String illId = bb.getId()+"";
                        String illType = bb.getIllnessType();
                        b.setIllnessType(illId);
                        b.setIllnessName(illType);
                        System.err.println("illId="+illId);
                        System.err.println("illType="+illType);
                        for (String aa : arrays){
                            boolean result = concWord.contains(aa);
                            System.err.println("aa="+aa);
                            System.err.println("result="+result);
                            if(result){
                                negativeResultDao.addCountResultMessage(b);
                                continue;
                            }
                        }
                    }

//                    int sum = negativeResultDao.getMessageByPhyNumber(bean);
//                    if(sum>0){//修改
//                        int num = negativeResultDao.updateDataInfo(bean);
//                        if(num <=0){
//                            res.append("第"+obj.getString("id")+"数据，"+obj.getString("phyName")+"修改失败！'\\n");
//                        }
//                    }else {//新增
//                        int num = negativeResultDao.addDataInfo(bean);
//                        if(num <=0){
//                            res.append("第"+obj.getString("id")+"数据，"+obj.getString("phyName")+"新增失败！'\\n");
//                        }
//                    }
                    int num = negativeResultDao.addDataInfo(bean);
                    if(num <=0){
                        res.append("第"+obj.getString("id")+"数据，"+obj.getString("phyName")+"新增失败！'\\n");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res.toString().length()<=0?"导入成功":res.toString();
    }

    @Override
    public String reservation(List<JSONObject> lstObj) {
        PersonnelReservationBean bean=new PersonnelReservationBean();
        String res = "";
        int team =1;
        int i = 0;
        String personName = "";
        String phone = "";
        String idNumber = "";
        String department = "";
        String hospital = "";
        String sex = "";
        String setMeal = "";
        try {
            if (lstObj != null && lstObj.size() > 0) {
                for (JSONObject obj : lstObj) {
                    i++;
                    personName = obj.getString("personName").trim();
                    idNumber = obj.getString("idNumber").trim();
                    sex = obj.getString("sex").trim();

                    department = obj.getString("department").trim();
                    hospital = obj.getString("hospital").trim();
                    setMeal = obj.getString("setMeal").trim();
                    phone = obj.getString("phone").trim();


                    //判断姓名为空
                    if(StringHelper.isEmpty(personName)){
                        res += "第" + i + "行姓名为空;";
                    }
                    bean.setPersonName(personName);

                    //判断身份证为空
                    if (StringHelper.isEmpty(idNumber) ||  "0.0".equals(idNumber.trim())) {
                        res += "第" + i + "行" + personName + "行身份证为空;";
                        team = 2;
                    } else if (idNumber.length() != 18) {
                        res += "第" + i + "行" + personName + "行身份证格式错误;";
                        team = 2;
                    }
                    bean.setIdNumber(idNumber);

                    //判断性别为空
                    if (StringHelper.isEmpty(sex) ) {
                        res += "第" + i + "行" + personName + "行性别为空;";
                        team = 2;
                    }else {
                        String a=getSexByIdcard(idNumber);
                        String b= "";
                        if(sex.equals("男")){
                            b="0";
                        }else{
                            b="1";
                        }
                        if(!a.equals(b)){
                            res += "第" + i + "行" + personName + "行身份证与性别不匹配;";
                        }else {
                            bean.setSex(b);
                        }
                    }

                    //判断部门名称为空
                    if(!department.isEmpty()) {
                        String departmentName = dao.getdepartmentName(department);
                        if (StringHelper.isEmpty(departmentName) ||  "0.0".equals(departmentName.trim())) {
                            team = 2;
                            res += "第" + i + "行" + personName + "部门名称有误，请检查";
                            System.out.println(res);
                        } else {
                            bean.setDepartment(departmentName + "");
                        }
                    }else{
                        team = 2;
                        res += "第" + i + "行" + personName + "部门名称为空";
                    }

                    //判断医院名称为空
                    if (StringHelper.isEmpty(hospital) ) {
                        res += "第" + i + "行" + personName + "行医院名称为空;";
                        team = 2;
                    }else{
                        if(hospital.equals("A")){
                            bean.setHospital("33");
                        }else if(hospital.equals("B")) {
                            bean.setHospital("34");
                        }else if(hospital.equals("C")) {
                            bean.setHospital("35");
                        }else {
                            res += "第" + i + "行" + personName + "行医院名称有误，请检查";
                        }
                    }

                    //判断体检套餐为空
                    if (StringHelper.isEmpty(setMeal) ) {
                        res += "第" + i + "行" + personName + "行体检套餐为空;";
                        team = 2;
                    }else if(!setMeal.contains(sex)){
                        res += "第" + i + "行" + personName + "行体检套餐内容与性别不符合;";
                        team = 2;
                    } else {
                        PersonnelReservationBean bean1 = dao.getMealName(setMeal);
                        String setMealName = bean1.getSetMealId();
                        if (StringHelper.isEmpty(setMealName) ||  "0.0".equals(setMealName.trim())) {
                            team = 2;
                            res += "第" + i + "行" + personName + "体检套餐有误，请检查";
                            System.out.println(res);
                        } else {
                            bean.setSetMeal(setMealName + "");
                            bean.setCheckType(bean1.getCheckType());
                            bean.setCombName(setMeal);
                        }
                    }

                    //判断手机号码为空
                    if (StringHelper.isEmpty(phone) ||  "0.0".equals(phone.trim())) {
                        res += "第" + i + "行" + personName + "行手机号码为空;";
                        team = 2;
                    } else if (!isLegalMobileNumber(phone)) {
                        res += "第" + i + "行" + personName + "行手机号码格式错误;";
                        team = 2;
                    }
                    bean.setPhone(phone);

                    if(team!=2){
                        // 查询通过身份证、姓名、电话去查询
                        PersonnelReservationBean beans = dao.getInfoById(personName,idNumber,phone);
                        if(beans!=null){
                            //获取预约人的id
                            bean.setId(beans.getId());
                            int k = dao.updateReservation(bean);
                            res = "导入成功";
                        }else{
                            res += "第" + i + "行" + personName + "行数据有误，在职人员信息未找到。请检查";
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

    private String ChangepersonType(String personType) {
        String team;
        if(personType.equals("在职")){
            team="1";
        }else if(personType.equals("离退休")){
            team="2";
        }else if(personType.equals("劳务派遣")){
            team="3";
        }else{
            team="0";
        }
        return team;
    }

    public static boolean containsChineseCharacters(String str) {
        if (str == null || "".equals(str) || "null".equals(str)) {
            return true;
        }
        String regex = "[\u4e00-\u9fa5]+";
        return str.matches(".*" + regex + ".*");
    }


    private String changeView(String srt){
        if(StringHelper.isEmpty(srt)){
            return "";
        }else{
            return srt;
        }
    }

    public static boolean isLegalMobileNumber(String mobile) {
        if (StringUtils.isEmpty(mobile) || mobile.length() != 11) {
            return false;
        }
        return mobile.matches(MOBILE_RULE);
    }
    /**
     * 验证身份证真假
     * @param  carNumber 身份证号
     * @return boolean*/
    public static boolean isCard(String carNumber) {
        //判断输入身份证号长度是否合法
        if (carNumber.length() != 18) {
         return false;
        }
        //校验身份证真假
        int sum = 0;
        int[] weight = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};//将加权因子定义为数组
        //遍历weight数组 求身份证前17项系数和
        for (int i = 0; i < weight.length; i++) {
            int n = carNumber.charAt(i) - 48;//获取 身份证对应数
            int w = weight[i];
            sum += w * n;
        }
        //对11求余
        int index = sum % 11;
        //校验码
        String m = "10X98765432";
        //获取身份证最后一位进行比对
        return m.charAt(index) == carNumber.charAt(17);
    }


    /**
     * 根据身份编号获取性别
     *
     * @param Idcard 身份编号
     */
    public static String getSexByIdcard(String Idcard) {
        String sCardNum = Idcard.substring(16, 17);
        if (Integer.parseInt(sCardNum) % 2 != 0) {
            return "0";
        } else {
            return "1";
        }
    }

    /**
     * 根据身份证号计算持有者年龄
     * @param idCard
     * @return
     */
    public static int countAge(String idCard) {
        if (idCard.length() != 18 && idCard.length() != 15) {
            throw new IllegalArgumentException("身份证号长度错误");
        }
        String year;
        String monthDay;
        if (idCard.length() == 18) {
            year = idCard.substring(6,10);
            monthDay = idCard.substring(10,14);
        } else {
            year = "19" + idCard.substring(6, 8);
            monthDay = idCard.substring(8, 12);
        }
        //获取当前时间字符串如：2022-1128
        String nowTimeStr = new SimpleDateFormat("yyyy-MMdd").format(new Date());
        String yearNow = nowTimeStr.substring(0, 4);// 当前年份
        String monthDayNow = nowTimeStr.substring(5, 9);// 当前月日
        int age = Integer.parseInt(yearNow) - Integer.parseInt(year);
        //age减一的情况 ：用户月日大于当前月日（开头可以为0的4位数int）
        if (Integer.parseInt(monthDay) > Integer.parseInt(monthDayNow)) {
            age = age - 1;
        }
        return age;
    }
}
