package com.malk.pake.service.impl;

import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.malk.pake.service.PkDingProcService;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.dingtalk.DDR_New;
import com.malk.service.aliwork.YDClient;
import com.malk.service.dingtalk.DDClient;
import com.malk.service.dingtalk.DDClient_Workflow;
import com.malk.utils.PublicUtil;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
@Slf4j
public class PkDingProcServiceImpl implements PkDingProcService {

    @Autowired
    private DDClient ddClient;
    @Autowired
    private DDClient_Workflow ddClient_workflow;
    @Autowired
    private YDClient ydClient;

    @Override
    public void syncAmt(String processInstanceId) {
        Map map=ddClient_workflow.getProcessInstanceId(ddClient.getAccessToken(),processInstanceId);
        log.info("map:{}",map);
        Map rule=new HashMap();
        rule.put("DDSelectField_UHMSVWTIEYGW","type");// 费用报销类型
        rule.put("RelateField_1YSKOD9PT0N40","cc");// 出差申请
        Map data=getData(map,rule);
        String projectId;
        if("差旅费报销".equals(data.get("type"))){
            rule.put("TableField_135H2SA1S12PS","detail");// 报销明细
            data=getData(map,rule);
            List<Map> list=UtilMap.getList(UtilMap.getMap(data,"cc"),"list");
            if(list==null||list.size()<1){
                return;
            }
            Map cc=(Map) list.get(0);
            Map ccMap=ddClient_workflow.getProcessInstanceId(ddClient.getAccessToken(),String.valueOf(cc.get("procInstId")));
            Map ccRule=new HashMap();
            ccRule.put("TableField_GN1B25VL6PKW","detail");// 费用报销类型
            ccRule.put("DDSelectField-KDCL0BQO","ccType");//
            Map ccData=getData(ccMap,ccRule);
            log.info("ccData:{}",ccData);
            List<Map> table=JSONObject.parseArray(UtilMap.getString(UtilMap.getMap(ccData,"detail"),"value"),Map.class);
            if(table==null||table.size()<1){
                return;
            }
            String ccType=UtilMap.getString(ccData,"ccType");
            if(!ccType.equals("项目费用")){
                return;
            }
            List<Map> detail=UtilMap.getList(table.get(0),"rowValue");
            Optional optional = detail.stream().filter(item -> "DDSelectField-KDCL1UD0".equals(item.get("key"))).findAny();
            projectId=((JSONObject) optional.get()).getJSONObject("extendValue").getString("codeName");
        }else{
            rule.put("TableField_VXS0O5SIYUPS","detail");// 报销明细
            rule.put("DDSelectField_12JKA5S3V6P6O","fycc");// 费用出处
            rule.put("TextField_1EWZ8SATVB280","projectId");
            data=getData(map,rule);
            log.info("data:{}",data);
            String fycc=UtilMap.getString(data,"fycc");
            if(!fycc.equals("项目费用")){
                return;
            }
            projectId=UtilMap.getString(data,"projectId");
//            List<Map> table=JSONObject.parseArray(UtilMap.getString(UtilMap.getMap(data,"detail"),"value"),Map.class);
//            if(table==null||table.size()<1){
//                return;
//            }
//            List<Map> detail=UtilMap.getList(table.get(0),"rowValue");
//            Optional optional = detail.stream().filter(item -> "DDSelectField_GEABKH83MMO0".equals(item.get("key"))).findAny();
//            String isProject=((JSONObject) optional.get()).getString("value");
//            if(!"是".equals(isProject)){
//                return;
//            }
//            log.info("detail:{}",detail);
//            Optional optional1 = detail.stream().filter(item -> "FormRelateField_319R30PPM0W0".equals(item.get("key"))).findAny();
//            List<Map> projects=((JSONObject) optional1.get()).getJSONObject("extendValue").getJSONArray("list")
//                    .getJSONObject(0).getJSONArray("rowValue").toJavaList(Map.class);
//            Optional optional3 = projects.stream().filter(item -> "TextField-K2AD4O5B".equals(item.get("key"))).findAny();
//            projectId=((JSONObject) optional3.get()).getString("value");
        }
        List<Map> list=UtilMap.getList(JSONObject.parseObject(UtilMap.getString(UtilMap.getMap(data,"detail"),"extValue")),"statValue");
        if(list!=null&&list.size()>0){
            log.info("projectId:{},type:{},amt：{}",projectId,String.valueOf(data.get("type")),String.valueOf(list.get(0).get("num")));
            syncYida(projectId,String.valueOf(data.get("type")),String.valueOf(list.get(0).get("num")));
            log.info("同步完成！");
        }else{
            log.error("合计金额为空！");
        }
    }
    private Map getData(Map instance,Map rule){
        Map resultMap=new HashMap();
        List<Map> list=(List<Map>) instance.get("formComponentValues");
        for (Map map:list) {
            if(rule.containsKey(String.valueOf(map.get("id")))){
                String componentType=String.valueOf(map.get("componentType"));
                if(componentType.equals("TableField")){
                    resultMap.put(rule.get(String.valueOf(map.get("id"))), map);
                }else if(componentType.equals("FormRelateField")){
                    resultMap.put(rule.get(String.valueOf(map.get("id"))), JSONObject.parseObject(String.valueOf(map.get("extValue"))));
                }else if(componentType.equals("RelateField")){
                    resultMap.put(rule.get(String.valueOf(map.get("id"))), JSONObject.parseObject(String.valueOf(map.get("extValue"))));
                }else{
                    resultMap.put(rule.get(String.valueOf(map.get("id"))),map.get("value"));
                }
            }
        }
        return resultMap;
    }

