package com.zjrs.zwnw.zj.blo.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.micrometer.core.instrument.util.StringUtils;
import org.mohrss.leaf.core.framework.domain.blo.impl.BLOImpl;
import org.mohrss.leaf.core.framework.persistens.PageResult;
import org.mohrss.leaf.core.framework.persistens.PageUtil;
import com.zjrs.zwnw.jbxxgl.blo.GrxxglBLO;
import com.zjrs.zwnw.jbxxgl.entity.VAc01Mapper;
import com.zjrs.zwnw.jbxxgl.entity.VSSgAreaMapper;
import com.zjrs.zwnw.jbxxgl.po.VSAc01PO;
import com.zjrs.zwnw.jbxxgl.po.VSSgAreaPO;
import com.zjrs.zwnw.rlzysc.entity.VGgfwDictMapper;
import com.zjrs.zwnw.rlzysc.po.VGgfwDict;
import com.zjrs.zwnw.sxgl.blo.impl.JcsxqdkBLOimpl;
import com.zjrs.zwnw.zj.blo.GccrcBLO;
import com.zjrs.zwnw.zj.bpo.WjfwFeignClientBPO;
import com.zjrs.zwnw.zj.dto.*;
import com.zjrs.zwnw.zj.entity.*;
import com.zjrs.zwnw.zj.po.*;
import com.zjrs.zwnw.zj.util.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.mock.web.MockMultipartFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

@Service
public class GccrcBLOImpl extends BLOImpl implements GccrcBLO {
    private static final Logger LOG = LoggerFactory.getLogger(GccrcBLOImpl.class);

    @Resource
    private WjfwFeignClientBPO wjfwFeignClientBPO;
    @Resource
    GccrcMapper gccrcMapper;
    @Resource
    GccrcLsMapper gccrcLsMapper;
    @Resource
    GccrcQfMapper gccrcQfMapper;
    @Resource
    GccrcFjMapper gccrcFjMapper;
    @Resource
    VGgfwDictMapper vGgfwDictMapper;
    @Resource
    private VSSgAreaMapper vSSgAreaMapper;
    @Resource
    private VAc01Mapper vAc01Mapper;
    @Resource
    private RsZjGccrcDrlogMapper rsZjGccrcDrlogMapper;
    @Resource
    private RsZjGccrcPhotoDrlogMapper rsZjGccrcPhotoDrlogMapper;
    @Resource
    private GrxxglBLO grxxglBLO;

    @Override
    public GccrcInfoDTO getGccrcInfo(GccrcQueryByIdDTO dto) {
        return gccrcMapper.getGccrcInfo(dto);
    }

    @Override
    public int queryCntById(String rsZjGccrcLsh,String ztid) {
        QueryWrapper<GccrcPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ztid", ztid);
        int cnt = gccrcMapper.selectCount(queryWrapper);
        return cnt;
    }

    @Override
    public PageResult getGccrcList(GccrcQueryDTO dto, int page, int rows) {
        Page<GccrcListDTO> page1 = new Page<>(page, rows);
        Page<GccrcListDTO> pageResult = (Page) gccrcMapper.getGccrcListPage(page1, dto);
        PageResult result = PageUtil.PageResult(pageResult);
        return result;
    }

    @Override
    public String saveOrUpd(GccrcPO gccrcPO, GccrcLsPO gccrcLsPO) {
        String rsZjGccrcLsh=gccrcPO.getRsZjGccrcLsh();
        if(StringUtils.isBlank(gccrcPO.getRsZjGccrcLsh())) {
            //新增数据
            rsZjGccrcLsh= UUID.randomUUID().toString().replace("-", "");
            gccrcPO.setRsZjGccrcLsh(rsZjGccrcLsh);
            gccrcMapper.insert(gccrcPO);
        }else{
            GccrcPO gccrcOldPO=gccrcMapper.selectById(gccrcPO.getRsZjGccrcLsh());
            gccrcPO.setRckzt(gccrcOldPO.getRckzt());

            gccrcMapper.updateById(gccrcPO);
        }
        //保存变更内容
        if(StringUtils.isNotBlank(gccrcLsPO.getBgnr())) {
            gccrcLsPO.setRsZjGccrcLsh(rsZjGccrcLsh);
            gccrcLsMapper.insert(gccrcLsPO);
        }

        return rsZjGccrcLsh;
    }

