package com.seeyon.apps.bip.quartz;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.seeyon.apps.bip.constants.BipConstants;
import com.seeyon.apps.common.workflow.util.FormDataBeanUtil;
import com.seeyon.apps.ext.quartz.AbstractQuartzTask;
import com.seeyon.apps.ext.workflow.vo.FormDataVo;
import com.seeyon.apps.mplus.api.MplusApi;
import com.seeyon.cap4.bizportalold.util.HttpClientUtil;
import com.seeyon.cap4.form.api.FormApi4Cap4;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.fieldCtrl.enums.CreditQueryConstant;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.util.JDBCAgent;
import com.seeyon.ctp.util.Strings;
import com.seeyon.ctp.util.json.JSONUtil;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.inject.Inject;
import java.io.File;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.seeyon.cap4.form.bean.fieldCtrl.enums.CreditQueryConstant.Category.*;

/**
 * 功能描述:<br>
 * <pre>
 *
 * </pre>
 *
 * @Author: FanGaowei
 * @Date: 2024/1/8
 */
public class QixinSyncQuartz extends AbstractQuartzTask {

    private static final Log LOGGER = LogFactory.getLog(QixinSyncQuartz.class);

    private static final Integer ENTERPRISE_INFO_EXACT_BUSINESS = 11;
    private static final Integer ENTERPRISE_INFO_EXACT_INSTITUTION = 12;
    private static final Integer ENTERPRISE_INFO_EXACT_LAW = 13;


    final String serviceCode = "m20000000000003002";

    @Inject
    private MplusApi mplusApi;
    @Inject
    private FormApi4Cap4 formApi4Cap4;

