package com.weaver.seconddev.njwebservice.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.weaver.common.hrm.util.Util;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import com.weaver.seconddev.njwebservice.entity.DataOptions;
import com.weaver.seconddev.njwebservice.entity.FormDataDuty;
import com.weaver.verupgrade.conn.CONN_TYPE;
import com.weaver.verupgrade.conn.RecordSet;
import com.weaver.verupgrade.hrm.resource.ResourceComInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author liang.cheng
 * @Date 2025/1/7 11:20 AM
 * @Description: 二开工具类
 * @Version 1.0
 */
public class SecondUtil {
    private final static Logger log = LoggerFactory.getLogger(SecondUtil.class);


    public static String getNacosContent(String dataId,String group,String key) {
        String configSingle = "";
        // 定义 Nacos 服务器地址和配置信息
        String serverAddr = "10.6.24.64:20000";

        // 初始化 Nacos 配置服务
        Properties properties = new Properties();
        properties.put("serverAddr", serverAddr);

        try {
            ConfigService configService = NacosFactory.createConfigService(properties);
            String content = configService.getConfig(dataId, group, 5000);
            log.error("Config content: " + content);

            // 解析 Properties 文件
            Properties prop = new Properties();
            prop.load(new java.io.ByteArrayInputStream(content.getBytes()));
            configSingle = prop.getProperty(key);
        } catch (NacosException | java.io.IOException e) {
            log.error("Failed to get config: " + e.getMessage());
        }
        return configSingle;
    }

    public static String getWorkflowConfig(String loginName) {
        RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
        String poolname = CONN_TYPE.ebuilder.getType();
        String pwd = "";
        String sql = "select pro from uf_submitconfig where zdmc = '"+loginName+"'";
        rs.executeSql(sql,poolname);
        if (rs.next()){
            pwd = Util.null2String(rs.getString("pro"));
        }
        return pwd;
    }

    public static String validationParam(String loginName,String password,String workflowId,String creator) {
        //1.权限判断 （日志返回获取nacos文件权限不足 todo）
//        String pwd = getNacosContent("weaver-secondev-wsaccount.properties", "DEFAULT_GROUP", loginName);
//        log.error("配置文件获取值："+pwd);
//        if(pwd == null || !pwd.equals(password)){
//            return "权限不足...";
//        } 采用eb表单

        String pwd = getWorkflowConfig(loginName);
        log.error("validationParam pwd = " + pwd);
        if("".equals(pwd) || !pwd.equals(password)){
            return "该流程id不在可创建流程列表";
        }

        //2.todo e10获取ip地址 log4fj记录
        log.error("调用主机ip地址日志记录");

        //3.流程名 流程ID
        if ("".equals(workflowId)) {
            return "流程ID不能为空...";
        }

        //4.todo 流程id不存在时默认流程 e10不知道怎么查

        //5.创建人
        if("".equals(creator)) {
            return "创建人不能为空...";
        }

        return "";
    }


    /**
     * 获取明细表Id
     * @param workflowId
     * @return
     */
    public static List<Long> getDetailFormId(String workflowId,String zhsjy) {
        log.error("getDetailFormId start : " + workflowId );
        log.error("getDetailFormId zhsjy : " + zhsjy );
        List<Long> formIdList = new ArrayList();
        RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
        String poolname = zhsjy;
        String sql = "select form_id from e10_core_business.dbo.form_table where form_id in (select id from  e10_core_business.dbo.sub_form where form_id in (select relatekey from e10_core_business.dbo.wfp_relateform  where workflowid = '"+workflowId+"'))";
        log.error("getDetailFormId sql : " + sql);
        rs.executeSql(sql,poolname);
        while (rs.next()){
            formIdList.add(Util.getLongValue(rs.getString("form_id")));
        }

        log.error("getDetailFormId formIdList : " + formIdList);
        return formIdList;
    }


