package com.mortals.xhx.daemon.demo;

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.common.code.YesNoEnum;
import com.mortals.xhx.common.key.Constant;
import com.mortals.xhx.common.model.RequestTaskReq;
import com.mortals.xhx.common.pdu.api.ApiReqPdu;
import com.mortals.xhx.common.pdu.api.ApiRespPdu;
import com.mortals.xhx.feign.flowable.IApiFlowInstanceFeign;
import com.mortals.xhx.module.matter.model.MatterDatumEntity;
import com.mortals.xhx.module.matter.model.MatterDatumFileEntity;
import com.mortals.xhx.module.matter.model.MatterDetailQuery;
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.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author karlhoo
 */
@CommonsLog
@RestController
@RequestMapping("test")
public class RequestInstanceController {

    @Autowired
    private IApiFlowInstanceFeign apiFlowInstanceFeign;

    @Autowired
    private MatterService matterService;
    @Autowired
    private MatterDetailService matterDetailService;
    @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 MatterBaseinfoService matterBaseinfoService;


    @Autowired
    private ParamService paramService;

    @PostMapping("/instance/startById")
    public ApiRespPdu startById(@RequestBody ApiReqPdu<RequestTaskReq> req) {
        ApiRespPdu<String> respPdu = new ApiRespPdu<>();
        try {
            HashMap<String, Object> variables = new HashMap<>();

            variables.put("initiator", req.getTransmission().getUserId());
            variables.put("_FLOWABLE_SKIP_EXPRESSION_ENABLED", true);

            //respPdu = apiFlowInstanceFeign.startById(req.getTransmission().getProcDefId(), variables);
        } catch (Exception e) {
            log.error("error", e);
        }
        return respPdu;
    }

    @PostMapping("/instance/updateState")
    public ApiRespPdu updateState(@RequestBody ApiReqPdu<RequestTaskReq> req) {
        ApiRespPdu<String> respPdu = new ApiRespPdu<>();
        try {

            //respPdu = apiFlowInstanceFeign.updateState(req.getTransmission().getState(),req.getTransmission().getProcessInstanceId());
        } catch (Exception e) {
            log.error("error", e);
        }
        return respPdu;
    }


    /**
     * 同步解析材料
     *
     * @param req
     * @return
     */
    @PostMapping("/datumn")
    public ApiRespPdu 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) {

        RequestTaskReq requestTaskReq = new RequestTaskReq();
        requestTaskReq.setProcessInstanceId("11111");
        requestTaskReq.setDeployId("1");
        requestTaskReq.setUserId("admin");
        requestTaskReq.setDataKey("mydata");

        ApiReqPdu<RequestTaskReq> requestTaskReqApiReqPdu = new ApiReqPdu<>();
        requestTaskReqApiReqPdu.setTransmission(requestTaskReq);
        requestTaskReqApiReqPdu.setSeq("123456");

        System.out.println(JSON.toJSONString(requestTaskReqApiReqPdu));

    }

}