    @Override
    public String taskRun(String param) throws Exception {
       /* String path = SystemEnvironment.getLogsFolder() + "gongshang.log";
        FileUtils.writeStringToFile(new File(path), JSONUtil.toJSONString(getCreditQueryInfo(param)), "UTF-8");*/
        AtomicInteger success = new AtomicInteger(0);
        AtomicInteger error = new AtomicInteger(0);
        Vector<String> syncMsgs = new Vector();
        FormBean formBean = formApi4Cap4.getFormByFormCode("inner_gs");
        String sql = "select id from " + formBean.getMasterTableBean().getTableName();
        // 根据税号查询数据
        try(JDBCAgent agent = new JDBCAgent(true, false)) {
            agent.execute(Strings.isNotBlank(param) ? param : sql);
            List<Map<String, Object>> list = agent.resultSetToList();
            list.parallelStream().forEach(row -> {
                Long id = Convert.toLong(row.get("id"));
                try {
                    FormDataMasterBean masterBean = formApi4Cap4.getDataMasterBeanById(id, formBean, null);

                    // 处理数据
                    FormDataVo formDataVo = FormDataBeanUtil.trans2FormDataVo(BipConstants.getPluginId(),
                            formBean.getId(), null, formBean, masterBean);

                    // 获取税号字段
                    String sh = formDataVo.getFieldData("验证税号").getStringValue();

                    JSONObject res = getCreditQueryInfo(sh);
                   /* String s = FileUtils.readFileToString(new File("/Users/kkdo/zcseeyon/05 伙伴项目/12 湖北橙阳科技有限公司/01 三峡旅游集团有限公司/v5/apps-customize/src/main/java/com/seeyon/apps/bip/quartz/data.json"),
                            "utf-8");
                    JSONObject res = JSONUtil.parseJSONString(s, JSONObject.class);
                    // 数据更新*/
                    JSONObject baseInfo = res.getJSONObject("business_info");
                    formDataVo.getNewFieldDataMap().put("客商名称", baseInfo.getString("name"));

                    String address = baseInfo.getString("address");
                    if(Strings.isBlank(address)) {
                        address = "空";
                    }
                    formDataVo.getNewFieldDataMap().put("客户详细地址", address);
                    formDataVo.getNewFieldDataMap().put("详细地址_F", address);
                    formDataVo.getNewFieldDataMap().put("企业类型", baseInfo.getString("org_type"));
                    formDataVo.getNewFieldDataMap().put("实缴资本", baseInfo.getString("actual_capi"));
                    String regCapi = baseInfo.getString("reg_capi");
                    formDataVo.getNewFieldDataMap().put("注册资本", regCapi.substring(0,regCapi.length()-3));

                    // 处理高管信息
                    List<FormDataVo> gaoguan = formDataVo.getSubFormMap().get("高管详细信息表");
                    Map<String, FormDataVo> gaoguanMap =
                            gaoguan.stream().collect(Collectors.toMap(sub -> {
                                try {
                                    return sub.getFieldData("主要成员姓名").getStringValue();
                                } catch (NoSuchFieldException e) {
                                    return "error";
                                }
                            }, Function.identity(),(key1, key2)->key2));

                    JSONArray gaoguanArr = res.getJSONArray("employees");

                    for (int i = 0; i < gaoguanArr.size(); i++) {
                        JSONObject gaoguanInfo = gaoguanArr.getJSONObject(i);
                        FormDataVo gaoguanVo = gaoguanMap.get(gaoguanInfo.getString("name"));

                        if(null == gaoguanVo) {
                            // 新增一行 处理一下空行的问题
                            FormDataVo formDataVo1 = gaoguanMap.get("");
                            if(null != formDataVo1) {
                                formDataVo1.getNewFieldDataMap().put("主要成员姓名", gaoguanInfo.getString("name"));
                                formDataVo1.getNewFieldDataMap().put("主要成员职务", gaoguanInfo.getString("job_title"));
                                gaoguanMap.remove("");
                            } else {
                                Map<String, Object> fieldMap = new HashMap<>();
                                fieldMap.put("主要成员姓名", gaoguanInfo.getString("name"));
                                fieldMap.put("主要成员职务", gaoguanInfo.getString("job_title"));
                                FormDataBeanUtil.addNewRow("高管详细信息表", formDataVo, fieldMap, masterBean);
                            }
                        } else {
                            gaoguanVo.getNewFieldDataMap().put("主要成员职务", gaoguanInfo.getString("job_title"));
                        }
                    }

                    // 工商变更信息
                    JSONArray array = res.getJSONArray("changerecords");
                    List<FormDataVo> changerecords = formDataVo.getSubFormMap().get("工商变更明细");


                    Map<String, FormDataVo> changeMap =
                            changerecords.stream().collect(Collectors.toMap(sub -> {
                                try {
                                    return sub.getFieldData("工商变更项目").getStringValue() + sub.getFieldData("变更日期").getStringValue();
                                } catch (NoSuchFieldException e) {
                                    return "error";
                                }
                            }, Function.identity(),(key1, key2)->key2));

                    // 遍历
                    for (int i = 0; i < array.size(); i++) {
                        JSONObject record = array.getJSONObject(i);
                        String type = record.getString("change_item");
                        String changeDate = record.getString("change_date");
                        String unique = type + changeDate;

                        FormDataVo changeRow = changeMap.get(unique);

                        if(null == changeRow) {
                            // 新增一行

                            FormDataVo formDataVo1 = changeMap.get("");
                            if(null != formDataVo1) {
                                formDataVo1.getNewFieldDataMap().put("工商变更项目", type);
                                formDataVo1.getNewFieldDataMap().put("变更日期", changeDate);
                                formDataVo1.getNewFieldDataMap().put("工商变更前", record.getString("before_content"));
                                formDataVo1.getNewFieldDataMap().put("工商变更后", record.getString("after_content"));
                                formDataVo1.getNewFieldDataMap().put("历史信息标签", record.getString("tag"));
                                changeMap.remove("");
                            } else {
                                Map<String, Object> fieldMap = new HashMap<>();
                                fieldMap.put("工商变更项目", type);
                                fieldMap.put("变更日期", changeDate);
                                fieldMap.put("工商变更前", record.getString("before_content"));
                                fieldMap.put("工商变更后", record.getString("after_content"));
                                fieldMap.put("历史信息标签", record.getString("tag"));
                                FormDataBeanUtil.addNewRow("工商变更明细", formDataVo, fieldMap, masterBean);
                            }
                        } else {
                            changeRow.getNewFieldDataMap().put("工商变更前", record.getString("before_content"));
                            changeRow.getNewFieldDataMap().put("工商变更后", record.getString("after_content"));
                            changeRow.getNewFieldDataMap().put("历史信息标签", record.getString("tag"));
                        }
                    }

                    FormDataBeanUtil.saveMaster(formDataVo, masterBean);

                    formApi4Cap4.saveOrUpdateFormData(masterBean, formBean.getId(), true);
                    syncMsgs.add(sh + "同步成功");
                    success.getAndIncrement();
                } catch (Exception e) {
                    log.error("同步失败：" + id + e.getMessage());
                    syncMsgs.add("同步失败：" + id + e.getMessage());
                    error.getAndIncrement();
                }
            });
        } catch (Exception e){
            log.error("同步数据异常：", e);
        }
        return success.get() + "个成功 | 失败" + error.get() + "个:" + StringUtils.join(syncMsgs, "    ");
    }