    @Override
    public String getDictAAA103(String AAA100, String AAA102) {
        try{
            QueryWrapper<VGgfwDict> queryWrapper = new QueryWrapper<>();
            VGgfwDict dict=vGgfwDictMapper.selectOne(queryWrapper);
            return dict.getAaa103();
        }catch (Exception ex){
            return "";
        }
    }

    @Override
    public String getArea(String areaCode) {
        try{
            VSSgAreaPO poarea = vSSgAreaMapper.selectOne(new QueryWrapper<VSSgAreaPO>()
                    .eq("area_code", areaCode));
            return poarea.getAreaname();
        }catch (Exception ex){
            return "";
        }
    }

    @Override
    public Long getCntByZtid(GccrcSaveDTO dto) {
        return gccrcMapper.getCntByZtid(dto);
    }

    @Override
    public PageResult getBglsList(GccrcQueryByIdPageDTO dto, int page, int rows) {
        Page<GccrcLsPO> page1 = new Page<>(page, rows);
        Page<GccrcLsPO> pageResult = (Page) gccrcMapper.getBglsList(page1, dto);
        PageResult result = PageUtil.PageResult(pageResult);
        return result;
    }

    @Override
    public GccrcQfInfoDTO getDzkxx(GccrcQfQueryDTO dto) {
        return gccrcQfMapper.getDzkxx(dto);
    }

    @Override
    public void saveIsZxGccrc(GccrcSaveIsZxDTO dto, GccrcLsPO gccrcLsPO) {
        //保存变更内容
        if(StringUtils.isNotBlank(gccrcLsPO.getBgnr())) {
            gccrcLsMapper.insert(gccrcLsPO);
        }
        UpdateWrapper<GccrcPO> updateWrapper=new UpdateWrapper<>();
        GccrcPO po=new GccrcPO();
        po.setRckzt(dto.getRckzt());
        gccrcMapper.update(po, updateWrapper);
    }

    @Override
    public PageResult getDzkqfList(GccrcQueryByIdPageDTO dto, int page, int rows) {
        Page<GccrcQfPO> page1 = new Page<>(page, rows);
        Page<GccrcQfListDTO> pageResult = (Page) gccrcQfMapper.getDzkqfList(page1, dto);
        PageResult result = PageUtil.PageResult(pageResult);
        return result;
    }

    @Override
    public String getMaxLsh(GccrcInfoDTO dto) {
        return gccrcQfMapper.getMaxLsh(dto);
    }

    @Override
    public void saveQfzt(GccrcInfoDTO gccrcInfoDTO, GccrcQfPO gccrcQfPO, GccrcLsPO gccrcLsPO,String nowDate) {
        //保存变更内容
        if(StringUtils.isNotBlank(gccrcLsPO.getBgnr())) {
            gccrcLsMapper.insert(gccrcLsPO);
        }
        //签发时把以前的改成0
        UpdateWrapper<GccrcQfPO> updateQfWrapper=new UpdateWrapper<>();
        GccrcQfPO qfPO=new GccrcQfPO();
        qfPO.setYxbz("0");
        gccrcQfMapper.update(qfPO,updateQfWrapper);

        gccrcQfMapper.insert(gccrcQfPO);
        UpdateWrapper<GccrcPO> updateWrapper=new UpdateWrapper<>();
        GccrcPO po=new GccrcPO();
        po.setRckzt(gccrcInfoDTO.getRckzt());
        po.setQfsj(nowDate);
        gccrcMapper.update(po, updateWrapper);

    }

    @Override
    public void exportGccrc(GccrcQueryDTO dto, HttpServletResponse res) {
        //列表数据
        List<ExportGccrcListDTO> gccrcQueryList = gccrcMapper.exportGccrcList(dto);
        InputStream inputStream = null;
        try {
            inputStream = JcsxqdkBLOimpl.class.getClassLoader()
                    .getResourceAsStream("templates" + File.separator + "zj" + File.separator + "gccrcExport.xlsx");
            
            String fileName = "高层次人才导出结果.xlsx";
            res.setContentType("application/vnd.ms-excel;charset=utf-8");
            res.setHeader("Content-disposition", "attachment;filename=" + fileName);
            res.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else{
                LOG.info("inputStream为空");
            }
        }
    }
    @Override
    public VSAc01PO queryRyxx(AC01DTO dto) {
        QueryWrapper<VSAc01PO> queryWrapper = new QueryWrapper<>();
        return vAc01Mapper.selectOne(queryWrapper);
    }

