package com.zjrs.ggfw.rlzysc.blo.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.mohrss.leaf.core.framework.persistens.PageResult;
import org.mohrss.leaf.core.framework.persistens.PageUtil;
import org.mohrss.leaf.core.framework.util.CurrentUser;
import org.mohrss.leaf.core.framework.web.exception.AppException;
import com.zjrs.ggfw.portal.blo.CommBLO;
import com.zjrs.ggfw.portal.entity.VAc01Mapper;
import com.zjrs.ggfw.portal.entity.VGgfwDictMapper;
import com.zjrs.ggfw.portal.entity.VRsGgfwUserMapper;
import com.zjrs.ggfw.portal.entity.VSgAreaMapper;
import com.zjrs.ggfw.portal.po.VAc01;
import com.zjrs.ggfw.portal.po.VGgfwDict;
import com.zjrs.ggfw.portal.po.VRsGgfwUser;
import com.zjrs.ggfw.portal.po.VSgArea;
import com.zjrs.ggfw.rlzysc.blo.YgbaBLO;
import com.zjrs.ggfw.rlzysc.dto.*;
import com.zjrs.ggfw.rlzysc.entity.YgbadwMapper;
import com.zjrs.ggfw.rlzysc.entity.YgbaygMapper;
import com.zjrs.ggfw.rlzysc.entity.YgbaygTempMapper;
import com.zjrs.ggfw.rlzysc.po.RsRlzyYgbadwPO;
import com.zjrs.ggfw.rlzysc.po.RsRlzyYgbaygTempPO;
import com.zjrs.ggfw.rlzysc.po.RsRlzyYgbaygYwPO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

import static org.mohrss.leaf.core.framework.util.SecurityUtils.getCurrentUser;

@Service
public class YgbaBLOImpl implements YgbaBLO {

    private static final Logger LOG = LoggerFactory.getLogger(YgbaBLOImpl.class);

    @Autowired
    private YgbadwMapper ygbadwMapper;

    @Autowired
    private YgbaygMapper ygbaygMapper;

    @Autowired
    private VGgfwDictMapper vGgfwDictMapper;


    @Autowired
    private VSgAreaMapper vSgAreaMapper;

    @Autowired
    private YgbaygTempMapper ygbaygTempMapper;
    @Autowired
    private VRsGgfwUserMapper vRsGgfwUserMapper;

    @Autowired
    CommBLO commBLO;
    @Autowired
    VAc01Mapper vAc01Mapper;


    @Override
    public Map<String, Object> getDwxx(){
        CurrentUser currentUser = getCurrentUser();
        String userid = currentUser.getUsername() == null ? "" : currentUser.getUsername().trim();
        //String userid = "8f876cab5fbc4b9ab7101a85ea9a4e7f";
        if(StringUtils.isBlank(userid)){
            throw new AppException("用户ID为空");
        }
        return this.ygbadwMapper.getDwxx(userid);
    }

    @Override
    public String saveDwxx(YgbadwUDTO dto){
        String id = dto.getRsrlzyygbadwlsh();
        RsRlzyYgbadwPO po = new RsRlzyYgbadwPO();
        BeanUtils.copyProperties(dto, po);

        CurrentUser currentUser = getCurrentUser();
        String userid = currentUser.getUsername() == null ? "" : currentUser.getUsername().trim();
        VRsGgfwUser VRsGgfwUserTmp = vRsGgfwUserMapper.selectById(userid);
        po.setZtid(VRsGgfwUserTmp.getZtid());

        String currentTime = this.commBLO.getCurrenttime();
        if(StringUtils.isBlank(id)){//新增
            po.setBae002(userid);
            this.ygbadwMapper.insert(po);
        }else{//修改
            po.setBae004(userid);
            po.setBae005(currentTime);
        }
        return po.getRsrlzyygbadwlsh();
    }

    @Override
    public PageResult getYgxxlist(YgbaYgxxQueryDTO dto, Integer pagenum, Integer pagesize){
        Page<RsRlzyYgbaygYwPO> page = new Page<>(dto.getPagenum(), dto.getPagesize());
        Page<RsRlzyYgbaygYwPO> pageResult = (Page) ygbadwMapper.getYgxxlist(page, dto);
        PageResult result = PageUtil.PageResult(pageResult);
        return result;
    }