    /**
     * 表单字段构建
     * @return
     */
    public static JSONObject getFromDataByDataDetails(List<FormDataDuty> formDataDutyList) {
        JSONObject formData = new JSONObject();
        formData.put("module","workflow");

        JSONArray dataDetails = new JSONArray();
        formData.put("dataDetails", dataDetails);

//        JSONObject inputDataKey = new JSONObject();
//        inputDataKey.put("dataKey", "sqdh");
//        inputDataKey.put("content", "12345");
//        dataDetails.add(inputDataKey);
//
//        //申请人
//        JSONObject sqr = new JSONObject();
//        dataDetails.add(sqr);
//        JSONArray dataOptions = new JSONArray();
//        sqr.put("dataKey","sqr");
//        sqr.put("dataOptions",dataOptions);
//
//        JSONObject option = new JSONObject();
//        option.put("optionId",100001700000063120L);
//        dataOptions.add(option);
//
//
//        //申请部门
//
//        JSONObject sqbm = new JSONObject();
//        dataDetails.add(sqbm);
//        JSONArray dataOptions_sqbm = new JSONArray();
//        sqbm.put("dataKey","sqbm");
//        sqbm.put("dataOptions",dataOptions_sqbm);
//
//        JSONObject option_sqbm = new JSONObject();
//        option_sqbm.put("optionId",100001590000004676L);
//        dataOptions_sqbm.add(option_sqbm);
//
//        JSONObject aa1 = new JSONObject();
//        dataDetails.add(aa1);
//        aa1.put("dataKey","wlbh");
//        aa1.put("dataIndex",1L);
//        aa1.put("content","1");
//        aa1.put("subFormId","100003690000001814");
//
//        JSONObject cc1 = new JSONObject();
//        dataDetails.add(cc1);
//        JSONArray ccOption = new JSONArray();
//        cc1.put("dataKey","cs");
//        cc1.put("dataIndex",1L);
//        cc1.put("subFormId","100003690000001814");
//        cc1.put("dataOptions",ccOption);
//        JSONObject option_cc = new JSONObject();
//        option_cc.put("optionId",100001700000063120L);
//        ccOption.add(option_cc);
//
//        JSONObject bb1 = new JSONObject();
//        dataDetails.add(bb1);
//        bb1.put("dataKey","jey");
//        bb1.put("dataIndex",1L);
//        bb1.put("content","55.42");
//        bb1.put("subFormId","100003690000001814");




        //
        formDataDutyList.forEach(formDataDuty -> {
            if (formDataDuty.getSubFormId() != null) {
                //明细表
                if (formDataDuty.getDataOptions() == null) {
                    //普通字段
                    JSONObject inputDataKey = new JSONObject();
                    inputDataKey.put("dataKey", formDataDuty.getDataKey());
                    inputDataKey.put("dataIndex", formDataDuty.getDataIndex());
                    inputDataKey.put("content", formDataDuty.getContent());
                    inputDataKey.put("subFormId", formDataDuty.getSubFormId());
                    dataDetails.add(inputDataKey);
                }else {
                    JSONObject details = new JSONObject();
                    dataDetails.add(details);

                    JSONArray dataOptions = new JSONArray();
                    details.put("dataKey", formDataDuty.getDataKey());
                    details.put("dataIndex", formDataDuty.getDataIndex());
                    details.put("subFormId", formDataDuty.getSubFormId());

                    details.put("dataOptions", dataOptions);
                    List<DataOptions> dataOptions1 = formDataDuty.getDataOptions();
                    dataOptions1.forEach(e -> {
                        JSONObject option = new JSONObject();
                        option.put("optionId", e.getOptionId());
                        dataOptions.add(option);
                    });
                }

            }else  {
                //主表
                if (formDataDuty.getDataOptions() == null) {
                    //普通字段
                    JSONObject inputDataKey = new JSONObject();
                    inputDataKey.put("dataKey", formDataDuty.getDataKey());
                    inputDataKey.put("content", formDataDuty.getContent());
                    dataDetails.add(inputDataKey);
                }else {
                    //浏览按钮字段
                    // 浏览按钮
                    JSONObject details = new JSONObject();
                    dataDetails.add(details);

                    JSONArray dataOptions = new JSONArray();
                    details.put("dataKey", formDataDuty.getDataKey());
                    details.put("dataOptions", dataOptions);

                    List<DataOptions> dataOptions1 = formDataDuty.getDataOptions();
                    dataOptions1.forEach(e -> {
                        JSONObject option = new JSONObject();
                        option.put("optionId", e.getOptionId());
                        //fieldType 3为附件
                        if (formDataDuty.getFieldType() == 3) {
                            option.put("content", e.getContent());
                        }
                        dataOptions.add(option);
                    });

                }
            }
        });

        return formData;
    }

