package com.engine.htxc.htqc.dao;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.interfaces.htsc.comInfo.PropBean;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Title: ecology-9
 * @Company: 泛微软件
 * @author: K1810039
 * @version: 1.0
 * @CreateDate: 2022-09-23 11:31
 * @Description: 合同模块相关Dao
 * @ModifyLog:
 **/
@Slf4j
public class HtqcDao {

    /**
     * 根据产品id获取对应的对手方编码和名称
     * @param productIds 产品id
     * @return 对手方 map{编码:名称}
     */
    public static Map<String, String> getDsfNameAndCodeDao(String productIds) {
        log.info("productIds:[{}]",productIds);
        Map<String, String> dsfMap = new HashMap<>();
        final RecordSet rs = new RecordSet();
        String prodIds = converString(productIds);
        log.info("prodIds:[{}]",prodIds);
        String sql = "select distinct a.SOCIALCREDITCODE,b.DSFMC from uf_prodcontrelation a left join uf_dsfgl b on b.DSFBM = a.SOCIALCREDITCODE where a.PRODUCTID in ("+prodIds+")";
        log.info(sql);
        try {
            rs.execute(sql);
            while (rs.next()){
                dsfMap.put(Util.null2String(rs.getString("SOCIALCREDITCODE")),Util.null2String(rs.getString("DSFMC")));
            }
        } catch (Exception e) {
            log.error("getDsfNameAndCode查询数据异常：",e);
        }
        log.info("dsfMap:[{}]", JSON.toJSONString(dsfMap));
        return dsfMap;
    }


    public static Map<String, Object> getContractInfoDao(String htbhs) {
        log.info("htbhs:[{}]",htbhs);
        Map<String, Object> resMap = new HashMap<>();
        final RecordSet rs = new RecordSet();
        String condition = String.format("'%s'", StringUtils.join(htbhs.split(","),"','"));
        String validSql = "  select htlx,count(1) num from uf_contractlist " +
                "where htbh in ("+condition+") group by htlx ";
        log.info(validSql);
        rs.execute(validSql);
        int count = rs.getCounts();
        resMap.put("count",count);
        log.info("count:[{}]",count);

        if(count == 1){
            rs.next();
            String htlx = Util.null2String(rs.getString("htlx"));
            resMap.put("htlx",htlx);
            log.info("htlx:[{}]",htlx);
            // 业务类
            if(htlx.contains("YW")){
                Map<Object, Object> yspflMap = new HashMap<>();
                String ywSql = "select yspfl from uf_otcdertra where HTBH in ("+condition+")";
                log.info(ywSql);
                RecordSet ywRs = new RecordSet();
                ywRs.execute(ywSql);
                while (ywRs.next()){
                    String yspfl = Util.null2String(ywRs.getString("yspfl"));
                    log.info("yspfl:[{}]",yspfl);
                    yspflMap.put(yspfl,yspfl);
                }
                log.info("yspflMap:[{}]",JSON.toJSONString(yspflMap));
                resMap.put("yspfl",yspflMap.size());
            }else {
                resMap.put("yspfl",1);
            }

            //查询合同所有附件
            String fjids = "";
            // by wf 添加印章字段、常用印章字段
            List<String> yzlist=new ArrayList<>();
            List<String> cyyzlist=new ArrayList<>();
            List<String> ztlist=new ArrayList<>();
            RecordSet rs2 = new RecordSet();

            String configSql = " select a.jmbd maintable,b.jmbd dttable,fjzd from uf_htspckhtqcpzb a, uf_htspckhtqcpzb_dt1 b " +
                    " where a.id=b.mainid and htfl='"+htlx+"'";
            log.info(configSql);
            rs.execute(configSql);
            while (rs.next()){
                String maintable = Util.null2String(rs.getString("maintable"));
                String dttable = Util.null2String(rs.getString("dttable"));
                String fjzd = Util.null2String(rs.getString("fjzd"));

                String fjSql = " select "+fjzd+" from "+maintable+" a,"+dttable+" b where a.id=b.mainid and htbh in("+condition+")";
                log.info(fjSql);
                rs2.execute(fjSql);
                while(rs2.next()){
                    String fj = Util.null2String(rs2.getString(fjzd));
                    fjids += fj+",";
                }
                log.info("1-fjids:[{}]",fjids);

                String yzSql = " select yz,cyyz,zt from "+maintable+"  where  htbh in("+condition+")";
                log.info(yzSql);
                rs2.execute(yzSql);
                while(rs2.next()){
                    yzlist.add(Util.null2String(rs2.getString("yz")));
                    cyyzlist.add(Util.null2String(rs2.getString("cyyz")));
                    ztlist.add(Util.null2String(rs2.getString("zt")));
                }
            }
            if(StringUtils.isNotBlank(fjids)){
                fjids = fjids.substring(0,fjids.length()-1);
            }
            log.info("2-fjids:[{}]",fjids);
            boolean flag= true;
            if(!ztlist.isEmpty()){
                flag= ztlist.stream().allMatch(item-> (",0,6,").contains("," + item + ","));
            }
            resMap.put("htfj",fjids);
            resMap.put("flag",flag);
            resMap.put("yz", Arrays.stream(String.join(",", yzlist).split(",")).distinct().collect(Collectors.joining(",")) );
            resMap.put("cyyz",Arrays.stream(String.join(",", cyyzlist).split(",")).distinct().collect(Collectors.joining(",")));
        }
        log.info("resMap:[{}]", JSON.toJSONString(resMap));
        return resMap;
    }


