package com.engine.htxc.contract.dao;

import com.engine.htxc.commonutil.db.DbTools;
import com.engine.htxc.commonutil.db.EntityCrudUtil;
import com.engine.htxc.contract.dto.CounterPartyDTO;
import com.engine.htxc.contract.dto.UserDeptInfoDTO;
import com.engine.htxc.contract.entity.UfOtcdertra;
import com.engine.htxc.contract.entity.UserEntity;
import com.engine.integration.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;

import java.util.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Title: ecology-9
 * @Company: 泛微软件
 * @author: K1810050
 * @version: 1.0
 * @CreateDate: 2022/8/18 21:02
 * @Description: 发起合同流程相关查询dao
 * @ModifyLog: 添加注释
 **/
@Slf4j
public class ContractDao {

    public static final DbTools dbtools=new DbTools();

    /**
     * 根据社会代码查询对手方编码
     * @param codes
     * @return
     */
    public static List<String> selectCounterPartyByCertCode(List<String> codes){
        if(codes==null||codes.isEmpty()){
            return Collections.emptyList();
        }
        String sql="select dsfbm from uf_dsfgl t,uf_dsfgl_dt1 d where d.mainid=t.id and d.zjhm in ('"+ String.join("','", codes) +"')";
        final RecordSet recordSet = new RecordSet();
        recordSet.executeQuery(sql);
        List<String> result=new ArrayList<>();
        while (recordSet.next()){
            result.add(recordSet.getString("dsfbm"));
        }
        return result;
    }

    /**
     * 查询合同表主键id
     * @param uuid
     * @return
     */
    public static int getDataIdByUuid(RecordSetTrans rst,String uuid) throws Exception {
        rst.executeQuery("select id from UF_OTCDERTRA where modeuuid=? ", uuid);
        if (rst.next()) {
            return rst.getInt("id");
        }
        return -1;
    }


    public static Map<String, String> getUserByWorkcodeAndDeptCode(String workcode, String deptCode){
        String sql="select r.id as userid,r.lastname as username,r.telephone as telephone,r.email as email,r.departmentid as departmentid,r.workcode as workcode,d.departmentname as departmentname ,d.departmentcode as departmentcode from HRMRESOURCE r,hrmdepartment d where r.departmentid=d.id and  workcode=? and DEPARTMENTCODE=? ";
        final RecordSet rs = new RecordSet();
        final Map<String, String> result = new HashMap<>();
        rs.executeQuery(sql,workcode,deptCode);
        if (rs.next()) {
            for (String s : rs.getColumnName()) {
                result.put(s,rs.getString(s));
            }
        }
        return result;

    }

    /**
     * 根据工号和部门批量查询用户信息
     * @param userDeptInfoDTOS
     * @return
     */
    public static List<UserEntity> getUsersByWorkcodeAndDeptCodeList(List<UserDeptInfoDTO> userDeptInfoDTOS) {
        String sql="select w.jobtitlecode as jobcode,r.loginid,r.id as userid,r.lastname as username,r.telephone as telephone,r.email as email,r.departmentid as departmentid,r.workcode as workcode,d.departmentname as departmentname ,d.departmentcode as departmentcode from HRMRESOURCE r,hrmdepartment d,hrmjobtitles w where r.departmentid=d.id and w.id=r.jobtitle and   (workcode,DEPARTMENTCODE) in (%s)";
        sql = String.format(sql, String.join(",", Collections.nCopies(userDeptInfoDTOS.size(), "(?,?)")));

        List<Object> params=new ArrayList<>(userDeptInfoDTOS.size()*2);
        for (UserDeptInfoDTO userDeptInfoDTO : userDeptInfoDTOS) {
            params.add(userDeptInfoDTO.getUserCode());
            params.add(userDeptInfoDTO.getDeptCode());
        }
        return EntityCrudUtil.selectList(sql,UserEntity.class,params);
    }