    /**
     * 获取表名
     * @param workflowId
     * @return
     */
    public static String getTableName(String workflowId) {
        RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
        String poolname = CONN_TYPE.workflow.getType();
        String tableName = "";
        String sql = "select table_name from e10_core_business.dbo.form_table where \n" +
                " form_id = (select relatekey from e10_core_business.dbo.wfp_relateform where workflowid = '"+workflowId+"')";

        log.error(" SecondUtil getTableName sql " + sql);
        rs.executeSql(sql,poolname);
        while (rs.next()){
            tableName = Util.null2String(rs.getString("table_name"));
        }
        log.error(" SecondUtil tableName " + tableName);
        return tableName;
    }

    /**
     * 获取工作流Id
     * @param requestId
     * @return
     */
    public static String getWorkflowIdByReq(String requestId) {
        RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
        String poolname = CONN_TYPE.workflow.getType();
        String workflowId = "";
        String sql = "select workflowid from e10_core_business.dbo.wfc_form_data where requestid = '"+requestId+"'\n" +
                " and delete_type = 0";
        log.error(" SecondUtil getWorkflowIdByReq sql " + sql);
        rs.executeSql(sql,poolname);
        if (rs.next()){
            workflowId = Util.null2String(rs.getString("workflowid"));
        }
        log.error(" SecondUtil workflowId " + workflowId);
        return workflowId;
    }

    public static String getidByrequestid(String requestId) {
        RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
        String poolname = CONN_TYPE.workflow.getType();
        String dataid = "";
        String sql = "select workflowid,dataid from e10_core_business.dbo.wfc_form_data where requestid = '"+requestId+"'\n" +
                " and delete_type = 0";
        log.error(" SecondUtil getidByrequestid sql " + sql);
        rs.executeSql(sql,poolname);
        if (rs.next()){
            dataid = Util.null2String(rs.getString("dataid"));
        }
        log.error(" SecondUtil dataid " + dataid);
        return dataid;
    }




