package com.mortals.xhx.daemon;

import cn.hutool.core.io.FileUtil;
import cn.hutool.setting.Setting;
import cn.hutool.setting.dialect.Props;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.base.system.upload.service.UploadService;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.common.key.Constant;
import com.mortals.xhx.common.pdu.ApiRespPdu;
import com.mortals.xhx.module.matter.model.MatterDatumEntity;
import com.mortals.xhx.module.matter.model.MatterDatumFileEntity;
import com.mortals.xhx.module.matter.service.*;
import com.mortals.xhx.module.matters.service.MattersDetailService;
import com.mortals.xhx.module.matters.service.MattersService;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

/**
 * 事项数据同步更新
 *
 * @author: zxfei
 * @date: 2022/3/30 9:45
 */
@CommonsLog
@RestController
@RequestMapping("test")
public class RequestDataController {

    @Autowired
    private MatterService matterService;
    @Autowired
    private MattersService mattersService;
    @Autowired
    private MattersDetailService mattersDetailService;
    @Autowired
    private MatterFlowlimitService matterFlowlimitService;
    @Autowired
    private MatterAcceptService matterAcceptService;
    @Autowired
    private MatterSetbaseService matterSetbaseService;
    @Autowired
    private MatterQuestionService matterQuestionService;
    @Autowired
    private MatterIntermediaryService matterIntermediaryService;
    @Autowired
    private MatterDatumService matterDatumService;
    @Autowired
    private MatterDatumFileService matterDatumFileService;
    @Autowired
    private MatterChargesService matterChargesService;


    @Autowired
    private ParamService paramService;
    @Autowired
    private UploadService uploadService;


    /**
     * 生成基础数据prop
     *
     * @return
     */
    @PostMapping("/baseprop")
    public ApiRespPdu<String> baseprop() {
        ApiRespPdu<String> respPdu = new ApiRespPdu<>();

        Map<String, String> baseInfoMap = matterService.getBaseInfoMap(null);
        //保存为

        Setting setting = Setting.create();
        setting.putAll(baseInfoMap);
        setting.store("E://baseinfo.setting");

        Map<String, String> sqclInfoMap = matterService.getSqclInfoMap(null);

        sqclInfoMap.entrySet().stream().peek(item -> {
            String[] split = item.getValue().split(",");
            if (split.length > 1) {
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < split.length; i++) {
                    sb.append(split[i]);
                    sb.append(".");
                    sb.append(split[i]);
                    if (i != split.length - 1) {
                        sb.append(",");
                    }

                }
                item.setValue(sb.toString());
            }
        }).count();

        setting = Setting.create();
        setting.putAll(sqclInfoMap);
        setting.store("E://sqclinfo.setting");

