package com.weaver.seconddev.njwebservice;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weaver.common.elog.util.DateUtils;
import com.weaver.common.hrm.util.HrmCommonUtil;
import com.weaver.common.hrm.util.StringUtils;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import com.weaver.framework.rpc.context.impl.TenantRpcContext;
import com.weaver.seconddev.njwebservice.entity.DataOptions;
import com.weaver.seconddev.njwebservice.entity.FormDataDuty;
import com.weaver.seconddev.njwebservice.prop.ConfigProp;
import com.weaver.seconddev.njwebservice.util.*;
import com.weaver.teams.domain.user.SimpleEmployee;
import com.weaver.verupgrade.conn.RecordSet;
import com.weaver.verupgrade.hrm.company.DepartmentComInfo;
import com.weaver.verupgrade.workflow.workflow.WorkflowAllComInfo;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import static com.weaver.seconddev.njwebservice.util.SecondUtil.getFromDataByDataDetails;


/**
 * 自动创建流程 webService
 */
@Service("autoCreateWorkflowService")
public class AutoCreateWorkflowService {

    private final static Logger log = LoggerFactory.getLogger(AutoCreateWorkflowService.class);

    @Autowired
    private HrmCommonUtil hrmCommonUtil;

    @Autowired
    private WorkflowAllComInfo workflowAllComInfo;

    @Autowired
    private DocUtil docUtil;

    @Autowired
    private DatabaseUtils databaseUtils;

    @Autowired
    private DepartmentComInfo departmentComInfo;

    @Autowired
    private ConfigProp configProp;

    private static final String HOST = "http://10.6.24.64:20600/papi/openapi";