    @Override
    public String getName() {
        return "定时同步启信宝数据";
    }


    private JSONObject getCreditQueryInfo(String name) throws BusinessException {
        String domain = mplusApi.getDomain();
        String ticket = mplusApi.getTicket(serviceCode);
        String url = domain + "/svr/enterprise/info";
        Map<String, Object> jsonObject = new HashMap<>();
        jsonObject.put("ticket", ticket);
        jsonObject.put("keyword", name);
        jsonObject.put("type", "1");
        jsonObject.put("parameterType", "2");
        jsonObject.put("isEnterpriseOnly", 1);
        jsonObject.put("isOpenMap", false);
        Map<String, Object> res = HttpClientUtil.doPost(url, jsonObject);
        Map<String, Object> data = (Map<String, Object>) res.get("data");
        String state = res.get("code").toString();
        if (!"1000".equals(state)) {
            BusinessException e = new BusinessException(res.get("msg").toString());
            LOGGER.error(res.get("msg").toString(), e);
            throw e;
        }
        Integer mplusType = MapUtils.getInteger(data, "mplusType");

        Map<String, Object> queryInfo = new HashMap<>();
        Set<Object> handledNames = Sets.newHashSet();
        for (CreditQueryConstant.Category category : CreditQueryConstant.Category.values()) {
            String egName = category.getKey();
            handledNames.add(egName);
            if (data.containsKey(egName)) {
                queryInfo.put(egName, data.get(egName));
            }
        }
        List municipalityList = Lists.newArrayList("北京", "天津", "上海", "重庆");
        Map<String, Object> info = new HashMap<>();
        data.entrySet().forEach(entry -> {
            if (!handledNames.contains(entry.getKey())) {
                if ("city".equals(entry.getKey()) && municipalityList.contains(data.get("province1"))) {
                    info.put(entry.getKey(), data.get("province1"));
                } else {
                    info.put(entry.getKey(), entry.getValue());
                }
            }
        });
        queryInfo.put(getKeyName(mplusType), info);
        if (!Objects.equals(mplusType, ENTERPRISE_INFO_EXACT_BUSINESS)) {
            queryInfo.put("url", "||");
        }else{
            queryInfo.put("url", MapUtils.getString(data, "chart_url", "") + "|" + MapUtils.getString(data, "lawsuit_url", "") + "|" + MapUtils.getString(data, "risk_url", ""));
        }
        String s = JSONUtil.toJSONString(queryInfo);

        return JSONUtil.parseJSONString(s, JSONObject.class);
    }

    /**
     * 精确查询对应有三种类型 工商 事业单位 律所，根据type返回不同的key
     *
     * @param mplusType
     * @return
     */
    private String getKeyName(Integer mplusType) {
        return Objects.equals(mplusType, ENTERPRISE_INFO_EXACT_BUSINESS) ? BUSINESS_INFO.getKey() : Objects.equals(mplusType, ENTERPRISE_INFO_EXACT_INSTITUTION) ? INSTITUTION.getKey() : LAW_FIRM_INFO.getKey();
    }
}