    @Override
    public String saveYgxx(YgbaygUDTO dto){
        String id = dto.getRsrlzyygbaygywlsh();
        RsRlzyYgbaygYwPO po = new RsRlzyYgbaygYwPO();
        BeanUtils.copyProperties(dto, po);

        CurrentUser currentUser = getCurrentUser();
        String userid = currentUser.getUsername() == null ? "" : currentUser.getUsername().trim();
        String currentTime = this.commBLO.getCurrenttime();
        po.setRyzt("01");
        if(StringUtils.isBlank(id)){//新增
            //校验是否已存在
            QueryWrapper<RsRlzyYgbaygYwPO> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("zjhm",po.getZjhm());
            queryWrapper.eq("ts_yxbz","1");
            RsRlzyYgbaygYwPO rsRlzyYgbaygYwPO = ygbaygMapper.selectOne(queryWrapper);
            if (null != rsRlzyYgbaygYwPO) {
                throw new AppException("该职工已存在!");
            }
            po.setBae002(userid);
            po.setBae004(userid);
            po.setBae005(currentTime);
            this.ygbaygMapper.insert(po);
        }
        return po.getRsrlzyygbaygywlsh();
    }

    @Override
    public void batchSubmitYgxx(YgbaygCommDTO dto){
        RsRlzyYgbaygYwPO po = new RsRlzyYgbaygYwPO();
        CurrentUser currentUser = getCurrentUser();
        String userid = currentUser.getUserid()==null?"":currentUser.getUserid().trim();
        String currentTime = this.commBLO.getCurrenttime();//获取当前时间
        po.setBae004(userid);//最近修改人
        po.setBae005(currentTime);//最近修改时间

        String ids = dto.getIds();
        String[] idArr = ids.split(",");
        List<String> list = Arrays.asList(idArr);
        RsRlzyYgbaygYwPO po2 = new RsRlzyYgbaygYwPO();
        for(String id : list){
            po.setRsrlzyygbaygywlsh(id);
            po2 = this.ygbaygMapper.selectById(id);
        }
    }
    @Override
    public void delYgxx(YgbaygCommDTO dto){
        RsRlzyYgbaygYwPO po = new RsRlzyYgbaygYwPO();
        CurrentUser currentUser = getCurrentUser();
        String userid = currentUser.getUserid()==null?"":currentUser.getUserid().trim();
        String currentTime = this.commBLO.getCurrenttime();//获取当前时间
        po.setBae004(userid);//最近修改人
        ygbaygMapper.updateById(po);
    }

    @Override
    public void quitYgxx(YgbaygQuitDTO dto){
        RsRlzyYgbaygYwPO po = new RsRlzyYgbaygYwPO();
        CurrentUser currentUser = getCurrentUser();
        String userid = currentUser.getUserid()==null?"":currentUser.getUserid().trim();
        String currentTime = this.commBLO.getCurrenttime();//获取当前时间
        po.setBae004(userid);//最近修改人
        ygbaygMapper.updateById(po);
    }
    @Override
    public Map<String, String> importYgxx(InputStream is)  throws Exception {
        //企业信息是否已存在
        CurrentUser currentUser = getCurrentUser();
        String userid = currentUser.getUsername() == null ? "" : currentUser.getUsername().trim();
        String currentTime = this.commBLO.getCurrenttime();//获取当前时间

        VRsGgfwUser VRsGgfwUserTmp = vRsGgfwUserMapper.selectById(userid);

        QueryWrapper<RsRlzyYgbadwPO> dwqueryWrapper = new QueryWrapper<>();
        dwqueryWrapper.eq("ztid", VRsGgfwUserTmp.getZtid());
        RsRlzyYgbadwPO rsRlzyYgbadwPO = ygbadwMapper.selectOne(dwqueryWrapper);
        if(rsRlzyYgbadwPO == null){
            throw new AppException("请先保存企业信息");
        }

        //导入批号
        String drph = UUID.randomUUID().toString().replaceAll("-", "");
        Map<String, String> resultMap = new HashMap<>();

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

        Map<String, String> fieldsMapper = new HashMap<String, String>();
        fieldsMapper.put("姓名", "xm");
        fieldsMapper.put("证件类型", "zjlx");
        fieldsMapper.put("合同到期时间", "htdqsj");
        fieldsMapper.put("备注", "bz");
        
        List<String> rowMapperList = new ArrayList<>();

        resultMap.put("code", "0");
        resultMap.put("msg", "导入成功");
        resultMap.put("drph", drph);
        return resultMap;
    }