    @Override
    public void updateRckzt() {
        QueryWrapper<GccrcPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("rckzt","1");
        List<GccrcPO> list=gccrcMapper.selectList(queryWrapper);
        for(int i=0;i<list.size();i++){
            GccrcPO po=list.get(i);
            UpdateWrapper<GccrcPO> updateWrapper=new UpdateWrapper<>();
            GccrcPO po1=new GccrcPO();
            po1.setRckzt("2");
            gccrcMapper.update(po1, updateWrapper);
        }
    }

    @Override
    public PageResult getFjList(GccrcQueryByIdPageDTO dto, int page, int rows) {
        Page<GccrcFjListDTO> page1 = new Page<>(page, rows);
        Page<GccrcFjListDTO> pageResult = (Page) gccrcFjMapper.getFjList(page1, dto);
        return PageUtil.PageResult(pageResult);
    }
    @Override
    public void saveFj(GccrcFjPO gccrcFjPO) {
        gccrcFjMapper.insert(gccrcFjPO);
    }
    @Override
    public void delFj(GccrcFjPO gccrcFjPO) {
        UpdateWrapper<GccrcFjPO> updateWrapper=new UpdateWrapper<>();
        gccrcFjMapper.update(gccrcFjPO, updateWrapper);
    }

    @Override
    public void updateGsqs(GccrcQueryByIdDTO gccrcQueryByIdDTO, String gsqs) {
        UpdateWrapper<GccrcPO> updateWrapper=new UpdateWrapper<>();
        GccrcPO gccrcPO=new GccrcPO();
        gccrcPO.setGsqs(gsqs);
        gccrcMapper.update(gccrcPO, updateWrapper);
    }

    @Override
    public Map<String, String> importGccrc(InputStream is) throws Exception {
        //导入批号
        String drph = UUID.randomUUID().toString().replaceAll("-", "");
        Map<String, String> resultMap = new HashMap<>();

        //导入所需字典
        Map<String, Object> aa10RowSet = getGgfwDictRowSet();

        Map<String, String> fieldsMapper = new HashMap<String, String>();
        fieldsMapper.put("序号", "xh");
        fieldsMapper.put("手机号码", "aac067");
        fieldsMapper.put("人才卡号码", "rckhm");
        fieldsMapper.put("公示期数", "gsqs");
        fieldsMapper.put("申请类型", "sqlx");

        List<String> rowMapperList = new ArrayList<>();
        
        if (rowMapperList == null || rowMapperList.size() == 0) {
            resultMap.put("code", "1");
            resultMap.put("msg", "导入失败，请检查导入内容是否正确。");
            resultMap.put("drph", "");
            return resultMap;
        }
        resultMap.put("code", "0");
        resultMap.put("msg", "导入成功");
        resultMap.put("drph", drph);
        return resultMap;
    }

    @Override
    public List<Map<String, Integer>> queryGccrcDrhz(DrDTO dto) {
        QueryWrapper<RsZjGccrcDrlogPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("drph", dto.getDrph());
        int sbCnt = rsZjGccrcDrlogMapper.selectCount(queryWrapper);

        queryWrapper = new QueryWrapper<>();
        int cgCnt = rsZjGccrcDrlogMapper.selectCount(queryWrapper);
        Map<String, Integer> map = new HashMap<>();
        map.put("sbCnt", sbCnt);
        List<Map<String, Integer>> list = new ArrayList();
        list.add(map);
        return list;
    }

    @Override
    public PageResult queryGccrcDrsb(DrDTO dto, int page, int rows) {
        QueryWrapper<RsZjGccrcDrlogPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("drph", dto.getDrph());
        Page<RsZjGccrcDrlogPO> page1 = new Page<>(page, rows);
        Page<RsZjGccrcDrlogPO> pageResult = (Page) this.rsZjGccrcDrlogMapper.selectPage(page1, queryWrapper);
        PageResult result = PageUtil.PageResult(pageResult);
        return result;
    }

    @Override
    public PageResult queryGccrcDrcg(DrDTO dto, int page, int rows) {
        QueryWrapper<RsZjGccrcDrlogPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("drph", dto.getDrph());
        Page<RsZjGccrcDrlogPO> page1 = new Page<>(page, rows);
        Page<RsZjGccrcDrlogPO> pageResult = (Page) this.rsZjGccrcDrlogMapper.selectPage(page1, queryWrapper);
        PageResult result = PageUtil.PageResult(pageResult);
        return result;
    }