    /**
     * 将"1,2,3,.."格式的字符串，转换成"'1','2','3',..."格式的字符串
     * @param strs
     * @return
     */
    public static String converString(String strs){
        if (StringUtils.isNotBlank(strs)){
            String[] idStrs = strs.trim().split(",");
            if (idStrs.length > 0){
                StringBuffer sbf = new StringBuffer();
                for (String str : idStrs) {
                    if (StringUtils.isNotBlank(str)){
                        sbf.append("'").append(str.trim()).append("'").append(",");
                    }
                }
                if (sbf.length() > 0){
                    sbf = sbf.deleteCharAt(sbf.length() - 1);
                    return sbf.toString();
                }
            }
        }
        return "";
    }

    public static int getCurrentUserRole(String currentUserId){
        log.info("currentUserId:[{}]",currentUserId);
        // 获取 loginId
        String loginId = "";
        try {
            String sql = "select LOGINID from HRMRESOURCE where ID = ?";
            RecordSet rs = new RecordSet();
            rs.executeQuery(sql,currentUserId);
            if (rs.next()){
                loginId = Util.null2String(rs.getString("LOGINID"));
            }
            log.info("loginId:[{}]",loginId);
        } catch (Exception e) {
            log.error("查询用户loginId出错：",e);
        }
        if (StringUtils.isBlank(loginId)){
            log.info("当前用户[{}]的loginId未查到,请检查",currentUserId);
            return -1;
        }

        PropBean pb = new PropBean();
        // 总部办公室归档管理员角色，成员 loginId
        String [] zbbgsSysAdminArr = pb.getPropName("ht_zbbgsgdgly").split(",");
        // 部门年度归档管理员角色，成员loginId
        String [] bmndSysAdminArr = pb.getPropName("ht_bmndgdgly").split(",");
        // 业务主管部门归档管理员角色，成员loginId
        String [] ywzgbmSysAdminArr = pb.getPropName("ht_ywzgbmgdgly").split(",");

        int role = -1;
        // 判断当前用户的角色
        if (ArrayUtils.contains(zbbgsSysAdminArr,loginId)){
            // 总部办公室归档管理员
            log.info("当前用户[{}]为总部办公室归档管理员",loginId);
            role = 0;
        }else if (ArrayUtils.contains(bmndSysAdminArr,loginId)){
            // 部门年度归档管理员
            log.info("部门年度归档管理员-loginId:[{}]",loginId);
            role = 1;
        }else if (ArrayUtils.contains(ywzgbmSysAdminArr,loginId)){
            // 业务主管部门归档管理员
            log.info("业务主管部门归档管理员-loginId:[{}]",loginId);
            role = 2;
        }else {
            // 普通用户
            log.info("普通用户-loginId:[{}]",loginId);
            role = 3;
        }
        log.info("用户[{}]的身份:[{}]",loginId,role);
        return role;
    }

}
