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.*;
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.*;
import java.util.stream.Collectors;

/**
 * 同步事项申请条件等
 *
 * @author: zxfei
 * @date: 2021/9/22 10:46
 */
@CommonsLog
@RestController
@RequestMapping("test")
public class RequestMatterController {

    @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;

    /**
     * 同步解析常见问题
     *
     * @param req
     * @return
     */
    @PostMapping("/question")
    public ApiRespPdu question(@RequestBody ApiReqPdu<RequestTaskReq> req) {

        ApiRespPdu<String> respPdu = new ApiRespPdu<>();

        try {
            //拆分材料库数据
            matterDetailService.find(new MatterDetailQuery()).stream().peek(item -> {
                //String json = item.getMaterialsSqcl();
                String json = item.getQuestionCjwt();
                //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 jsonObject = jsonArray.getJSONObject(i);


                    List<MatterQuestionEntity> questionEntityList = jsonObject.entrySet().stream().map(question -> {
                        MatterQuestionEntity questionEntity = new MatterQuestionEntity();
                        questionEntity.setTitle(question.getKey());
                        questionEntity.setContent(question.getValue().toString());
                        questionEntity.setMatterId(item.getMatterId());
                        questionEntity.setSource(0);
                        questionEntity.setCreateTime(new Date());
                        questionEntity.setCreateUser("system");
                        return questionEntity;
                    }).collect(Collectors.toList());

                    matterQuestionService.save(questionEntityList);
                }

            }).count();


        } catch (Exception e) {
            log.error("error", e);
        }
        return respPdu;
    }

    /**
     * 同步解析受理条件
     *
     * @param req
     * @return
     */
    @PostMapping("/accept")
    public ApiRespPdu accept(@RequestBody ApiReqPdu<RequestTaskReq> req) {

        ApiRespPdu<String> respPdu = new ApiRespPdu<>();

        try {
            //拆分材料库数据
            matterDetailService.find(new MatterDetailQuery()).stream().peek(item -> {

                String json = item.getConditionsSltj();
                //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;
                }
                String value = null;
                try {
                    value = root.getString("受理条件");

                } catch (Exception e) {
                    log.error("error 受理条件",e);
                }

                if (ObjectUtils.isEmpty(json)) {
                    log.info("受理条件 is null");
                    return;
                }


            }).count();


        } catch (Exception e) {
            log.error("error", e);
        }
        return respPdu;
    }



    /**
     * 同步解析办理流程
     *
     * @param req
     * @return
     */
    @PostMapping("/flow")
    public ApiRespPdu flow(@RequestBody ApiReqPdu<RequestTaskReq> req) {

        ApiRespPdu<String> respPdu = new ApiRespPdu<>();
        try {
            //拆分材料库数据
            matterDetailService.find(new MatterDetailQuery()).stream().peek(item -> {
                String json = item.getProcessBllc();

                //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;
                    }

                }


                JSONArray jsonArray = null;
                try {
                    jsonArray = root.getJSONArray("办理流程");
                } catch (Exception e) {
                    log.error("error 无办理流程");
                }

                if (ObjectUtils.isEmpty(jsonArray)) {
                    log.info("办理流程 is null");
                    return;
                }

                List<MatterFlowlimitEntity> flowlimitEntityArrayList = new ArrayList<>();

                for (int i = 0; i < jsonArray.size(); i++) {


                    MatterFlowlimitEntity matterFlowlimitEntity = new MatterFlowlimitEntity();
                    matterFlowlimitEntity.setMatterId(item.getMatterId());
                    matterFlowlimitEntity.setSource(0);
                    matterFlowlimitEntity.setCreateTime(new Date());
                    matterFlowlimitEntity.setCreateUser("system");
                    JSONArray innerJsonArray = jsonArray.getJSONArray(i);
                    for (int j = 0; j < innerJsonArray.size(); j++) {

                        innerJsonArray.getJSONObject(j).entrySet().stream().peek(m -> {
                            Boolean bool=false;

                            if ("办理流程".equals(m.getKey().trim())) {
                                matterFlowlimitEntity.setFlowName(m.getValue().toString());
                                bool=true;
                            }

                            if ("办理时长".equals(m.getKey().trim())) {
                                matterFlowlimitEntity.setFlowTime(m.getValue().toString());
                                bool=true;
                            }

                            if ("转外时限".equals(m.getKey().trim())) {
                                matterFlowlimitEntity.setFlowTurnOut(m.getValue().toString());
                                bool=true;
                            }

                            if ("办理流程说明".equals(m.getKey().trim())) {
                                matterFlowlimitEntity.setFlowDesc(m.getValue().toString());
                                bool=true;
                            }

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



                    }
                    flowlimitEntityArrayList.add(matterFlowlimitEntity);
                }
                matterFlowlimitService.save(flowlimitEntityArrayList);
            }).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));

    }

}