    public String createWorkflow(String loginName, String password, String workflowId, String creator, String requestLevel, String mainTable , String[] detailTables){
        log.error("AutoCreateWorkflowService start");
        log.error("loginName:"+loginName+"=> password:"+password+"=> workflowId:"+workflowId+"=> creator:"+creator);
        log.error("requestLevel:"+requestLevel);
        log.error("mainTable:"+mainTable);
        String jtzhkey = configProp.getJtzhkey();
        String jtzhadmin = configProp.getJtzhadmin();
        //log.error("jtzhkey:"+jtzhkey+" jtzhadmin:"+itzhadmin);
        TenantRpcContext.setTargetTenantKey(jtzhkey);
        TenantRpcContext.setTargetEmployeeId(jtzhadmin);
         //实现自定义webservice接口逻辑
        String currentDate = DateUtils.getCurrentDate();
        String curDateTime = DateUtils.getCurDateTime();
        if(detailTables==null){
            log.error("明细表数据detailTables为null");
        }else{
            log.error("明细表数据detailTables:"+Arrays.toString(detailTables));
        }
//        String detailTablesStr = String.join(",", detailTables);

//        log.error("明细表数据:"+detailTablesStr);

        String workcode = creator;
        //1.入参校验
        String tips = SecondUtil.validationParam(loginName, password, workflowId, creator);
        if (!"".equals(tips)) {
            return tips;
        }

        //2.日志记录省略（todo）

        //E10 workflowId转换(未测试)
        WfUtil wfUtil = new WfUtil();
        Map<String, String> zhWfMap = wfUtil.getZhWfMap("t6kj9c07jr", creator, workflowId);

        workflowId = zhWfMap.get("workflowid");
        log.error("转换后的流程ID:"+workflowId);
        if(StringUtils.isEmpty(workflowId)) {
            return "E10流程ID转换失败，请假查e10_common.dbo.uf_zhwfid_mt配置信息";
        }

        String createTenantKey = zhWfMap.get("tenantKey");
        if(StringUtils.isEmpty(createTenantKey)) {
            return "E10获取流程对应租户失败，请假查e10_common.dbo.uf_zhwfid_mt配置信息";
        }

        String zhsjy = zhWfMap.get("zhsjy");

        //3.根据工号获取创建人id (租户概念后续增加)
        String groupId = "weaver-ebuilder-form-service";//不确定
        String sql = "select ID,TENANT_KEY from eteams.dbo.employee where status = 'normal' and job_num = '"+creator+"' and tenant_key = '"+createTenantKey+"'";

        Map<String,Object> recordMap = new HashMap<>();
//        String sourceType = "LOGIC";
        String sourceType = zhsjy;
        log.error("createWorkflow sql1 :"+sql + "   sourceType : " +sourceType);
        RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
        rs.executeQuery(sql, zhsjy);
        String tenantKey = "";
        if(rs.next()){
            creator =  rs.getString("ID");
            tenantKey =  rs.getString("TENANT_KEY");
        }

//        Map<String, Object> result = databaseUtils.execute(sourceType, groupId, sql);
//        List<Map<String,Object>> recordList = databaseUtils.getDataSourceList(result);
//
//        log.error("recordList : "+recordList);
//        if(CollectionUtils.isNotEmpty(recordList)){
//            recordMap = recordList.get(0);
//        }
//        creator =  String.valueOf(recordMap.get("id"));
//        String tenantKey = (String)recordMap.get("tenant_key");

        log.error("创建人ID:" + creator + "   租户key:" + tenantKey);

        if(StringUtils.isEmpty(creator)){
            return "创建人ID信息为空，请检查人员信息";
        }
        //紧急程度默认值
        if ("".equals(requestLevel) || requestLevel == null) {
            requestLevel = "0";
        }



        List<Long> detailFormId = SecondUtil.getDetailFormId(workflowId,zhsjy);


        JSONObject param = new JSONObject();
        param.put("userid", Long.valueOf(creator));
        param.put("workflowId", Long.valueOf(workflowId));
        param.put("requestLevel", Integer.parseInt(requestLevel));


        //4.主表数据 明细表数据 自动生成流程入参构造
        log.error("主表数据:"+mainTable);
        //主表数据 json {"sqr":"sqr1","date":"date1","hrm:zrr":"zrr1"}
        //字段名前面加 hrm:表示是人力资源字段
        if(mainTable == null || mainTable.equals("")){
            return "主表数据不能为空";
        }
        JSONObject jsonObject = JSONObject.parseObject(mainTable);
        Map<String, Object> mainMap = jsonObject.toJavaObject(Map.class);
        log.error("主表集合："+mainMap);
        List<FormDataDuty> formDataDutyList = new ArrayList();
        // 输出 Map 的内容
        for (Map.Entry<String, Object> entry : mainMap.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            FormDataDuty formDataDuty = FormDataDuty.builder().build();

            Long optionId = null;
//            log.error("入参key:"+key+" value:"+value);
            String code = "";
            JSONObject doc = new JSONObject();
            if (value instanceof String) {
                code = String.valueOf(value);
            } else if (value instanceof JSONObject) {
                 doc = (JSONObject) value;
            }else{
                code = String.valueOf(value);
            }

            if (!"".equals(key)) {
                if(key.contains("hrm:")){
                    //判断人力资源字段工号是否正确 (todo)
                    optionId = getIdByWorkcode(code,createTenantKey,zhsjy);
                    if(optionId == null) {
                        return "工号为空或不存在";
                    }
                    key = key.replace("hrm:", "");
                    formDataDuty.setDataKey(key);
                    formDataDuty.setFieldType(2);
                    DataOptions options = DataOptions.builder().optionId(optionId).build();
                    List<DataOptions> dataOptions = new ArrayList();
                    dataOptions.add(options);
                    formDataDuty.setDataOptions(dataOptions);
                } else if (key.contains("com:") || key.contains("dep:")) { //e10 分部部门同一个字段
                    if(key.split(":").length != 3){
                        return "主表字段名"+key+"不符合规则...";
                    }

                    String str2 = key.split(":")[1];//关联人力资源字段
                    String str3 = key.split(":")[2];//当前字段

                    if(mainMap.get("hrm:"+str2) != null){
                        String hrmResource = (String) mainMap.get("hrm:"+str2);
                        Long id = getIdByWorkcode(hrmResource,createTenantKey,zhsjy);
                        SimpleEmployee simpleEmployee = hrmCommonUtil.getSimpleEmployee(id);
                        log.error("simpleEmployee  == " + simpleEmployee.toString());
                        optionId = simpleEmployee.getDepartmentId();
                        if (key.contains("com:")) {
                            optionId = Long.valueOf(departmentComInfo.getSubcompanyid1(String.valueOf(optionId)));
                        }
                        key = str3;
                        formDataDuty.setDataKey(key);
                        formDataDuty.setFieldType(2);
                        DataOptions options = DataOptions.builder().optionId(optionId).build();
                        List<DataOptions> dataOptions = new ArrayList();
                        dataOptions.add(options);
                        formDataDuty.setDataOptions(dataOptions);
                    }else{
                        return  "主表字段"+key+"不包含关联字段" ;
                    }

                }else if(key.contains("doc:")){
                    key = key.replace("doc:", "");
                    if(key.length()==0){
                        return "主表上传附件字段名不符合规则";
                    }
                    if(doc.getString("filename") != null && doc.getString("content") != null) {
                        String docName = doc.getString("filename");
                        String base64 = doc.getString("content");
                        formDataDuty.setFieldType(3);
                        String docId = docUtil.createdocByBase642(docName, base64, "", creator, "");
                        log.error("生成的附件id："+docId);
                        formDataDuty.setDataKey(key);
                        DataOptions options = DataOptions.builder().optionId(Long.parseLong(docId)).content(docName).build();
                        List<DataOptions> dataOptions = new ArrayList();
                        dataOptions.add(options);
                        formDataDuty.setDataOptions(dataOptions);
                    }else {
                        return  "上传附件内容不符合规则...";
                    }

                }else {
//                    log.error("普通字段值："+value);
                    if(StringUtils.isNotEmpty(String.valueOf(value))){
                        formDataDuty.setFieldType(1);
                        formDataDuty.setDataKey(key);
                        formDataDuty.setContent(code);
                    }else{
//                        log.error("普通字段值为空");
                    }

                }
            }


            formDataDutyList.add(formDataDuty);
        }



        ///明细表数据
        //[[{"wlbh":"1","wlms":"2","pjxhj3y":"3","bylj":"4","kcsl":"5","tksl":"6","jey":"7","cbzx":"8"},{"wlbh":"1","wlms":"2","pjxhj3y":"3","bylj":"4","kcsl":"5","tksl":"6","jey":"7","cbzx":"8"}],[{"aa":"1","bb":"2"}]]

//        if (detailTablesStr.startsWith("[") && detailTablesStr.endsWith("]")) {
//            detailTablesStr = detailTablesStr.substring(1, detailTablesStr.length() - 1);
//        }
//        log.error("截取后的明细表数据："+detailTablesStr);

//        JSONArray outerArray = JSON.parseArray(detailTablesStr);
        if(detailTables==null){

        }else{
            log.error("处理明细数据");
            if(detailTables.length>0){
                // 遍历外部 JSONArray
                for (int i = 0; i < detailTables.length; i++) {
                    JSONArray innerArray = JSONArray.parseArray(detailTables[i]);  // 获取内部的 JSONArray
                    log.error("innerArray:"+innerArray);

                    if(innerArray.size()>0){
                        //判断明细表id是否存在
                        if (detailFormId.size() < i+1) {
                            log.error("明细表"+(i+1)+"form_id未找到或不存在");
                            return "明细表"+(i+1)+"form_id未找到或不存在";
                        }
                        Long subFormId = detailFormId.get(i);
                        log.error("明细表"+(i+1)+"form_id"+subFormId);

                        // 遍历内部 JSONArray
                        for (int j = 0; j < innerArray.size(); j++) {
                            JSONObject jsonDetail = innerArray.getJSONObject(j);
                            Long optionId = null;

                            // 遍历 JSONObject 的键值对
                            for (String key : jsonDetail.keySet()) {
                                FormDataDuty formDataDuty = FormDataDuty.builder().build();
                                String value = jsonDetail.getString(key);
                                if (!"".equals(key)) {
                                    if(key.contains("hrm:")){
                                        //判断人力资源字段工号是否正确 (todo)
                                        optionId = getIdByWorkcode(value,createTenantKey,zhsjy);
                                        if(optionId == null) {
                                            return "工号为空或不存在";
                                        }
                                        key = key.replace("hrm:", "");
                                        formDataDuty.setDataKey(key);
                                        formDataDuty.setDataIndex((long) (j + 1));
                                        formDataDuty.setSubFormId(subFormId);

                                        DataOptions options = DataOptions.builder().optionId(optionId).build();
                                        List<DataOptions> dataOptions = new ArrayList();
                                        dataOptions.add(options);
                                        formDataDuty.setDataOptions(dataOptions);
                                    } else if (key.contains("com:") || key.contains("dep:")) { //e10 分部部门同一个字段
                                        if(key.split(":").length != 3){
                                            return "明细表表字段名"+key+"不符合规则...";
                                        }

                                        String str2 = key.split(":")[1];//关联人力资源字段
                                        String str3 = key.split(":")[2];//当前字段

                                        if(mainMap.get("hrm:"+str2) != null){
                                            String hrmResource = (String) mainMap.get("hrm:"+str2);
                                            Long id = getIdByWorkcode(hrmResource,createTenantKey,zhsjy);
                                            SimpleEmployee simpleEmployee = hrmCommonUtil.getSimpleEmployee(id);
                                            optionId = simpleEmployee.getDepartmentId();
                                            if (key.contains("com:")) {
                                                optionId = Long.valueOf(departmentComInfo.getSubcompanyid1(String.valueOf(optionId)));
                                            }
                                            key = str3;
                                            formDataDuty.setDataKey(key);
                                            formDataDuty.setDataIndex((long) (j + 1));
                                            formDataDuty.setSubFormId(subFormId);
                                            DataOptions options = DataOptions.builder().optionId(optionId).build();
                                            List<DataOptions> dataOptions = new ArrayList();
                                            dataOptions.add(options);
                                            formDataDuty.setDataOptions(dataOptions);
                                        }else{
                                            return  "明细字段"+key+"不包含关联字段" ;
                                        }
                                    }else {
//                                log.error("明细表普通字段值："+value);
                                        if(StringUtils.isNotEmpty(value)){
                                            formDataDuty.setDataKey(key);
                                            formDataDuty.setDataIndex((long) (j + 1));
                                            formDataDuty.setContent(value);
                                            //目前写死 后续在找方法
                                            formDataDuty.setSubFormId(subFormId);
                                        }else{
//                                    log.error("明细表普通字段值为空");
                                        }

                                    }
                                    formDataDutyList.add(formDataDuty);
                                }

                            }

                        }
                    }

                }

                log.error("formDataDutyList数据："+formDataDutyList.size()+"-"+formDataDutyList);
            }
        }



        if(CollectionUtils.isNotEmpty(formDataDutyList)) {
            JSONObject fromDataByDataDetails = getFromDataByDataDetails(formDataDutyList);
            param.put("formData", fromDataByDataDetails);
        }


        //String formId = workflowAllComInfo.getFormId(workflowId);
        //log.error("表单id"+formId);

        //4.1 获取access_token ( 增加redis存储token todo)
        String token = "";
//        try {
//            token = AccessTokenUtil.getToken();
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
        try {
            token = AccessTokenUtil.getAccessToken(createTenantKey);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        log.error("access_token信息："+token);

        String url = HOST + "/api/workflow/core/paService/v1/doCreateRequest?access_token=" + token;

        JSONObject otherParams =new JSONObject();
        otherParams.put("isnextflow",1);
        param.put("otherParams",otherParams);

        log.error("表单json:"+param.toJSONString());
        // 远程调用创建流程。
        String response = HttpUtil.post(url, param.toJSONString());
        log.error("自动创建流程结果："+response);
        JSONObject responseObj = JSONObject.parseObject(response);
        Object message = responseObj.get("message");
        JSONObject messageObj = JSONObject.parseObject(message.toString());
        String errcode = messageObj.get("errcode").toString();

        log.error("errcode："+errcode);
        if(StringUtils.isNotEmpty(errcode)){
            if(messageObj.get("errcode").toString().equals("0")){
                log.error("requestId："+messageObj.get("requestId").toString());
                return Optional.ofNullable(messageObj.get("requestId")).map(Object::toString).orElse("");
            }else{
                log.error("errmsg："+messageObj.get("errmsg").toString());
                return messageObj.get("errmsg").toString();
            }
        }else{
            return "调用泛微流程创建接口失败";
        }

     }



    /**
     * 根据工号获取人员id
     * @param workcode
     * @return
     */
    private  Long getIdByWorkcode(String workcode,String createTenantKey , String zhsjy) {
        log.error("人员工号："+workcode);
        String groupId = "weaver-ebuilder-form-service";
        String sql = "select ID from eteams.dbo.employee where status = 'normal' and job_num = '"+workcode+"' and tenant_key = '"+createTenantKey+"'";
        Map<String,Object> recordMap = new HashMap<>();
//        String sourceType = "LOGIC";
        String sourceType = zhsjy;
//        Map<String, Object> result = databaseUtils.execute(sourceType, groupId, sql);
//        List<Map<String,Object>> recordList = databaseUtils.getDataSourceList(result);
//        if(CollectionUtils.isNotEmpty(recordList)){
//            recordMap = recordList.get(0);
//        }
        RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
        rs.executeQuery(sql, zhsjy);
        Long id = null;
        if(rs.next()){
            id = Long.parseLong(rs.getString("id"));
        }
        log.error("人员ID："+id);
        return id;
    }

}