    private Map<String, Object> getDictsRowSet() {
        Map<String, Object> result = new HashMap<>();
        QueryWrapper<VGgfwDict> dictQueryWrapper = null;
        // 证件类型
        dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.eq("AAA100", "JBXX_AAC058");
        List<VGgfwDict> zjlxList = vGgfwDictMapper.selectList(dictQueryWrapper);
        // 用工方式
        List<VGgfwDict> ygfsList = vGgfwDictMapper.selectList(dictQueryWrapper);
        result.put("zjlx", zjlxList);
        result.put("ygfs", ygfsList);
        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(RsRlzyYgbaygYwPO po, Map<String, Object> valuesMap, Map<String, Object> dictRowSet, StringBuilder builder) {
        String xm = objToStr(valuesMap.get("xm"));
        String zjlx = objToStr(valuesMap.get("zjlx"));
        String zjhm = objToStr(valuesMap.get("zjhm"));
        String hjfxzqh = objToStr(valuesMap.get("hjfxzqh"));
        String jzdz = objToStr(valuesMap.get("jzdz"));
        String csgw = objToStr(valuesMap.get("csgw"));
        String ygfs = objToStr(valuesMap.get("ygfs"));
        String rzsj = objToStr(valuesMap.get("rzsj"));
        String htdqsj = objToStr(valuesMap.get("htdqsj"));
        String bz = objToStr(valuesMap.get("bz"));

        //1、字典项校验
        List<VGgfwDict> zjlxList = (List<VGgfwDict>) dictRowSet.get("zjlx");
        List<VGgfwDict> ygfsList = (List<VGgfwDict>) dictRowSet.get("ygfs");

        Map<String, String> dictMap = null;

        
        //2、该人员是否已存在
        if (StringUtils.isNotBlank((String)valuesMap.get("zjlxCode")) && StringUtils.isNotBlank(zjhm)) {
            QueryWrapper<RsRlzyYgbaygYwPO> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("zjhm",zjhm);
            queryWrapper.eq("ts_yxbz","1");
            RsRlzyYgbaygYwPO rsRlzyYgbaygYwPO = ygbaygMapper.selectOne(queryWrapper);
            if (null != rsRlzyYgbaygYwPO) {
                builder.append("该职工已存在，不能重新导入；");
            }
        }

        //判断户籍格式
        if (StringUtils.isNotBlank(hjfxzqh)) {
            String[] hjfxzqhArr = hjfxzqh.split("\\.");
            if(hjfxzqhArr.length != 2){
                builder.append("“户籍地行政区划”列内容不符合导入要求；");
            }else{
                String xzqh = hjfxzqhArr[0];
                String name = hjfxzqhArr[1];
                QueryWrapper<VSgArea> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("AREA_CODE",xzqh);
                //queryWrapper.eq("AREA_NAME", name.trim());
                VSgArea vSgArea = vSgAreaMapper.selectOne(queryWrapper);
                if (vSgArea != null) {
                    valuesMap.put("hjfxzqhCode", xzqh);
                } else {
                    builder.append("“户籍地行政区划”列内容不符合导入要求；");
                }
            }
        }


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

        for (VGgfwDict dictpo : dictList) {
            String name = dictpo.getAaa103();
            names.append(name).append("、");
            if (aaa103.equals(name))
                code = dictpo.getAaa102();
        }
        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;
    }
    @Override
    public PageResult importHzList(YgbaygtempQueryDTO dto, Integer pagenum, Integer pagesize){
        Page<YgbargtempTjListDTO> page1 = new Page<>(pagenum, pagesize);
        Page<YgbargtempTjListDTO> pageResult = (Page) this.ygbaygTempMapper.importHzList(page1, dto.getDrph());
        PageResult result = PageUtil.PageResult(pageResult);
        return result;
    }

    @Override
    public PageResult importMxList(YgbaygtempQueryDTO dto, Integer pagenum, Integer pagesize) {
        QueryWrapper<RsRlzyYgbaygTempPO> queryWrapper = new QueryWrapper<>();
        //查询字段
        queryWrapper.eq("drph", dto.getDrph()).eq("drjg", dto.getDrjg());
        queryWrapper.orderByAsc("bae003");

        Page<RsRlzyYgbaygTempPO> page1 = new Page<>(pagenum, pagesize);
        Page<RsRlzyYgbaygTempPO> pageResult = (Page) this.ygbaygTempMapper.selectPage(page1, queryWrapper);
        PageResult result = PageUtil.PageResult(pageResult);
        return result;
    }

    @Override
    public RsRlzyYgbaygYwPO getYgxx(YgbaygCommDTO dto){
        return ygbaygMapper.selectById(dto.getIds());
    }

    @Override
    public VAc01 ygbaGetGrjbxx(YgbaygCommDTO dto){
        //校验是否已存在
        QueryWrapper<RsRlzyYgbaygYwPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("rs_rlzy_ygbadw_lsh",dto.getIds());
        queryWrapper.eq("ts_yxbz","1");
        RsRlzyYgbaygYwPO rsRlzyYgbaygYwPO = ygbaygMapper.selectOne(queryWrapper);
        if (null != rsRlzyYgbaygYwPO) {
            throw new AppException("该职工已存在!");
        }
        QueryWrapper<VAc01> ac01queryWrapper = new QueryWrapper<>();
        ac01queryWrapper.eq("aac058",dto.getZjlx());
        ac01queryWrapper.eq("aac147",dto.getZjhm());
        VAc01 ac01 = this.vAc01Mapper.selectOne(ac01queryWrapper);
        return ac01;
    }

}



