package com.malk.chenyixun.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.malk.chenyixun.service.ChenyixunService;
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.utils.UtilMap;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

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

@Service
public class ChenyixunServiceImpl implements ChenyixunService {
    @Autowired
    private YDClient ydClient;

    @Async
    @Override
    public void sync1(Map map) {
        String formInstId = UtilMap.getString(map, "formInstId");

        Map formData = ydClient.queryData(YDParam.builder()
                .formInstId(formInstId)
                .build(), YDConf.FORM_QUERY.retrieve_id).getFormData();

        List<Map> cwclr = UtilMap.getList(formData,"employeeField_mf0xew5w_id");//车务处理人
        Object jhdhsj = formData.get("dateField_mb5wl2kv");//计划到货时间
        List<Map> gys = convertAssociationFormField(UtilMap.getString(formData,"associationFormField_mb5wl2kq_id"));//供应商
        String gysbh = UtilMap.getString(formData,"textField_mb97iaeh");//供应商编号
        String gysmc = UtilMap.getString(formData,"textField_mcu6kvlh");//供应商名称
        List<Map> cghtdd = convertAssociationFormField(UtilMap.getString(formData,"associationFormField_mb97iaei_id"));//采购合同订单关联表单
        String cghtddbh = UtilMap.getString(formData,"serialNumberField_mb5wl2kl");//采购合同订单编号
        List<Map> fqr = UtilMap.getList(formData,"employeeField_mb5wl2kj_id");//发起人

        List<Map> carList = getYdInnerTableList("FORM-B940BDA5D34647E9B7923C9F9FB43B24S19P",formInstId,"tableField_mcn18skj");//采购合同订单车辆清单子表

        for (Map car : carList) {
            Map carFormData = new HashMap();

            carFormData.put("textField_mcn3vgm4",car.get("textField_mcn3vgm4"));//车辆编号
            carFormData.put("associationFormField_mcn18skl",convertAssociationFormField(UtilMap.getString(car,"associationFormField_mcn18skl_id")));//车辆选择
            carFormData.put("textField_mcn18sko",car.get("textField_mcn18sko"));//车架号
            carFormData.put("textField_mcn18skn",car.get("textField_mcn18skn"));//车型配置
            carFormData.put("dateField_mb5wl2kv",jhdhsj);//计划到货时间
            carFormData.put("employeeField_mcn5ez9k",cwclr);//车务处理人
            carFormData.put("employeeField_mb5wl2kj",fqr);//发起人
            carFormData.put("associationFormField_mb97iaei",cghtdd);//采购合同订单关联表单
            carFormData.put("associationFormField_mb5wl2kq",gys);//供应商
            carFormData.put("textField_mb97iaeh",gysbh);//供应商编号
            carFormData.put("textField_mbpvv7vc",cghtddbh);//采购合同订单编号
            carFormData.put("textField_mcu4ue56",car.get("textField_mcu4ue56"));//车型编号
            carFormData.put("textField_mcu6igax",gysmc);//供应商名称

            ydClient.operateData(YDParam.builder()
                    .formUuid("FORM-01B84B082A364F3AAE6FCB905B1860F0JL1H")//采购合同车辆清单中间表
                    .formDataJson(JSONObject.toJSONString(carFormData))
                    .build(), YDConf.FORM_OPERATION.create);
        }
    }

    @Async
    @Override
    public void sync2(Map map) {
        String formInstId = UtilMap.getString(map, "formInstId");

        Map formData = ydClient.queryData(YDParam.builder()
                .formInstId(formInstId)
                .build(), YDConf.FORM_QUERY.retrieve_id).getFormData();

        List<Map> kh = convertAssociationFormField(UtilMap.getString(formData,"associationFormField_mb5uutk8_id"));//客户
        String khbh = UtilMap.getString(formData,"textField_mb7jzz6z");//客户编号

        List<Map> xshtdd = convertAssociationFormField(UtilMap.getString(formData,"associationFormField_mb8s60wl_id"));//销售合同订单关联表单
        String xshtddbh = UtilMap.getString(formData,"serialNumberField_mb5uutk0");//销售合同订单编号

        List<Map> khhtda = convertAssociationFormField(UtilMap.getString(formData, "associationFormField_mcmq5gec_id"));//客户合同档案关联表单
        String khhtbh = UtilMap.getString(formData,"textField_mcmq5ged");//客户合同编号

        List<String> cw = UtilMap.getList(formData,"checkboxField_mcn18skp");//车务

        List<Map> carList = getYdInnerTableList("FORM-A2BD5F465D16475FB0E95EAD25BBE6ABRYU2",formInstId,"tableField_mcn18skj");//销售合同订单车辆清单子表

        for (Map car : carList) {
            Map carFormData = new HashMap();

            carFormData.put("associationFormField_mcn18skl",convertAssociationFormField(UtilMap.getString(car,"associationFormField_mcn18skl_id")));//车辆选择
            carFormData.put("textField_mcn18sko",car.get("textField_mcn18sko"));//车架号
            carFormData.put("textField_mcn18skn",car.get("textField_mcn18skn"));//车型配置
            carFormData.put("textField_mco7usdr",car.get("textField_mco7usdr"));//UUID

            carFormData.put("associationFormField_mb8s60wl",xshtdd);//销售合同订单关联表单
            carFormData.put("textField_mcu7umpx",xshtddbh);//销售合同订单编号

            carFormData.put("associationFormField_mcmq5gec",khhtda);//客户合同档案关联表单
            carFormData.put("textField_mcmq5ged",khhtbh);//客户合同编号

            carFormData.put("associationFormField_mb5uutk8",kh);//客户选择
            carFormData.put("textField_mb7jzz6z",khbh);//客户编号

            carFormData.put("checkboxField_mcn18skp",cw);//车务

            ydClient.operateData(YDParam.builder()
                    .formUuid("FORM-AC1FD7BF8F6C4FAF926B067EBD85B942PWOR")//销售合同车辆清单中间表
                    .formDataJson(JSONObject.toJSONString(carFormData))
                    .build(), YDConf.FORM_OPERATION.create);
        }
    }