    @Override
    public Map<String, String> importPhoto(MultipartFile inFile, String suffix) throws Exception {
        //导入批号
        String drph = UUID.randomUUID().toString().replaceAll("-", "");
        Map<String, String> resultMap = new HashMap<>();
        String filePath = null;
        List<File> files=new ArrayList<>();
        InputStream fileStream = null;
        try {
            File file = null;
//            ZipFile zipFile = null;
            filePath = System.getProperty("user.dir") + File.separator + UUID.randomUUID();
            String[] filename = inFile.getOriginalFilename().split("\\.");
            if(filename[0].length()<=3){
                file=File.createTempFile(filename[0]+"temp", filename[1]);
            }else{
                file=File.createTempFile(filename[0], filename[1]);
            }
            inFile.transferTo(file);
            files=FileUtil.unRar(file,filePath);
        }catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fileStream!=null){
                fileStream.close();
            }
            if (filePath != null) {
                FileUtil.delFiles(new File(filePath));
            }
        }
        resultMap.put("code", "0");
        resultMap.put("msg", "导入照片成功");
        resultMap.put("drph", drph);
        return resultMap;
    }

    @Override
    public List<Map<String, Integer>> queryPhotoDrhz(DrDTO dto) {
        QueryWrapper<RsZjGccrcPhotoDrlogPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("drph", dto.getDrph());
        int sbCnt = rsZjGccrcPhotoDrlogMapper.selectCount(queryWrapper);

        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("DRJG", "1");
        int cgCnt = rsZjGccrcPhotoDrlogMapper.selectCount(queryWrapper);
        Map<String, Integer> map = new HashMap<>();
        map.put("sbCnt", sbCnt);
        List<Map<String, Integer>> list = new ArrayList();
        list.add(map);
        return list;
    }

    @Override
    public PageResult queryPhotoDrsb(DrDTO dto, int page, int rows) {
        QueryWrapper<RsZjGccrcPhotoDrlogPO> queryWrapper = new QueryWrapper<>();
        Page<RsZjGccrcPhotoDrlogPO> page1 = new Page<>(page, rows);
        Page<RsZjGccrcPhotoDrlogPO> pageResult = (Page) this.rsZjGccrcPhotoDrlogMapper.selectPage(page1, queryWrapper);
        PageResult result = PageUtil.PageResult(pageResult);
        return result;
    }

    @Override
    public PageResult queryPhotoDrcg(DrDTO dto, int page, int rows) {
        QueryWrapper<RsZjGccrcPhotoDrlogPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("DRJG", "1");
        Page<RsZjGccrcPhotoDrlogPO> page1 = new Page<>(page, rows);
        Page<RsZjGccrcPhotoDrlogPO> pageResult = (Page) this.rsZjGccrcPhotoDrlogMapper.selectPage(page1, queryWrapper);
        PageResult result = PageUtil.PageResult(pageResult);
        return result;
    }
    private static void extractFile(final ZipEntry entry, ZipInputStream is)
            throws IOException {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(entry.getName());
            while (is.available() != 0) {
                fos.write(is.read());
            }
        } catch (IOException ioex) {
            fos.close();
        }
    }

    private Map<String, Object> getGgfwDictRowSet() {
        Map<String, Object> result = new HashMap<>();
        QueryWrapper<VGgfwDict> aa10QueryWrapper = null;
        //申请类型
        aa10QueryWrapper = new QueryWrapper<>();
        aa10QueryWrapper.eq("AAA100", "RS_ZJ_GCCRC_SQLX_JG");
        List<VGgfwDict> sqlxList = vGgfwDictMapper.selectList(aa10QueryWrapper);

        result.put("sqlx", sqlxList);
        return result;
    }

    //object对象转为String,主要处理BigDecimal
    private String objToStr(Object obj) {
        String str = null;
        if (obj instanceof String) {
            str = (String) obj;
        } else if (obj instanceof BigDecimal) {
            str = ((BigDecimal) obj).stripTrailingZeros().toPlainString();
        }
        if (StringUtils.isNotBlank(str)) {
            str = str.trim();
        }
        return str;
    }
    private void validationRule(GccrcPO gccrcPO, Map<String, Object> valuesMap, Map<String, Object> aa10RowSet, StringBuilder builder) {
        String aac003 = objToStr(valuesMap.get("aac003"));
        String zczymc = objToStr(valuesMap.get("zczymc"));
        String dwmc = objToStr(valuesMap.get("dwmc"));
        String gwszxsq = objToStr(valuesMap.get("gwszxsq"));
        String ldhtqx = objToStr(valuesMap.get("ldhtqx"));
        Object ldhtjzrqObj=valuesMap.get("ldhtjzrq");
        String ldhtjzrq=null;
        Object qfsjObj=valuesMap.get("qfsj");
        String qfsj=null;
        Object yxrqObj=valuesMap.get("yxrq");
        String yxrq=null;
        String bz = objToStr(valuesMap.get("bz"));
        String sqlx = objToStr(valuesMap.get("sqlx"));

        //2、空校验
        if (StringUtils.isBlank(aac003)) {
            builder.append("“姓名”、");
        }
        if (StringUtils.isBlank(dwmc)) {
            builder.append("“单位名称”、");
        }
        if (StringUtils.isBlank(gwszxsq)) {
            builder.append("“单位所在县市区”、");
        }
        if (StringUtils.isBlank(ldhtqx)) {
            builder.append("“劳动合同期限”、");
        }
        //若劳动合同期限为“固定期限”，则“劳动合同截止期限（精确到日）”不能为空。
        if (StringUtils.isBlank(ldhtjzrq)) {
            if (StringUtils.isNotBlank(ldhtqx) && ldhtqx.trim().equals("固定期限")) {
                builder.append("“劳动合同截止期限（精确到日）”、");
            }
        }
        if (StringUtils.isBlank(qfsj)) {
            builder.append("“签发日期（精确到日）”、");
        }
        if (StringUtils.isNotBlank(gwszxsq)) {
            //校验单位所在县市区是否合法
            QueryWrapper<VSSgAreaPO> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("AREA_NAME", gwszxsq.trim());
            VSSgAreaPO vsSgAreaPO = vSSgAreaMapper.selectOne(queryWrapper);
            if (vsSgAreaPO != null) {
                valuesMap.put("gwszxsqCode", vsSgAreaPO.getAreacode());
            } else {
                builder.append("“单位所在县市区”列内容不符合导入要求；");
            }
        }

        if (StringUtils.isNotBlank(dwmc) && getLength(dwmc) > 100) {
            builder.append("“单位名称”").append("列内容超出长度限制，最多录入50个汉字或100个字符；");
        }
        if (StringUtils.isNotBlank(bz) && getLength(bz) > 4000) {
            builder.append("“备注（原认定类别）”").append("列内容超出长度限制，最多录入2000个汉字或4000个字符；");
        }
        //判断日期格式是否符合规则
        if (StringUtils.isNotBlank(ldhtjzrq)) {
            try {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
                dateFormat.setLenient(false);
                Date date = dateFormat.parse(ldhtjzrq);
                dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String ldhtjzrqStr = dateFormat.format(date);
            } catch (Exception ex) {
                builder.append("“劳动合同截止期限（精确到日）”").append("列格式有误，应为YYYY/MM/DD格式，示例：2018/09/12；");
            }
        }
        if (StringUtils.isNotBlank(qfsj)) {
            try {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
                dateFormat.setLenient(false);
                Date date = dateFormat.parse(qfsj);
                dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String qfsjStr = dateFormat.format(date);
            } catch (Exception ex) {
                builder.append("“签发日期（精确到日）”").append("列格式有误，应为YYYY/MM/DD格式，示例：2018/09/12；");
            }
        }
        if (StringUtils.isNotBlank(yxrq)) {
            try {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
                dateFormat.setLenient(false);
                Date date = dateFormat.parse(yxrq);
                dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String yxrqStr = dateFormat.format(date);
            } catch (Exception ex) {
                builder.append("“有效日期（精确到日）”").append("列格式有误，应为YYYY/MM/DD格式，示例：2018/09/12；");
            }
        }
    }

    private Map<String, String> getAa10Aaa102(String aaa103, List<VGgfwDict> aa10List) {
        Map<String, String> resultMap = new HashMap<>();
        String code = null;
        StringBuilder names = new StringBuilder();

        resultMap.put("code", code);
        if (names != null && names.length() > 0) {
            resultMap.put("names", names.deleteCharAt(names.length() - 1).toString());
        } else {
            resultMap.put("names", "");
        }
        return resultMap;
    }

    private int getLength(String str) {
        int length = 0;
        if (StringUtils.isNotBlank(str)) {
            try {
                length = str.trim().getBytes("GBK").length;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return length;
    }
    private MultipartFile getMultipartFile(File file) {
        try (FileInputStream fis = new FileInputStream(file)) {
            // 参数依次为：参数名(file)、文件名、内容类型、输入流
            return new MockMultipartFile(
                    "file",
                    file.getName(),
                    "multipart/form-data",
                    fis
            );
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