        return respPdu;
    }


    /**
     * 同步事项数据
     *
     * @return
     */
    @PostMapping("/syncMatter")
    public ApiRespPdu<String> syncMatter() {
        ApiRespPdu<String> respPdu = new ApiRespPdu<>();

        matterService.syncMatter(null);

        return respPdu;
    }

    /*
     */

    /**
     * 同步解析材料
     *
     * @param
     * @return
     *//*
    @PostMapping("/datumn")
    public String datumn(@RequestBody ApiReqPdu<RequestTaskReq> req) {

        ApiRespPdu<String> respPdu = new ApiRespPdu<>();
        BiMap<String, String> materialPropertyInverseMap = HashBiMap.create(paramService.getParamByFirstOrganize(Constant.Param_materialProperty)).inverse();
        BiMap<String, String> materialTypeInverseMap = HashBiMap.create(paramService.getParamByFirstOrganize(Constant.Param_materialType)).inverse();
        BiMap<String, String> electronicgsInverseMap = HashBiMap.create(paramService.getParamByFirstOrganize(Constant.Param_electronicgs)).inverse();
        BiMap<String, String> materialSourceInverseMap = HashBiMap.create(paramService.getParamByFirstOrganize(Constant.Param_materialSource)).inverse();
        BiMap<String, String> paperGgInverseMap = HashBiMap.create(paramService.getParamByFirstOrganize(Constant.Param_paperGg)).inverse();
        BiMap<String, String> jianmMsInverseMap = HashBiMap.create(paramService.getParamByFirstOrganize(Constant.Param_jianmMs)).inverse();
        BiMap<String, String> sealWayInverseMap = HashBiMap.create(paramService.getParamByFirstOrganize(Constant.Param_sealWay)).inverse();
        BiMap<String, String> isMustInverseMap = HashBiMap.create(paramService.getParamByFirstOrganize(Constant.Param_isMust)).inverse();
        BiMap<String, String> iszzsbInverseMap = HashBiMap.create(YesNoEnum.getEnumMap()).inverse();
        BiMap<String, String> yesOrNoInverseMap = HashBiMap.create(YesNoEnum.getEnumMap()).inverse();

        //String value = inverse.getOrDefault(m.getValue().toString(), "0");

        try {
            //拆分材料库数据
            matterDetailService.find(new MatterDetailQuery()).stream().peek(item -> {
                String json = item.getMaterialsSqcl();
                //log.info("receive json:"+json);
                if (ObjectUtils.isEmpty(json) || "{}".equals(json)) {
                    log.info("json:" + json);
                    return;
                }
                JSONObject root = null;
                try {
                    root = JSON.parseObject(json);
                } catch (Exception e) {
                    json = json.replaceAll("\\\\", "\\\\\\\\");

                    try {
                        root = JSON.parseObject(json);
                    } catch (Exception e1) {
                        log.error("error json:" + json);
                        return;
                    }

                }

                if (root.isEmpty()) {
                    log.info("root is null");
                    return;
                }
                JSONArray jsonArray = null;
                try {
                    jsonArray = root.getJSONArray("申请材料");
                } catch (Exception e) {
                    log.error("error 无申请材料");
                }

                if (ObjectUtils.isEmpty(jsonArray)) {
                    log.info("申请材料 is null");
                    return;
                }

                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject secondJsonObject = jsonArray.getJSONObject(i);
                    MatterDatumEntity datumEntity = new MatterDatumEntity();
                    datumEntity.setMatterId(item.getMatterId());
                    datumEntity.setSource(0);
                    datumEntity.setCreateTime(new Date());
                    datumEntity.setCreateUser("system");

                    //材料详情
                    JSONArray jsonArrayThree = secondJsonObject.getJSONArray("材料详情");
                    if (!ObjectUtils.isEmpty(jsonArrayThree)) {

                        for (int j = 0; j < jsonArrayThree.size(); j++) {
                            jsonArrayThree.getJSONObject(j).entrySet().stream().peek(m -> {
                                Boolean bool = false;

                                if ("材料名称".equals(m.getKey().trim())) {
                                    datumEntity.setMaterialName(m.getValue().toString());
                                    bool = true;
                                }

                                if ("材料形式".equals(m.getKey().trim())) {
                                    //materialPropertyInverseMap
                                    String value = materialPropertyInverseMap.getOrDefault(m.getValue().toString(), "0");

                                    datumEntity.setMaterialProperty(Integer.parseInt(value));
                                    bool = true;
                                    checkKeyValue(materialPropertyInverseMap, m, value);

                                }

                                if ("材料必要性".equals(m.getKey().trim())) {
                                    //isMustInverseMap
                                    String value = isMustInverseMap.getOrDefault(m.getValue().toString(), "0");
                                    datumEntity.setIsMust(Integer.parseInt(value));
                                    bool = true;
                                    checkKeyValue(isMustInverseMap, m, value);
                                }

                                if ("材料类型".equals(m.getKey().trim())) {
                                    //materialTypeInverseMap
                                    String value = materialTypeInverseMap.getOrDefault(m.getValue().toString(), "0");
                                    datumEntity.setMaterialType(Integer.parseInt(value));
                                    bool = true;
                                    checkKeyValue(materialTypeInverseMap, m, value);
                                }

                                if ("电子材料格式".equals(m.getKey().trim())) {
                                    //electronicgsInverseMap
                                    String value = electronicgsInverseMap.getOrDefault(m.getValue().toString(), "0");
                                    datumEntity.setElectronicgs(Integer.parseInt(value));
                                    bool = true;
                                    checkKeyValue(electronicgsInverseMap, m, value);
                                }

                                if ("来源渠道".equals(m.getKey().trim())) {
                                    //materialSourceSmInverseMap
                                    String value = materialSourceInverseMap.getOrDefault(m.getValue().toString(), "0");
                                    datumEntity.setMaterialSource(Integer.parseInt(value));
                                    bool = true;
                                    checkKeyValue(materialSourceInverseMap, m, value);
                                }

                                if ("来源渠道说明".equals(m.getKey().trim())) {
                                    datumEntity.setMaterialSourceSm(m.getValue().toString());
                                    bool = true;
                                }

                                if ("纸质材料份数".equals(m.getKey().trim())) {
                                    //materialSourceSmInverseMap
                                    datumEntity.setPaperNum(Integer.parseInt(m.getValue().toString()));
                                    bool = true;
                                }

                                if ("纸质材料规格".equals(m.getKey().trim())) {
                                    //paperGgInverseMap
                                    String value = paperGgInverseMap.getOrDefault(m.getValue().toString(), "0");
                                    datumEntity.setPaperGg(Integer.parseInt(value));
                                    bool = true;
                                    checkKeyValue(paperGgInverseMap, m, value);

                                    datumEntity.setPaperGgText(m.getValue().toString());

                                }

                                if ("盖章或盖手印方式".equals(m.getKey().trim())) {
                                    //sealWayInverseMap
                                    String value = sealWayInverseMap.getOrDefault(m.getValue().toString(), "0");
                                    datumEntity.setSealWay(Integer.parseInt(value));
                                    bool = true;
                                    checkKeyValue(sealWayInverseMap, m, value);
                                    datumEntity.setSealWayText(m.getValue().toString());
                                }

                                if ("是否容缺".equals(m.getKey().trim())) {
                                    //yesOrNoInverseMap
                                    String value = yesOrNoInverseMap.getOrDefault(m.getValue().toString(), "0");
                                    datumEntity.setIsLack(Integer.parseInt(value));
                                    bool = true;
                                    checkKeyValue(yesOrNoInverseMap, m, value);
                                }

                                if ("是否减免".equals(m.getKey().trim())) {
                                    //yesOrNoInverseMap
                                    String value = yesOrNoInverseMap.getOrDefault(m.getValue().toString(), "0");
                                    datumEntity.setIsjianm(Integer.parseInt(value));
                                    bool = true;
                                    checkKeyValue(yesOrNoInverseMap, m, value);
                                }

                                if ("减免模式".equals(m.getKey().trim())) {
                                    //jianmMsInverseMap

                                    if ("".equals(m.getValue().toString())) {
                                        m.setValue("无");
                                    }
                                    String value = jianmMsInverseMap.getOrDefault(m.getValue().toString(), "0");
                                    datumEntity.setJianmMs(Integer.parseInt(value));
                                    bool = true;
                                    checkKeyValue(jianmMsInverseMap, m, value);
                                }

                                if ("填报须知".equals(m.getKey().trim())) {
                                    datumEntity.setRemarkSub(m.getValue().toString());
                                    bool = true;
                                }

                                if ("受理标准".equals(m.getKey().trim())) {
                                    datumEntity.setSummary(m.getValue().toString());
                                    bool = true;
                                }

                                if ("要求提供材料的依据".equals(m.getKey().trim())) {
                                    datumEntity.setClauseContent(m.getValue().toString());
                                    bool = true;
                                }

                                if ("备注".equals(m.getKey().trim())) {
                                    datumEntity.setRemark(m.getValue().toString());
                                    bool = true;
                                }

                                if (!bool) {
                                    System.out.println("name:" + m.getKey());
                                    System.out.print(" value:" + m.getValue());
                                }
                            }).count();
                        }
                    }


                    matterDatumService.save(datumEntity);
                    //示例样表
                    JSONArray jsonArrayone = secondJsonObject.getJSONArray("示例样表");
                    if (!ObjectUtils.isEmpty(jsonArrayone)) {
                        ArrayList<MatterDatumFileEntity> fileArrayList = new ArrayList<>();
                        for (int j = 0; j < jsonArrayone.size(); j++) {
                            MatterDatumFileEntity fileEntity = new MatterDatumFileEntity();
                            fileEntity.setCreateTime(new Date());
                            fileEntity.setCreateUser("system");
                            fileEntity.setDatumid(datumEntity.getId());
                            fileEntity.setSource(0);
                            fileEntity.setFiletype(1);
                            jsonArrayone.getJSONObject(j).entrySet().stream().peek(m -> {
                                fileEntity.setFileName(m.getKey());
                                fileEntity.setFileUrl(m.getValue().toString());
                            }).count();
                            fileArrayList.add(fileEntity);
                        }
                        matterDatumFileService.save(fileArrayList);

                    }
                    //空白表格
                    JSONArray jsonArraytwo = secondJsonObject.getJSONArray("空白表格");
                    if (!ObjectUtils.isEmpty(jsonArraytwo)) {

                        ArrayList<MatterDatumFileEntity> fileArrayList = new ArrayList<>();
                        for (int j = 0; j < jsonArraytwo.size(); j++) {
                            MatterDatumFileEntity fileEntity = new MatterDatumFileEntity();
                            fileEntity.setCreateTime(new Date());
                            fileEntity.setCreateUser("system");
                            fileEntity.setDatumid(datumEntity.getId());
                            fileEntity.setSource(0);
                            fileEntity.setFiletype(2);
                            jsonArraytwo.getJSONObject(j).entrySet().stream().peek(m -> {
                                fileEntity.setFileName(m.getKey());
                                fileEntity.setFileUrl(m.getValue().toString());
                            }).count();
                            fileArrayList.add(fileEntity);
                        }
                        matterDatumFileService.save(fileArrayList);
                    }
                }

            }).count();


        } catch (Exception e) {
            log.error("error", e);
        }
        return respPdu;
    }*/
    private void checkKeyValue(BiMap<String, String> map, Map.Entry<String, Object> m, String value) {
        if ("0".equals(value)) {
            //查看是否为空
            String temp = map.get(m.getValue().toString());
            if (ObjectUtils.isEmpty(temp)) {
                //打印枚举类型值
                System.out.println("uncheck name:" + m.getKey() + " value:" + m.getValue());
            }
        }
    }


    public static void main(String[] args) {


    }

}