    @Async
    @Override
    public void sync3(Map map) {
        String formInstId = UtilMap.getString(map, "formInstId");

        Map formData = ydClient.queryData(YDParam.builder()
                .formInstId(formInstId)
                .build(), YDConf.FORM_QUERY.retrieve_id).getFormData();

        List<Map> khhtda = convertAssociationFormField(UtilMap.getString(formData, "associationFormField_mbj0epft_id"));//客户合同档案关联表单
        String khhdbh = UtilMap.getString(formData, "textField_mbhjyvev");//客户合同编号

        String xshtddbh = UtilMap.getString(formData, "textField_mbhjyvee");//销售合同订单编号

        Map updateFormData = new HashMap();
        updateFormData.put("associationFormField_mbhn6ixw",khhtda);
        updateFormData.put("textField_mbj1dpay",khhdbh);

        List<Map> carList = getYdFormDataList("FORM-4B9A81B17E34471D8B3DA1ADC2C53A77U2EU", JSONObject.toJSONString(UtilMap.map("textField_mbj1dpaw", xshtddbh)), YDConf.FORM_QUERY.retrieve_list);

        for (Map car : carList) {
            String formInstanceId = UtilMap.getString(car, "formInstanceId");

            Map carFormData = UtilMap.getMap(car, "formData");

            String carkhhtbh = UtilMap.getString(carFormData, "textField_mbj1dpay");

            if (Strings.isNullOrEmpty(carkhhtbh)){
                ydClient.operateData(YDParam.builder()
                        .formInstanceId(formInstanceId)
                        .updateFormDataJson(JSONObject.toJSONString(updateFormData))
                        .build(), YDConf.FORM_OPERATION.update);
            }
        }
    }

    private List<Map> convertAssociationFormField(String jsonString) {
        String jsonString2 = StringEscapeUtils.unescapeJava(jsonString.substring(1, jsonString.length() - 1));//新供应商（关联表单）

        List<Map> associationFormField =(List<Map>) JSONArray.parse(jsonString2);

        return associationFormField;
    }

    private List<Map> getYdInnerTableList(String formUuid,String formInstId,String tableFieldId) {
        List<Map> list = new ArrayList<>();
        DDR_New ddrNew;
        int pageNumber = 1;
        int pageSize = 50;
        do {
            ddrNew = ydClient.queryData(YDParam.builder()
                    .formUuid(formUuid)
                    .formInstanceId(formInstId)
                    .tableFieldId(tableFieldId)
                    .pageNumber(pageNumber)
                    .pageSize(pageSize).build(), YDConf.FORM_QUERY.retrieve_details);

            list.addAll((List<Map>) ddrNew.getData());
            pageNumber++;
        }while (ddrNew.getTotalCount() > ddrNew.getPageNumber() * pageSize);
        return list;
    }

    private List<Map> getYdFormDataList(String formUuid, String searchCondition, YDConf.FORM_QUERY formQuery) {
        List<Map> list = new ArrayList<>();
        DDR_New ddrNew = new DDR_New();
        int pageNumber = 1;
        int pageSize = 100;
        do {
            ddrNew = ydClient.queryData(YDParam.builder().formUuid(formUuid)
                    .searchCondition(searchCondition)
                    .pageNumber(pageNumber)
                    .pageSize(pageSize).build(), formQuery);

            list.addAll((List<Map>) ddrNew.getData());
            pageNumber++;
        }while (ddrNew.getTotalCount() > ddrNew.getPageNumber() * pageSize);
        return list;
    }
}