    public static String getMeetingInfo(String loginname,String password,String companyIds,String startdate,String enddate) {
        net.sf.json.JSONObject object1 = new net.sf.json.JSONObject();
        try {

            //先判断是否有权限
            //String pwd = Util.null2String(getPropValue("htwsaccount", loginname)).trim();
            String pwd = getWorkflowConfig(loginname);

            if(pwd == null || !pwd.equals(password)){
                object1.put("status", "error");
                object1.put("msg", "权限不足");
                return object1.toString();
            }

            if(startdate==null||"".equals(startdate)||enddate==null||"".equals(enddate)){
                object1.put("status", "error");
                object1.put("msg", "时间不能为空");
                return object1.toString();
            }

            //HttpServletRequest request = XFireServletController.getRequest();
            //String ip = request.getRemoteAddr();//得到当前调用的主机IP
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String today = sdf.format(new Date());//当前时间
            log.error("excute webservice MeetingServiceServiceImpl start...");
            //writeLog("ip地址："+ip+" ,时间：" + today);

//            RecordSet rs1 = new RecordSet();//把当前调用的主机IP和时间记录在数据库中
//            rs1.execute("insert into uf_wslogs (host,datetime,type) values('"+ip+"','"+today+"','MeetingService')");

            if(companyIds == null || "".equals(companyIds)){
                object1.put("status", "error");
                object1.put("msg", "公司ID不能为空");
                return object1.toString();
            }

            //找出所有的会议室
            Map<String , String> meetingMap = new HashMap<>();
            RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
            rs.executeSql("select id,name from mt_room where org_id in ("+companyIds+")",CONN_TYPE.meeting.getType());
            while (rs.next()) {
                String id = Util.null2String(rs.getString("id"));
                String name = Util.null2String(rs.getString("name"));
                meetingMap.put(id, name);
            }

            if(meetingMap == null || meetingMap.size() <= 0){
                object1.put("status", "error");
                object1.put("msg", "找不到该公司下的会议室");
                return object1.toString();
            }

            log.error("找到会议室" + meetingMap.size() + "个");

            net.sf.json.JSONArray array = new net.sf.json.JSONArray();

//            String sql3 = "select t.id,t.name meetingname,t.address," +
//                    " t.begindate+' '+t.begintime as begindate," +
//                    " t.enddate+' '+t.endtime as enddate,t.caller,t.contacter,t.desc_n,t.hrmmembers,t.meetingstatus from Meeting t" +
//                    " where t.meetingstatus in (2,4) " +
//                    " and t.begindate+' '+begintime >= '"+startdate+"'" +
//                    " and t.enddate+' '+endtime <= '"+enddate+"'";

            String sql3 = "select a.id,a.name as meetingname,a.address,a.begin_datetime,a.end_datetime,a.caller,a.contacter,b.member_id,\n" +
                    " a.mt_status from mt_detail a left join mt_receipt_member b on a.id = b.mt_id where a.begin_datetime >= '"+startdate+"' " +
                    " and a.end_datetime <= '"+enddate+"' and a.mt_status in (2,4)";

            rs.execute(sql3,CONN_TYPE.meeting.getType());
            log.error("找到会议" + rs.getCounts() + "个");

            ResourceComInfo res = new ResourceComInfo();

            while (rs.next()) {//寻找meeting表中address多个的
                String address = Util.null2String(rs.getString("address"));
                String meetingname = Util.null2String(rs.getString("meetingname"));
                String begin = Util.null2String(rs.getString("begin_datetime"));
                String end = Util.null2String(rs.getString("end_datetime"));
                log.error("找到会议meetingname(" + meetingname + "),address(" + address + "),begin(" + begin + "),end(" + end + ")");
                if(address != null && !"".equals(address)){//去需要查询的公司下面的会议室匹配
                    String[] addressArray = address.split(",");
                    for(int i=0;i<addressArray.length;i++){
                        String str = addressArray[i];
                        Object name = meetingMap.get(str);
                        if(name != null && !"".equals(name.toString())){
                            net.sf.json.JSONObject object = new net.sf.json.JSONObject();
                            object.put("roomname", name.toString());
                            object.put("meetingname", meetingname);
                            object.put("begindate", begin);
                            object.put("enddate", end);
                            object.put("meetingId",rs.getString("id"));
                            object.put("caller",res.getLastnames(rs.getString("caller")));
                            object.put("contacter",res.getLastnames(rs.getString("contacter")));
                            object.put("content","");
                            object.put("members",res.getLastnames(rs.getString("member_id")));
                            object.put("meetingstatus",rs.getInt("mt_status"));
                            array.add(object);
                        }
                    }
                }
            }

            if(array != null && array.size() > 0){
                object1.put("status", "success");
                object1.put("msg", array.toString());
            }else{
                object1.put("status", "error");
                object1.put("msg", "找不到该时间段内的会议");
            }
        } catch (Exception e) {
            log.error("error：" + e.getMessage() );
            object1.put("status", "error");
            object1.put("msg", e.getMessage());
            return object1.toString();
        }

        return object1.toString();
    }


    public static String getUserId(int type,String value) {
        String userId = "";
        String columnName ="";
        switch (type) {
            case 2 :
                columnName = "username";
                break;
            case 3 :
                columnName = "USER_ID";
                break;
            case 4 :
                columnName = "mobile";
                break;
            case 5 :
                columnName = "email";
                break;
            default:
                columnName = "job_num";
                break;
        }
        RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
        String poolname = CONN_TYPE.hrm.getType();
        String sql = "select ID from eteams.employee where delete_type = 0 and status = 'normal' and "+columnName+"= '"+value+"'";
        rs.executeSql(sql,poolname);
        if (rs.next()) {
            userId = Util.null2String(rs.getString("ID"));
        }
        return userId;
    }



}
