package com.engine.htxc.contract.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.definedfield.HrmFieldManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ContractUtil {

    private ContractUtil(){

    }

    /**
     * 查询表单字段
     * @param tablename
     * @return
     */
    public static Map<String, Map<String,String>> getTableFieldInfo(String tablename){
        return  getTableFieldInfo(tablename,0);
    }

    /**
     * 获取表单字段信息
     * @param tablename
     * @param dtnum
     * @return
     */
    public static Map<String,Map<String,String>> getTableFieldInfo(String tablename,int dtnum){
        Map<String,Map<String,String>> infoMap = new HashMap<>();
        RecordSet rs = new RecordSet();
        String fieldsSql = " select b.* from workflow_bill a,workflow_billfield b " +
                " where a.id=b.billid and a.tablename=? ";
        if(dtnum>0){
            String dtname = tablename+"_dt"+dtnum;
            fieldsSql += " and detailtable = '"+dtname+"' ";
        }else{
            fieldsSql += " and detailtable is null ";
        }

        rs.executeQuery(fieldsSql,tablename);
        while(rs.next()){
            String fieldid = Util.null2String(rs.getString("id"));
            String fieldname = Util.null2String(rs.getString("fieldname")).toLowerCase();
            String fielddbtype =  Util.null2String(rs.getString("fielddbtype"));
            String fieldhtmltype =  Util.null2String(rs.getString("fieldhtmltype"));
            String type =  Util.null2String(rs.getString("type"));

            Map<String,String> item = new HashMap<>();
            item.put("fieldid",fieldid);
            item.put("fieldname",fieldname);
            item.put("fielddbtype",fielddbtype);
            item.put("fieldhtmltype",fieldhtmltype);
            item.put("type",type);

            infoMap.put(fieldname,item);

        }
        return infoMap;
    }

    /**
     * 合同审批发起节点构建合同查询参数
     * @param htlb
     * @return
     */
    public static JSONArray getParams(String htlb, String tableName){
        RecordSet rs = new RecordSet();
        JSONArray paramArr = new JSONArray();
        String condition = String.format("'%s'", StringUtils.join(htlb.split(","),"','"));
        String sql = " select t.* from " +
                "(select row_number() over(partition by htbh order by dqbb desc) rn,c.* " +
                " from ( select htbh,dqbb,sjfl,a.htlx from "+tableName+" a,uf_type_of_contract b " +
                " where substr(a.htlx,instr(a.htlx,'_')+1) =b.htlxbm  " +
                " and a.htbh in("+condition+") " +
                " ) c " +
                ") t where t.rn=1 ";

        rs.execute(sql);
        while (rs.next()){
            String htbh = Util.null2String(rs.getString("htbh"));
            String version = Util.null2String(rs.getString("dqbb"));
            String sjfl = Util.null2String(rs.getString("sjfl"));
            String htlx = Util.null2String(rs.getString("htlx"));

            JSONObject paramObj = new JSONObject();
            paramObj.put("htbh",htbh);
            paramObj.put("version",version);
            paramObj.put("fhtfl",sjfl);
            paramObj.put("htlx",htlx);
            paramArr.add(paramObj);
        }
        return paramArr;
    }

    /**
     * 根据合同类型查询合同主表名
     * @param htlx
     * @return
     */
    public static String getContractTableName(String htlx){
        return getContractTableName(htlx,-1);
    }

    /**
     * 根据合同类型查询合同相关名
     * @param htlx 合同类型
     * @param type 表类型
     * @return
     */
    public static String getContractTableName(String htlx,int type){
        String tableName = "";
        String configSql = "select jmbd from uf_htspckhtqcpzb where htfl=? ";
        if(type>=0){
            configSql = " select b.jmbd from uf_htspckhtqcpzb a,uf_htspckhtqcpzb_dt1 b where a.id=b.mainid and htfl=? and zslb="+type;
        }
        RecordSet rs = new RecordSet();
        rs.executeQuery(configSql,htlx);
        if(rs.next()){
            tableName = Util.null2String(rs.getString("jmbd")) ;
        }
        return tableName;
    }


    /**
     * 获取字段的显示值
     * @param fieldInfo 字段信息
     * @param fieldvalue  字段值
     * @param user
     *
     * @return
     */
    public static String getFieldValue(Map<String,String> fieldInfo, String fieldvalue, User user){
        String fieldid = fieldInfo.get("fieldid");
        String fiedlddbtype = fieldInfo.get("fielddbtype");
        String fieldhtmltype = fieldInfo.get("fieldhtmltype");
        String detailtype = fieldInfo.get("type");
        String showValue = fieldvalue;

        try{
            if("5".equals(fieldhtmltype)){
                // 查询选择框的所有可以选择的值
                RecordSet rs = new RecordSet();
                rs.executeQuery("select selectvalue,selectname from workflow_SelectItem where cancel=0 and fieldid =? and selectvalue=? ",new Object[]{fieldid,fieldvalue});
                if (rs.next()) {
                    showValue = Util.null2String(rs.getString("selectname"));
                }
            }else if("6".equals(fieldhtmltype)){
                //doc类型
                if(fieldvalue.length()>0){
                    RecordSet rs = new RecordSet();
                    rs.executeQuery("select docid,imagefileid, imagefilename from docimagefile where docid=?  order by versionid desc ",fieldvalue);
                    if (rs.next()) {
                        String docid = rs.getString("docid");
                        String imagefileid = rs.getString("imagefileid");
                        String imagefilename = rs.getString("imagefilename");
                        showValue = docid+","+imagefileid+","+imagefilename;
                    }
                }
            }else if("3".equals(fieldhtmltype) && fieldvalue.length()>0){
                HrmFieldManager hrmFieldManager = new HrmFieldManager();
                showValue = hrmFieldManager.getFieldvalue(user, fiedlddbtype, Util.getIntValue(fieldid), Util.getIntValue(fieldhtmltype), Util.getIntValue(detailtype), fieldvalue, 0);
            }
        }catch (Exception e){
            new BaseBean().writeLog(e);
        }
        return showValue;
    }


    /**
     * 查询合同基本要素信息
     * @param htbh 合同编号
     * @param htlx 合同类型
     * @param user
     * @return
     */
    public static Map<String,Object> getContractMainData(String htbh,String htlx,User user){
        Map<String,Object> htitem = new HashMap<String,Object>();
        RecordSet rs = new RecordSet();
        String configSql = " select jmbd,htxxzszd from uf_htspckhtqcpzb where htfl=? ";
        rs.executeQuery(configSql,htlx);
        if(rs.next()){
            //表单名
            String jmbd = Util.null2String(rs.getString("jmbd"));
            //表单字段
            String htxxzszd = Util.null2String(rs.getString("htxxzszd"));

            String baseInfoSql = "  select * from (select "+htxxzszd+" from "+jmbd+" where  htbh=? order by dqbb desc ) where rownum=1 ";
            Map<String,Map<String,String>> mainTableFieldInfo = ContractUtil.getTableFieldInfo(jmbd,0);
            rs.executeQuery(baseInfoSql,htbh);
            if(rs.next()){
                String[] columns = rs.getColumnName();
                for(int i=0;i<columns.length;i++){
                    String fieldname = columns[i].toLowerCase();
                    String fieldvalue = Util.null2String(rs.getString(fieldname));
                    htitem.put(fieldname,fieldvalue);
                    if(!"id".equals(fieldname)){
                        Map<String,String> fieldInfo = mainTableFieldInfo.get(fieldname);
                        String showname = getFieldValue(fieldInfo,fieldvalue,user);
                        htitem.put(fieldname+"span",showname);
                    }
                }
            }
        }
        return htitem;
    }

    /**
     * 获取合同文件数据
     * @param htlx  合同类型
     * @param mainid 主数据id
     * @param type 正文或附件
     * @param user 当前用户
     * @return
     */
    public static List<Map<String,Object>> getContractFileData(String htlx, int mainid, int type, User user){
        List<Map<String,Object>> dataList = new ArrayList<>();
        RecordSet rs = new RecordSet();
        RecordSet rs2 = new RecordSet();
        String configSql = " select zslbms,b.jmbd,htxxmxzszd from uf_htspckhtqcpzb a,uf_htspckhtqcpzb_dt1 b " +
                "where a.id=b.mainid and htfl=? and zslb=? ";
        rs.executeQuery(configSql,new Object[]{htlx,type});
        if(rs.next()) {
            String jmbd = Util.null2String(rs.getString("jmbd"));
            String htxxmxzszd = Util.null2String(rs.getString("htxxmxzszd"));

            String mainTable = jmbd.substring(0,jmbd.lastIndexOf("_"));
            int dtnum = Integer.parseInt(jmbd.substring(jmbd.lastIndexOf("dt")+2));
            Map<String,Map<String,String>> dtFieldInfo = getTableFieldInfo(mainTable,dtnum);
            String dataSql = " select "+htxxmxzszd+" from "+jmbd+" where mainid=? order by yyfs ";
            rs2.executeQuery(dataSql,mainid);
            String[] columns = rs2.getColumnName();
            while (rs2.next()){
                Map<String, Object> item = new HashMap<String, Object>();
                for (int i = 0; i < columns.length; i++) {
                    String fieldname = columns[i].toLowerCase();
                    String fieldvalue = Util.null2String(rs2.getString(fieldname));
                    item.put(fieldname, fieldvalue);
                    //id字段不处理
                    if("id".equals(fieldname)){
                        continue;
                    }
                    //用印后文件字段可能包含多个文件单独处理
                    if("yyhwj".equals(fieldname)){
                        if(StringUtils.isNotBlank(fieldvalue)){
                            List<Map<String,Object>> esealFileList = getEsealFile(fieldname,fieldvalue,dtFieldInfo,user);
                            item.put(fieldname+"Obj", esealFileList);
                        }
                        continue;
                    }
                    addFieldShowName(item,fieldname,fieldvalue,dtFieldInfo,user);
                }
                dataList.add(item);
            }
        }
        return dataList;
    }

    /**
     * 添加字段的显示值
     * @param item
     * @param fieldname
     * @param fieldvalue
     * @param tableField
     * @param user
     * @return
     */
    public static Map<String, Object> addFieldShowName(Map<String, Object> item,String fieldname,String fieldvalue,Map<String,Map<String,String>> tableField, User user){
        Map<String, String> fieldInfo = tableField.get(fieldname);
        String showname = getFieldValue(fieldInfo, fieldvalue,user);
        String fieldhtmltype = fieldInfo.get("fieldhtmltype");
        if ("6".equals(fieldhtmltype) && !"".equals(showname)) {
            String[] docInfo = showname.split(",");
            if (docInfo.length == 3) {
                item.put("docid", docInfo[0]);
                item.put("imagefileid", docInfo[1]);
                item.put("imagefilename", docInfo[2]);
            }
        }else if("3".equals(fieldhtmltype) && !"".equals(showname)){
            String[] fieldvalues = Util.splitString(fieldvalue, ",");
            String[] fieldshownames = Util.splitString(showname, ",");
            List<Map<String, Object>> replaceDatas = new ArrayList<Map<String, Object>>();
            for(int j=0; fieldvalues!=null&&j<fieldvalues.length;j++){
                if(fieldvalues.length != fieldshownames.length){
                    break;
                }
                if(Util.null2String(fieldshownames[j]).length()==0){
                    continue;
                }
                Map<String, Object> replaceData = new HashMap<String, Object>();
                replaceData.put("id", fieldvalues[j]);
                replaceData.put("name", fieldshownames[j]);
                replaceDatas.add(replaceData);
            }
            item.put(fieldname + "span", showname);
            item.put(fieldname + "Obj",replaceDatas);
        }else {
            item.put(fieldname + "span", showname);
        }
        return item;
    }

    /**
     * @description: 获取用印后文件
     * @version: 1.0
     * @author: wanxq
     * @date: 2022年08月23 10:36:12
     * @param: [fieldname, fieldvalue, tableField, user]
     * @return: java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     **/
    public static List<Map<String,Object>> getEsealFile(String fieldname, String fieldvalue,Map<String,Map<String,String>> tableField,User user){
        List<Map<String,Object>> esealFileList = new ArrayList<>();
        Map<String, String> fieldInfo = tableField.get(fieldname);
        String[] sealFileIds = fieldvalue.split(",");
        for(int i=0;i<sealFileIds.length;i++){
            String showname = getFieldValue(fieldInfo, sealFileIds[i],user);
            if(!"".equals(showname)){
                String[] docInfo = showname.split(",");
                if (docInfo.length == 3) {
                    Map<String,Object> fileMap = new HashMap<>();
                    fileMap.put("docid", docInfo[0]);
                    fileMap.put("imagefileid", docInfo[1]);
                    fileMap.put("imagefilename", docInfo[2]);
                    esealFileList.add(fileMap);
                }
            }
        }
        return esealFileList;
    }

    /**
     * 根据合同类型获取默认建模查看页面地址
     * @param htlx 合同类型
     * @return
     */
    public static String getViewUrl(String htlx){
        return getViewUrl(htlx,"0");
    }

    /**
     * 根据合同类型获取默认建模查看页面地址
     * @param htlx 合同类型
     * @return
     */
    public static String getViewUrl(String htlx,String ismobile){
        String viewUrl = "";
        RecordSet rs = new RecordSet();
        String configSql = " select jmckmburl,mobiledydjmckurl from uf_htspckhtqcpzb where htfl=? ";
        rs.executeQuery(configSql,htlx);
        if(rs.next()){
            viewUrl = Util.null2String(rs.getString("jmckmburl"));
            if("1".equals(ismobile)){
                viewUrl = Util.null2String(rs.getString("mobiledydjmckurl"));
            }
        }
        return viewUrl;
    }

    public static String getEditUrl(String wfunnumber,String htlx,String nodeunnumber){
        String editUrl = "";
        RecordSet rs = new RecordSet();
        String configSql = " select jmmburl from uf_contapprtemp where lc=? and htlx=? and lcjd=? ";
        rs.executeQuery(configSql,new Object[]{wfunnumber,htlx,nodeunnumber});
        if(rs.next()){
            editUrl = Util.null2String(rs.getString("jmmburl"));
        }
        return editUrl;
    }
}