    private void syncYida(String projectId,String type,String amt){
        if(PublicUtil.isNull(projectId)||PublicUtil.isNull(type)||PublicUtil.isNull(amt)){
            log.error("有空数据退出");
            return;
        }
        List<Map> list = (List<Map>) ydClient.queryData(YDParam.builder().formUuid("FORM-NO96679107GDYGUK9SM8T42G95KA2KZOMUELL4")
                .searchFieldJson(JSONObject.toJSONString(UtilMap.map("textField_llemcq7d", projectId))).build(), YDConf.FORM_QUERY.retrieve_list_all).getData();
        if(list==null||list.size()<1){
            log.error("未查到该项目：{}",projectId);
            return;
        }
        Map map=list.get(0);
        Map formData=UtilMap.getMap(map,"formData");
        String formInstId=UtilMap.getString(map,"formInstanceId");
        Map upMap=new HashMap();
        if(type.equals("日常费用报销")){
            upMap.put("numberField_lvvsbjz0",NumberUtil.add(UtilMap.getString(formData,("numberField_lvvsbjz0")),amt));//其他变动费用合计
            upMap.put("numberField_lwk1dgvv",NumberUtil.add(UtilMap.getString(formData,("numberField_lwk1dgvv")),amt));//其他变动费用合计-OA
        }else if(type.equals("差旅费报销")){
            upMap.put("numberField_lvvsbjyy",NumberUtil.add(UtilMap.getString(formData,("numberField_lvvsbjyy")),amt));//差旅费合计
            upMap.put("numberField_lwk1dgvt",NumberUtil.add(UtilMap.getString(formData,("numberField_lwk1dgvt")),amt));//差旅费合计-OA
        }else if(type.equals("业务招待费报销")){
            upMap.put("numberField_lvvsbjyz",NumberUtil.add(UtilMap.getString(formData,("numberField_lvvsbjyz")),amt));//招待费合计
            upMap.put("numberField_lwk1dgvu",NumberUtil.add(UtilMap.getString(formData,("numberField_lwk1dgvu")),amt));//招待费合计-OA
        }else if(type.equals("交通费")){
            upMap.put("numberField_lwso04d8",NumberUtil.add(UtilMap.getString(formData,("numberField_lwso04d8")),amt));//交通费合计
            upMap.put("numberField_lwso04da",NumberUtil.add(UtilMap.getString(formData,("numberField_lwso04da")),amt));//交通费合计-OA
        }else{
            return;
        }
        upMap.put("numberField_lvuf44q4", NumberUtil.add(UtilMap.getString(formData,("numberField_lvuf44q4")),amt));//变动费用合计
        ydClient.operateData(YDParam.builder().formInstId(formInstId)
                .updateFormDataJson(JSONObject.toJSONString(upMap))
                .build(), YDConf.FORM_OPERATION.update);
    }

    public static void main(String[] args) {
        Map formData=UtilMap.map("ad",1);
        System.out.println(NumberUtil.add(UtilMap.getString(formData,"numberField_lvvsbjz0"),"100"));
    }

}