    /**
     * 查询部门简称
     * @param deptId
     * @return
     */
    public static String getDeptAbbrByDeptId(int deptId){
        RecordSet rs = new RecordSet();
        // 获取部门id
        String sql = "select docnumabbreviation from hrmdepartmentdefined where   deptid=?";
        rs.executeQuery(sql,deptId);
        if (rs.next()) {
            return rs.getString("docnumabbreviation");
        }
        return "";
    }



    /**
     * 查询编号最大编码
     * @param deptAbbr
     * @param year
     * @param prefix
     * @return
     */
    public static int getMaxNum(String deptAbbr, String year, String prefix) {
        final RecordSet rs = new RecordSet();
        rs.executeQuery("select  max(zzbh)+1 as zzbh  from uf_ContractNoAggr where qz=? and year=? and zzjgjc=?", prefix, year, deptAbbr);
        if(rs.next()){
            return Math.max(rs.getInt("zzbh"),1);
        }else{
            return -1;
        }
    }
    public static void updateUfOtcdertraFiles(RecordSetTrans rst, UfOtcdertra contractMain) throws Exception {
        rst.executeUpdate("update uf_otcdertra set htzw=?,htfj=? where id=? ", contractMain.getHtzw(), contractMain.getHtfj(), contractMain.getId());
    }
    public static boolean checkTemplateNo(String templateNo){
        final RecordSet rs = new RecordSet();
        rs.executeQuery(" SELECT  count(b.id) c FROM  docimagefile a ,uf_wdzx b,imagefile c ,uf_wdzx_dt1 d where  a.imagefileid=b.wj and a.imagefileid=c.imagefileid and b.id=d.mainid and d.zt=1 and b.mbbh=?",templateNo);
        if(rs.next()){
           return rs.getInt("c")>0;
        }
        return false;
    }

    public static List<Integer> findCounterparty(List<CounterPartyDTO> counterPartyDTOS){
        String sql="select a.id from  uf_dsfgl a ,  uf_dsfgl_dt1 b   where  b.mainid=a.id and  (b.zjlx,b.zjhm) in (%s)";
        sql = String.format(sql, String.join(",", Collections.nCopies(counterPartyDTOS.size(), "(?,?)")));
        List<String> params=new ArrayList<>(counterPartyDTOS.size()*2);
        for (CounterPartyDTO counterPartyDTO : counterPartyDTOS) {
            params.add(counterPartyDTO.getCertType());
            params.add(counterPartyDTO.getCertNo());
        }
        final RecordSet rs = new RecordSet();
        rs.executeQuery(sql,params);
        List<Integer> result=new ArrayList<>();
        while (rs.next()){
            result.add(rs.getInt("id"));
        }
        return result;
    }

    public static List<String> findContractSeal(List<String> seals){
        String sql="select id from uf_ContractSeal where yzbh in (%s)";
        sql=String.format(sql, String.join(",", Collections.nCopies(seals.size(), "?")));
        final RecordSet rs = new RecordSet();
        rs.executeQuery(sql,seals);
        List<String> result=new ArrayList<>();
        while (rs.next()){
            result.add(rs.getString("id"));
        }
        return result;
    }


    public static boolean checkCategory(String categeryId) {
        final RecordSet rs = new RecordSet();
        rs.executeQuery("select count(id) c from uf_type_of_contract where  bzsm=?",categeryId);
        if(rs.next()){
            return rs.getInt(1)>0;
        }
        return false;
    }
    /**
     * 查询合同的编号
     * @title getSealNocount
     * @author K1810015
     * @updateTime 2022/9/2 17:23
     */
    public static String getSealCount(String tablename,String htbh){
        if(StringUtils.isBlank(tablename) && StringUtils.isBlank(htbh)){
            return "";
        }
        String sql="select  wm_concat_old(yz) as yz from "+ tablename+" where 1=1 and htbh in ("+ Arrays.stream(htbh.split(",")).map(item->"\'"+item+"\'").collect(Collectors.joining(","))+")";
        return  dbtools.getsqlonevalue(sql);
    }

