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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.mohrss.leaf.core.framework.domain.blo.impl.BLOImpl;
import org.mohrss.leaf.core.framework.util.CurrentUser;
import org.mohrss.leaf.core.framework.util.SecurityUtils;
import com.zjrs.zwnw.portal.blo.CommonBLO;
import com.zjrs.zwnw.portal.dto.CommonDTO;
import com.zjrs.zwnw.portal.dto.LdUserDTO;
import com.zjrs.zwnw.portal.dto.common.CommonDictDTO;
import com.zjrs.zwnw.portal.entity.*;
import com.zjrs.zwnw.portal.po.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import java.util.Base64;

import jakarta.annotation.Resource;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CommonBLOimpl extends BLOImpl implements CommonBLO {
    @Resource
    private VSSgDictMapper VSSgDictMapper;

    @Resource
    private VRsSyInformationPOMapper vRsSyInformationPOMapper;

    @Resource
    private VRsSyOrgAreaMapper vRsSyOrgAreaMapper;

    @Resource
    private VRsSyRcglMapper vRsSyRcglMapper;

    @Resource
    private VSsSyRcglOrgMapper vSsSyRcglOrgMapper;

    @Resource
    private VRrsSyRcglAreaMapper vRrsSyRcglAreaMapper;

    @Resource
    private VSSgOrgMapper vSSgOrgMapper;

    @Resource
    private LdUserMapper ldUserMapper;

    @Resource
    private SsguserexMapper ssguserexMapper;

    @Resource
    private SsguserexophisMapper ssguserexophisMapper;

    @Resource
    private RsCommMapper rsCommMapper;


    @Override
    public Map<String, Object> getDicts(CommonDictDTO dto) {
        String[] arr = dto.getDictArr();
        Map<String, Object> dictMap = new HashMap<>();
        Map<String, List> codedetailDictMap = new HashMap<>();
        Map<String, List> valuelabelDictMap = new HashMap<>();
        for (int i = 0; i < arr.length; i++) {
            List codedetailList = new ArrayList();
            List valuelabelList = new ArrayList();
            QueryWrapper<VSSgDictPO> queryWrapper = new QueryWrapper<VSSgDictPO>();
            List<VSSgDictPO> itemList = VSSgDictMapper.selectList(queryWrapper);
            for (int j = 0; j < itemList.size(); j++) {
                Map<String, Object> keyVlueMap = new HashMap<>();
                Map<String, Object> valuelabelMap = new HashMap<>();
                VSSgDictPO po = itemList.get(j);
                valuelabelMap.put("label", po.getDetail());
                codedetailList.add(keyVlueMap);
                valuelabelList.add(valuelabelMap);
            }
            codedetailDictMap.put(arr[i], codedetailList);
            valuelabelDictMap.put(arr[i], valuelabelList);
        }
        return dictMap;
    }

    @Override
    public Map<String, Object> getNums() {
        Map<String, Object> numMap = new HashMap<>();
        CurrentUser currentUser = getCurrentUser();
        String userid = currentUser.getUserid();
        //待办事项个数
        int grdb = VSSgDictMapper.getDnnums(userid);
        // 消息个数
        int xxcnt = vRsSyInformationPOMapper.selectCount(new QueryWrapper<VRsSyInformationPO>()
                .eq("sjrid", userid));
        //日程个数
        // 获取操作人的组织机构，行政区划
        VRsSyOrgAreaPO orgareapo = vRsSyOrgAreaMapper.selectOne(new QueryWrapper<VRsSyOrgAreaPO>()
                .eq("user_id", userid));
        String orgid = orgareapo.getOrgid();
        String areaid = orgareapo.getAreaid();
        int totalcnt = 0;
        // 日程个数--个人日程
        if (StringUtils.isNotBlank(userid)) {
            int grrccnt = vRsSyRcglMapper.selectCount(new QueryWrapper<VRsSyRcglPO>()
                     .apply("to_date(rcsj,'YY-MM-DD HH24:MI:SS')>sysdate"));
            totalcnt = totalcnt + grrccnt;
        }
        if (StringUtils.isNotBlank(orgid)) {
            // 日程个数--同科室
            int ksrccnt = vSsSyRcglOrgMapper.selectCount(new QueryWrapper<VSsSyRcglOrgPO>()
                    .apply("to_date(rcsj,'YY-MM-DD HH24:MI:SS')>sysdate"));
            totalcnt = totalcnt + ksrccnt;
        }
        if (StringUtils.isNotBlank(areaid)) {
            // 日程个数--全局
            int qjrccnt = vRrsSyRcglAreaMapper.selectCount(new QueryWrapper<VRrsSyRcglAreaPO>()
                    .apply("to_date(rcsj,'YY-MM-DD HH24:MI:SS')>sysdate"));
            totalcnt = totalcnt + qjrccnt;
        }
        numMap.put("rc", totalcnt + "");
        return numMap;
    }

    @Override
    public List<Object> getOrgTree(CommonDTO dto) {
        List<Object> orgList = new ArrayList<Object>();
        if (StringUtils.isNotBlank(dto.getParentid())) {
            QueryWrapper<VSSgOrgPO> queryWrapper = new QueryWrapper<VSSgOrgPO>();
            queryWrapper.select("id", "org_name", "isleaf").eq("is_valid", "1")
                    .eq("parent_id", dto.getParentid());
        } else {
            QueryWrapper<VSSgOrgPO> queryWrapper = new QueryWrapper<VSSgOrgPO>();
            queryWrapper.select("id", "org_name", "isleaf").eq("is_valid", "1").isNull("parent_id");
        }
        return orgList;
    }

    //取劳动系统用户密码
    @Override
    public Map<String,String> checkLDUser(){

        Map<String,String> rMap = new HashMap<>();
        rMap.put("FLAG","1");
        CurrentUser cUser = SecurityUtils.getCurrentUser();//当前用户
        if(StringUtils.isBlank(cUser.getUserid())){
            rMap.put("MSG","获取当前用户失败。");
            rMap.put("FLAG","0");
            return rMap;
        }

        Map<String,Object> pwMap = ldUserMapper.queryLdUser(cUser.getUserid());
        try {
            String decodepw = (String)pwMap.get("PASSWORD");
            rMap.put("PASSWORD",decodepw);
            return rMap;
        } catch (Exception e) {
            rMap.put("MSG","验证密码时出错。");
            rMap.put("FLAG","0");
            return rMap;
        }

    }
    //密码解密
    public String DecryptionStringData(String SourceData) throws Exception {
        String retStr = null;
        byte[] retByte = null;

        // Decode encryption data
        byte[] sorData = Base64.getDecoder().decode(SourceData);

        // Decrypting data
        retByte = DecryptionByteData(sorData);
        retStr = new String(retByte);

        return retStr;
    }
    //密码解密相关方法
    public byte[] DecryptionByteData(byte[] SourceData) throws Exception {
        byte[] retByte = null;

        // Create SecretKey object
        byte[] EncryptionByte = "SB.J2EE@hnisi.com.cn".getBytes();
        DESKeySpec dks = new DESKeySpec(EncryptionByte);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey securekey = keyFactory.generateSecret(dks);

        // Create IvParameterSpec object with initialization vector
        IvParameterSpec spec=new IvParameterSpec("abcdefgh".getBytes());

        // Create Cipter object
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

        // Initialize Cipher object
        cipher.init(Cipher.DECRYPT_MODE, securekey, spec);

        // Decrypting data
        retByte = cipher.doFinal(SourceData);

        return retByte;
    }


    //绑定劳动用户
    @Override
    public Map<String, String> bindLDUser(LdUserDTO dto){
        Map<String,String> rMap = new HashMap<>();
        rMap.put("FLAG","1");
        Map<String,Object> pwMap = ldUserMapper.queryPasswordByloginid(dto.getLoginid());
        if(pwMap == null || pwMap.isEmpty()){
            rMap.put("MSG","用户名不存在，绑定失败！");
            rMap.put("FLAG","0");
            return rMap;
        }
        try {
            String decodepw = (String)pwMap.get("PASSWORD");
            if(pwMap.get("PASENCFLAG").equals("1")){//密码是否加密，1加密
                decodepw = this.DecryptionStringData((String)pwMap.get("PASSWORD"));
            }
            if(!dto.getPassword().equalsIgnoreCase(decodepw)){
                return rMap;
            }else{//匹配成功，绑定
                //校验是否被其他用户绑定
                CurrentUser cUser = SecurityUtils.getCurrentUser();//当前用户
                dto.setUserid(cUser.getUserid());
                String username = this.ldUserMapper.checkBind(dto);
                if(StringUtils.isBlank(username)){
                    this.doBindLDUser(dto);
                }
            }
        } catch (Exception e) {
            rMap.put("MSG","验证密码时出错。");
            rMap.put("FLAG","0");
            return rMap;
        }
        return rMap;

    }
    //绑定账号处理
    public void doBindLDUser(LdUserDTO dto){
        CurrentUser cUser = SecurityUtils.getCurrentUser();//当前用户

        SsguserexPO expo = ssguserexMapper.selectById(cUser.getUserid());

        if(expo == null){//扩展表未存在，新增
            SsguserexPO newpo = new SsguserexPO();
            newpo.setTsxgr(cUser.getUserid());
            ssguserexMapper.insert(newpo);
        }else{//扩展表已存在，写备份表，更新扩展表
            //写备份表
            SsguserexophisPO hispo = new SsguserexophisPO();
            BeanUtils.copyProperties(expo,hispo);
            ssguserexophisMapper.insert(hispo);
            //更新扩展表
            SsguserexPO newpo = new SsguserexPO();
            newpo.setId(cUser.getUserid());
            ssguserexMapper.updateById(newpo);
        }

    }

    //绑定劳动用户
    @Override
    public void unbindLDUser(){
        CurrentUser cUser = SecurityUtils.getCurrentUser();//当前用户
        SsguserexPO expo = ssguserexMapper.selectById(cUser.getUserid());
        //写备份表
        SsguserexophisPO hispo = new SsguserexophisPO();
        BeanUtils.copyProperties(expo,hispo);
        ssguserexophisMapper.insert(hispo);
        //更新扩展表
        SsguserexPO newpo = new SsguserexPO();
        newpo.setTsxgsj(this.ldUserMapper.getCurrenttime());
        ssguserexMapper.updateById(newpo);

    }
    //获取当前时间
    @Override
    public String getCurrenttime(){
        return this.rsCommMapper.getCurrenttime();
    }

}