    /**
     *根据工号和部门查询 单个直接选择，多个若有jobCode根据jobCode查询，没有jobCode默认选主岗 ，若该部门没有主岗多个都是兼岗都不取  校验时报错
     * @param userDeptInfoDTOS
     * @return
     */
    public static List<UserEntity> getUsersByWorkcodeAndJobCodeList(List<UserDeptInfoDTO> userDeptInfoDTOS){
        final List<UserEntity> users = getUsersByWorkcodeAndDeptCodeList(userDeptInfoDTOS);
        //按工号收集用户
        Map<String, List<UserEntity>> userMap = getUserMap(users);
        //按工号收集岗位
        Map<String, String> userJobCodeMap = getUserJobCodeMap(userDeptInfoDTOS);
        return getUserEntityList(userJobCodeMap, userMap);
    }


    private static Map<String, String> getUserJobCodeMap(List<UserDeptInfoDTO> userDeptInfoDTOS) {
        Map<String,String> userJobCodeMap=new HashMap<>();
        for (UserDeptInfoDTO userDeptInfoDTO : userDeptInfoDTOS) {
            userJobCodeMap.put(userDeptInfoDTO.getUserCode(),userDeptInfoDTO.getJobCode());
        }
        return userJobCodeMap;
    }

    private static Map<String, List<UserEntity>> getUserMap(List<UserEntity> users) {
        Map<String,List<UserEntity>> userMap=new HashMap<>();
        for (UserEntity user : users) {
            List<UserEntity> userAccountList = userMap.get(user.getWorkcode());
            if(null== userAccountList){
                userAccountList= new ArrayList<>();
                userMap.put(user.getWorkcode(),userAccountList);
            }
            userAccountList.add(user);
        }
        return userMap;
    }

    private static List<UserEntity> getUserEntityList(Map<String, String> userJobCodeMap, Map<String, List<UserEntity>> userMap) {
        //根据工号和部门查询 查到单个账号直接选择，多个账号若传有jobCode根据jobCode查询，没有jobCode默认选主岗 ，若该部门没有主岗多个都是兼岗都不取  校验时报错
        List<UserEntity> userEntityList=new ArrayList<>();
        for (Map.Entry<String, List<UserEntity>> userEntry : userMap.entrySet()) {
            final List<UserEntity> userEntities = userEntry.getValue();
            //单个直接取
            if(userEntities.size()==1){
                userEntityList.add(userEntities.get(0));
            }else{
                log.info("工号[{}]查到[{}]个账号",userEntry.getKey(),userEntities.size());
                //多个账号若有jobCode根据jobCode查询，没有传jobCode选择主岗 否则出错
                UserEntity userEntity = findUserWithJobCodeOrMajorPosition(userEntry.getKey(),userEntities, userJobCodeMap);
                if(null!=userEntity){
                    userEntityList.add(userEntity);
                }else{
                    log.error("工号[{}]查询账号出错",userEntry.getKey());
                }
            }

        }
        return userEntityList;
    }

    private static UserEntity findUserWithJobCodeOrMajorPosition(String userCode,List<UserEntity> userEntities, Map<String,String> userJobCodeMap) {
        final String jobCode = userJobCodeMap.get(userCode);
        if(!StringUtils.isBlank(jobCode)){
            log.info("工号[{}]传入岗位:[{}]",userCode,jobCode);
            for (UserEntity userEntity : userEntities) {
                if(userEntity.getJobCode().equals(jobCode)){
                    return userEntity;
                }
            }
        }
        log.info("工号[{}]查询主岗",userCode);
        //没有传jobCode选择主岗
        return findMajorPositionUser(userEntities);
    }

    private static UserEntity findMajorPositionUser(List<UserEntity> userEntities) {
        for (UserEntity userEntity : userEntities) {
            //工号和登录号相等是主岗
            if(userEntity.getWorkcode().equals(userEntity.getLoginid())){
                return userEntity;
            }
        }
        return null;
    }
}
