package com.malk.pake.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.malk.pake.service.PkProjectService;
import com.malk.pake.utils.HttpUtils;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.service.aliwork.YDClient;
import com.malk.service.dingtalk.DDClient;
import com.malk.service.dingtalk.DDClient_Notice;
import com.malk.service.dingtalk.DDClient_Workflow;
import com.malk.utils.UtilDateTime;
import com.malk.utils.UtilMap;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class PkProjectServiceImpl implements PkProjectService {

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

    private String projectFormUUID = "FORM-7F8921D7324F43B3B1147C1D99A3F758NFIL";
    private String saleFormUUID = "FORM-4V966N81BW8D84BFBI41WACUKFRZ1XBFPVELLJ";
    private String trainUUID = "FORM-78E05305A9BB4BBBABF5E34F781530D1RP78";
    private String airUUID = "FORM-53E3974D2A074B00AA6C66DE278F7938ZNNT";

    /// dingtalk
    @Value("${dingtalk.appKey}")
    private String APP_EKY;
    @Value("${dingtalk.appSecret}")
    private String APP_SECRET;
    /// aliwork
    @Value("${aliwork.appType}")
    private String APP_TYPE;
    @Value("${aliwork.systemToken}")
    private String SYSTRM_TOKEN;
    /// 阿里商旅
    @Value("${alibusinesstravel.appKey}")
    private String BUS_kEY;
    @Value("${alibusinesstravel.appSecret}")
    private String BUS_SECRET;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final Map<String,String> AIR_FEE_TYPE  = new HashMap<>();
    static {
        AIR_FEE_TYPE.put("10101","机票预订");
        AIR_FEE_TYPE.put("10202","机票改签手续费");
        AIR_FEE_TYPE.put("10203","机票改签差价");
        AIR_FEE_TYPE.put("10301","机票退款");
        AIR_FEE_TYPE.put("10302","机票改签退款");
        AIR_FEE_TYPE.put("10303","机票补退");
        AIR_FEE_TYPE.put("10401","机票保险-航意险购买");
        AIR_FEE_TYPE.put("10501","机票保险-航意险退保");
        AIR_FEE_TYPE.put("11001","机票预订服务费");
        AIR_FEE_TYPE.put("11002","机票改签服务费");
        AIR_FEE_TYPE.put("10304","机票票据服务费退款");
        AIR_FEE_TYPE.put("11003","机票票据服务费");
        AIR_FEE_TYPE.put("11004","机票托管协议服务费");
        AIR_FEE_TYPE.put("11005","机票改签托管协议服务费");
    }
    private static final Map<String,String> TRAIN_FEE_TYPE = new HashMap<>();
    static {
       TRAIN_FEE_TYPE.put("6001","火车票预订");
       TRAIN_FEE_TYPE.put("6003","火车票改签差价");
       TRAIN_FEE_TYPE.put("6004","火车票改签手续费");
       TRAIN_FEE_TYPE.put("6005","火车票退票");
       TRAIN_FEE_TYPE.put("6007","火车票预订服务费");
       TRAIN_FEE_TYPE.put("6008","火车票改签服务费");
       TRAIN_FEE_TYPE.put("6009","火车票预订退款");
       TRAIN_FEE_TYPE.put("6010","火车票改签退款");
       TRAIN_FEE_TYPE.put("6101","火车票抢票加速包");
       TRAIN_FEE_TYPE.put("6011","火车票票据服务费");
       TRAIN_FEE_TYPE.put("6012","火车票技术服务费");
       TRAIN_FEE_TYPE.put("6013","火车票票据服务费退款");
       TRAIN_FEE_TYPE.put("6014","火车票线下退改退款");
    }
    @Override
    public void saleUpdateProject(String formInstId) {
//        log.info("流程id：{}",formInstId);
        Map formData = ydClient.queryData(YDParam.builder().formInstanceId(formInstId).build(),
                YDConf.FORM_QUERY.retrieve_id).getFormData();
        String contractCode = formData.get("textField_llew0vlc").toString();
        String contractName = formData.get("textareaField_lq0s1gcw").toString();
        String contractAmount = formData.get("numberField_llew0vlx_value").toString();
        String projectCode = formData.get("textField_ltpbh04c").toString();
        if (!projectCode.isEmpty() && ObjectUtil.isNotNull(projectCode)){
            List<Map<String, Object>> dataList = (List<Map<String, Object>>)ydClient.queryData(YDParam.builder().formUuid(projectFormUUID)
                            .searchFieldJson(JSONObject.toJSONString(UtilMap.map("textField_llemcq7d", projectCode))).build(),
                    YDConf.FORM_QUERY.retrieve_search_form).getData();

            List<Map<String,Object>> association = new ArrayList<>();
            Map<String, Object> map = UtilMap.map("appType, formType, formUuid, instanceId, subTitle, title", "APP_UNSAR4O4Y7NBDUYXLIP4", "process", saleFormUUID, formInstId, contractCode, contractName);
            association.add(map);
            dataList.forEach(e->{
                ydClient.operateData(YDParam.builder()
                        .formInstanceId(e.get("formInstanceId").toString())
                        .updateFormDataJson(JSON.toJSONString(UtilMap.map("associationFormField_lmlq4t3o, textField_lmlq4t3p, textField_lmlq4t3q, numberField_m731di5q",association,contractName,contractCode,contractAmount)))
                        .useLatestVersion(true)
                        .build(), YDConf.FORM_OPERATION.update);
            });
        }
    }

    @Override
    public void oaUpdateProject(String processInstanceId, String formUuid, Map<String, String> compsId_main, Map<String, String> compsId_itinerary, String compId_sub_oa) {

        String token = ddClient.getAccessToken(APP_EKY, APP_SECRET);
//        log.info("processInstanceId:{}",processInstanceId);
        Map processData = ddClient_workflow.getProcessInstanceId(token, processInstanceId);
        List<Map> formComponentValues = (List<Map>) processData.get("formComponentValues");
        String userId = String.valueOf(processData.get("originatorUserId"));
        long cDate = UtilDateTime.parse(UtilMap.getString(processData, "createTime"), "yyyy-MM-dd'T'HH:mm").getTime();
        Map formData = UtilMap.map("employeeField_ltxqs53k, departmentSelectField_lu20ayky, dateField_ltxqs53j, textField_lygnetw9", Arrays.asList(userId), Arrays.asList(processData.get("originatorDeptId")), cDate, UtilMap.getString(processData, "businessId"));
        Optional optional = formComponentValues.stream().filter(item -> "费用出处".equals(item.get("name"))).findAny();
        if (optional.isPresent() && (UtilMap.getString((Map) optional.get(), "value").equals("项目费用") || UtilMap.getString((Map) optional.get(), "value").equals("研发费用"))){
            Double OATravelSum = 0.0;//OA差旅费用
            Double OATrafficSum = 0.0;//OA交通费用
            Double OAEntertainSum = 0.0;//OA招待费用
            Double OAOtherSum = 0.0;//OA其他费用
            optional = formComponentValues.stream().filter(item -> "项目编号".equals(item.get("name"))).findAny();
            if (!optional.isPresent()){
                return;
            }
            String projectCode = UtilMap.getString((Map) optional.get(), "value");
            optional = formComponentValues.stream().filter(item -> "费用报销类型".equals(item.get("name"))).findAny();
            String type = UtilMap.getString((Map) optional.get(), "value");
            for (String name : compsId_main.keySet()) {
                String compId = compsId_main.get(name);
                // 判定是否子表 [宜搭]
                if (compId.startsWith("tableField_")) {
                    List<Map> details = new ArrayList<>();
                    // 兼容明细组件, 存在多条情况 [加班跨天才有有明细]
                    optional = formComponentValues.stream().filter(item -> compId_sub_oa.equals(item.get("name"))).findAny();
                    if (!optional.isPresent()) {
                        continue;
                    }
                    String schedule = UtilMap.getString((Map) optional.get(), "value");
                    List<Map> itineraryList = ((List<Map>) JSON.parse(schedule));
                    // 循环明细数据
                    for (Map itinerary : itineraryList) {
                        List<Map> rowValue = (List<Map>) itinerary.get("rowValue");
                        Map rowData = new HashedMap();
                        // 循环子表组件插入宜搭表单
                        for (String subName : compsId_itinerary.keySet()) {
                            if ("出发时间".equals(subName) || "返回时间".equals(subName)) {
                                rowValue.forEach(r->{
                                    Object label = r.get("label");
                                    if (label instanceof  JSONArray){
                                        Object value = r.get("value");
                                        JSONArray jsonArray = JSONArray.parseArray(value.toString());
                                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                        try {
                                            rowData.put(compsId_itinerary.get("出发时间"), sdf.parse(jsonArray.get(0).toString()).getTime());
                                            rowData.put(compsId_itinerary.get("返回时间"), sdf.parse(jsonArray.get(1).toString()).getTime());
                                        } catch (ParseException e) {
//                                            log.info("字符串时间转字符串出错");
                                        }
                                    }
                                });
                            }else {
                                //  加班单跨天 [子表label为空]
                                try {
                                    Object value = rowValue.stream().filter(item -> subName.equals(item.get("bizAlias")) || subName.equals(item.get("label"))).findAny().get().get("value");
                                    rowData.put(compsId_itinerary.get(subName), value);
                                } catch (Exception e) {
//                                    log.info("流程版本字段差异");
                                }
                            }
                        }
                        details.add(rowData);
                        String category = "";
                        double amount = 0.0;
                        if ("行程明细".equals(compId_sub_oa)){
                            amount = Double.parseDouble(rowValue.stream().filter(item -> "合计金额（元）".equals(item.get("bizAlias")) || "合计金额（元）".equals(item.get("label"))).findAny().get().get("value").toString());
                        }else {
                            category = rowValue.stream().filter(item -> "报销类目".equals(item.get("bizAlias")) || "报销类目".equals(item.get("label"))).findAny().get().get("value").toString();
                            amount =  Double.parseDouble(rowValue.stream().filter(item -> "报销金额（元）".equals(item.get("bizAlias")) || "报销金额（元）".equals(item.get("label"))).findAny().get().get("value").toString());
                        }
                        if ("日常费用报销".equals(type)){
                            if ("团建费".equals(category)){
                                OAEntertainSum = OAEntertainSum + amount;
                            } else if ("交通费".equals(category)) {
                                OATrafficSum = OATrafficSum + amount;
                            }else {
                                OAOtherSum = OAOtherSum + amount;
                            }
                        }else if ("差旅费报销".equals(type)){
                            OATravelSum = OATravelSum + amount;
                        }else if ("业务招待费报销".equals(type)){
                            OAEntertainSum = OAEntertainSum + amount;
                        }else if ("交通费".equals(type)){
                            OATrafficSum = OATrafficSum + amount;
                        }
                    }
                    formData.put(compId, details);
                }
                else {
                    optional = formComponentValues.stream().filter(item -> name.equals(item.get("name"))).findAny();
                    if (!optional.isPresent()){
                        continue;
                    }
                    formData.put(compId,UtilMap.getString((Map) optional.get(), "value"));
                }
            }

            List<Map> dataList = (List<Map>) ydClient.queryData(YDParam.builder().formUuid("FORM-25910D3D9DA6455C9234BEC1C08687FD0OZK")
                    .searchFieldJson(JSON.toJSONString(UtilMap.map("textField_llemcq7d",projectCode))).build(), YDConf.FORM_QUERY.retrieve_list).getData();
            Double finalOATravelSum = OATravelSum;
            Double finalOATrafficSum = OATrafficSum;
            Double finalOAEntertainSum = OAEntertainSum;
            Double finalOAOtherSum = OAOtherSum;
            dataList.forEach(e->{
                Map data = (Map) e.get("formData");
                //差旅费用
                double travelAmount = Double.parseDouble(data.get("numberField_m7473oph_value")==null||data.get("numberField_m7473oph_value").toString().isEmpty() ? "0.0" : data.get("numberField_m7473oph_value").toString());
                //交通费用
                double trafficAmount = Double.parseDouble(data.get("numberField_m7473opi_value")==null||data.get("numberField_m7473opi_value").toString().isEmpty() ? "0.0" : data.get("numberField_m7473opi_value").toString());
                //招待费用
                double entertainAmount = Double.parseDouble(data.get("numberField_m7473opn_value")==null||data.get("numberField_m7473opn_value").toString().isEmpty() ? "0.0" : data.get("numberField_m7473opn_value").toString());
                //其他费用
                double otherAmount = Double.parseDouble(data.get("numberField_m7473opo_value")==null||data.get("numberField_m7473opo_value").toString().isEmpty() ? "0.0" : data.get("numberField_m7473opo_value").toString());
                //累计总成本
                double totalSumAmount = Double.parseDouble(data.get("numberField_m7473opq_value")==null||data.get("numberField_m7473opq_value").toString().isEmpty() ? "0.0" : data.get("numberField_m7473opq_value").toString());
                //预算总成本
                double totalBudgetedCost = Double.parseDouble(data.get("numberField_m732y3r0_value")==null||data.get("numberField_m732y3r0_value").toString().isEmpty() ? "0.0" : data.get("numberField_m732y3r0_value").toString());
                //累计报销费
                double totalApplyCost = Double.parseDouble(data.get("numberField_m7wyydmc_value")==null||data.get("numberField_m7wyydmc_value").toString().isEmpty() ? "0.0" : data.get("numberField_m7wyydmc_value").toString());
                //累计预算报销费用
                double totalBudgetedApply = Double.parseDouble(data.get("numberField_m7wyydmd_value")==null||data.get("numberField_m7wyydmd_value").toString().isEmpty() ? "0.0" : data.get("numberField_m7wyydmd_value").toString());
                travelAmount = travelAmount + finalOATravelSum;
                trafficAmount = trafficAmount + finalOATrafficSum;
                entertainAmount = entertainAmount + finalOAEntertainSum;
                otherAmount = otherAmount + finalOAOtherSum;
                totalSumAmount = totalSumAmount + finalOATravelSum + finalOATrafficSum + finalOAEntertainSum + finalOAOtherSum;
                totalApplyCost = totalApplyCost + finalOATravelSum + finalOATrafficSum + finalOAEntertainSum + finalOAOtherSum;
                ydClient.operateData(YDParam.builder()
                        .appType(APP_TYPE)
                        .systemToken(SYSTRM_TOKEN)
                        .formInstanceId(e.get("formInstanceId").toString())
                        .updateFormDataJson(JSON.toJSONString(UtilMap.map("numberField_m7473oph, numberField_m7473opi, numberField_m7473opn, numberField_m7473opo, numberField_m7473opq, numberField_m7473oqm, numberField_m7wyydmc, numberField_m7473oqi",travelAmount,trafficAmount,entertainAmount,otherAmount,totalSumAmount,totalSumAmount/totalBudgetedCost*100,totalApplyCost,totalApplyCost/totalBudgetedApply*100)))
                        .build(),YDConf.FORM_OPERATION.update);
            });
            // 用于审批回传
//        List<Map> tasks = UtilMap.getList(processData, "tasks");
//        formData.put("textField_lygvvyd9", tasks.get(0).get("taskId"));
//        formData.put("textField_lygvvyda", tasks.get(0).get("userId"));
            formData.put("textField_lyh4y3th", processInstanceId);
            ydClient.operateData(YDParam.builder()
                    .appType(APP_TYPE)
                    .systemToken(SYSTRM_TOKEN)
                    .formUuid(formUuid)
                    .formDataJson(JSON.toJSONString(formData))
                    .userId(userId)
                    .build(), YDConf.FORM_OPERATION.create);
        }
    }


    @Override
    public void getTrainInternal(String startDate, String endDate) {
        String token = getBusinessTravelToken();
        if (ObjectUtil.isNotNull(token)){
            Map<String, Object> param = UtilMap.map("app_key, so_corp_token, page_no, page_size, period_start, period_end", BUS_kEY, token, 1, 100, startDate, endDate);
            String url = "https://btripopen.alibtrip.com/api/train/v1/bill-settlement?";
            List<Object> results = getResult(url, param);
            if (ObjectUtil.isNotNull(results) && results.size()>0){
                results.forEach(r->{
                    JSONObject result = JSONObject.parseObject(r.toString());
                    if (ObjectUtil.isNotNull(result)){
                        if (ObjectUtil.isNotNull(result.get("project_code")) && !result.get("project_code").toString().isEmpty()){
                            String projectCode = result.get("project_code").toString();

                            List<Map> dataList = (List<Map>) ydClient.queryData(YDParam.builder().formUuid("FORM-25910D3D9DA6455C9234BEC1C08687FD0OZK")
                                    .searchFieldJson(JSON.toJSONString(UtilMap.map("textField_llemcq7d",projectCode))).build(), YDConf.FORM_QUERY.retrieve_list).getData();
                            Double amount = result.get("ticket_corp_pay_price") == null || result.get("ticket_corp_pay_price").toString().isEmpty()?0.0:Double.parseDouble(result.get("ticket_corp_pay_price").toString());
                            dataList.forEach(e->{
                                Map data = (Map) e.get("formData");
                                //差旅费用
                                double travelAmount = Double.parseDouble(data.get("numberField_m7473oph_value")==null||data.get("numberField_m7473oph_value").toString().isEmpty() ? "0.0" : data.get("numberField_m7473oph_value").toString());
                                //交通费用
//                            double trafficAmount = Double.parseDouble(data.get("numberField_m7473opi_value")==null||data.get("numberField_m7473opi_value").toString().isEmpty() ? "0.0" : data.get("numberField_m7473opi_value").toString());
                                //累计总成本
                                double totalSumAmount = Double.parseDouble(data.get("numberField_m7473opq_value")==null||data.get("numberField_m7473opq_value").toString().isEmpty() ? "0.0" : data.get("numberField_m7473opq_value").toString());
                                //预算总成本
                                double totalBudgetedCost = Double.parseDouble(data.get("numberField_m732y3r0_value")==null||data.get("numberField_m732y3r0_value").toString().isEmpty() ? "0.0" : data.get("numberField_m732y3r0_value").toString());
                                //累计报销费
                                double totalApplyCost = Double.parseDouble(data.get("numberField_m7wyydmc_value")==null||data.get("numberField_m7wyydmc_value").toString().isEmpty() ? "0.0" : data.get("numberField_m7wyydmc_value").toString());
                                //累计预算报销费用
                                double totalBudgetedApply = Double.parseDouble(data.get("numberField_m7wyydmd_value")==null||data.get("numberField_m7wyydmd_value").toString().isEmpty() ? "0.0" : data.get("numberField_m7wyydmd_value").toString());
                                travelAmount = travelAmount + amount;
                                totalSumAmount = totalSumAmount + amount;
                                totalApplyCost = totalApplyCost + amount;
                                ydClient.operateData(YDParam.builder()
                                        .appType(APP_TYPE)
                                        .systemToken(SYSTRM_TOKEN)
                                        .formInstanceId(e.get("formInstanceId").toString())
                                        .updateFormDataJson(JSON.toJSONString(UtilMap.map("numberField_m7473oph, numberField_m7473opq, numberField_m7473oqm, numberField_m7wyydmc, numberField_m7473oqi",travelAmount,totalSumAmount,totalSumAmount/totalBudgetedCost*100,totalApplyCost,totalApplyCost/totalBudgetedApply*100)))
                                        .build(),YDConf.FORM_OPERATION.update);
                            });
                        }
                        HashMap<String, Object> formData = new HashMap<>();
                        try {
                            formData.put("dateField_m9jm4pia",simpleDateFormat.parse(result.get("book_time").toString()).getTime());//预定时间
                            formData.put("textField_m9jm4pib",result.get("booker_name"));//预定人
                            formData.put("textField_m9jm4pic",result.get("traveler_name"));//出行人
                            formData.put("textField_m9jm4pid",result.get("cascade_department"));//联级部门
                            formData.put("textField_m9jm4pik",result.get("cost_center"));//成本中心名称
                            formData.put("textField_m9jm4pil",result.get("project_name"));//项目名称
                            formData.put("textField_m9jm4pim",result.get("project_code"));//项目编码
                            formData.put("textField_m9jm4pj5",TRAIN_FEE_TYPE.get(result.get("fee_type").toString()));//费用类型
                            formData.put("dateField_m9jm4pit",simpleDateFormat.parse(result.get("dept_date") + " 00:00:00").getTime());//发车日期
                            formData.put("textField_m9jm4piu",result.get("dept_time"));//发车时间
                            formData.put("dateField_m9jm4piv",simpleDateFormat.parse(result.get("arr_date") + " 00:00:00").getTime());//到达日期
                            formData.put("textField_m9jm4piw",result.get("arr_time"));//到达时间
                            formData.put("textField_m9jm4pj2",result.get("dep_city_name"));//出发城市
                            formData.put("textField_m9jm4pj3",result.get("arr_city_name"));//到达城市
                            formData.put("textField_m9jm4pj4",result.get("seat_type"));//坐席
                            formData.put("numberField_m9jm4pjb",result.get("ticket_corp_pay_price"));//企业支付金额
                            formData.put("textareaField_m9jm4pjf",result.get("business_trip_result"));//出差事由
                            formData.put("textareaField_m9jm4pjg",result.get("change_result"));//改签原因
                            formData.put("textareaField_m9jm4pjh",result.get("refund_reason"));//退订原因
                            formData.put("textareaField_m9jm4pjn",result.get("exceed_reason"));//超标原因
                            formData.put("textareaField_m9jm4pjo",result.get("remark"));//备注
                        } catch (ParseException e) {
                            throw new RuntimeException(e);
                        }
                        ydClient.operateData(YDParam.builder()
                                .appType(APP_TYPE)
                                .systemToken(SYSTRM_TOKEN)
                                .formUuid(trainUUID)
                                .formDataJson(JSON.toJSONString(formData))
                                .build(), YDConf.FORM_OPERATION.create);
                    }
                });
            }
        }
    }

    @Override
    public void getAirInternal(String startDate, String endDate) {
        String token = getBusinessTravelToken();
        if (ObjectUtil.isNotNull(token)){
            Map<String, Object> param = UtilMap.map("app_key, so_corp_token, page_no, page_size, period_start, period_end", BUS_kEY, token, 1, 100, startDate, endDate);
            String url = "https://btripopen.alibtrip.com/api/flight/v1/bill-settlement?";
            List<Object> results = getResult(url, param);
            if (ObjectUtil.isNotNull(results) && results.size()>0){
                results.forEach(r->{
                    JSONObject result = JSONObject.parseObject(r.toString());
                    if (ObjectUtil.isNotNull(result)){
                        if (ObjectUtil.isNotNull(result.get("project_code")) && !result.get("project_code").toString().isEmpty()){
                            String projectCode = result.get("project_code").toString();

                            List<Map> dataList = (List<Map>) ydClient.queryData(YDParam.builder().formUuid("FORM-25910D3D9DA6455C9234BEC1C08687FD0OZK")
                                    .searchFieldJson(JSON.toJSONString(UtilMap.map("textField_llemcq7d",projectCode))).build(), YDConf.FORM_QUERY.retrieve_list).getData();
                            Double amount = result.get("corp_settle_price") == null || result.get("corp_settle_price").toString().isEmpty()?0.0:Double.parseDouble(result.get("corp_settle_price").toString());
                            dataList.forEach(e->{
                                Map data = (Map) e.get("formData");
                                //差旅费用
                                double travelAmount = Double.parseDouble(data.get("numberField_m7473oph_value")==null||data.get("numberField_m7473oph_value").toString().isEmpty() ? "0.0" : data.get("numberField_m7473oph_value").toString());
                                //交通费用
//                            double trafficAmount = Double.parseDouble(data.get("numberField_m7473opi_value")==null||data.get("numberField_m7473opi_value").toString().isEmpty() ? "0.0" : data.get("numberField_m7473opi_value").toString());
                                //累计总成本
                                double totalSumAmount = Double.parseDouble(data.get("numberField_m7473opq_value")==null||data.get("numberField_m7473opq_value").toString().isEmpty() ? "0.0" : data.get("numberField_m7473opq_value").toString());
                                //预算总成本
                                double totalBudgetedCost = Double.parseDouble(data.get("numberField_m732y3r0_value")==null||data.get("numberField_m732y3r0_value").toString().isEmpty() ? "0.0" : data.get("numberField_m732y3r0_value").toString());
                                //累计报销费
                                double totalApplyCost = Double.parseDouble(data.get("numberField_m7wyydmc_value")==null||data.get("numberField_m7wyydmc_value").toString().isEmpty() ? "0.0" : data.get("numberField_m7wyydmc_value").toString());
                                //累计预算报销费用
                                double totalBudgetedApply = Double.parseDouble(data.get("numberField_m7wyydmd_value")==null||data.get("numberField_m7wyydmd_value").toString().isEmpty() ? "0.0" : data.get("numberField_m7wyydmd_value").toString());
                                travelAmount = travelAmount + amount;
                                totalSumAmount = totalSumAmount + amount;
                                totalApplyCost = totalApplyCost + amount;
                            ydClient.operateData(YDParam.builder()
                                    .appType(APP_TYPE)
                                    .systemToken(SYSTRM_TOKEN)
                                    .formInstanceId(e.get("formInstanceId").toString())
                                    .updateFormDataJson(JSON.toJSONString(UtilMap.map("numberField_m7473oph, numberField_m7473opq, numberField_m7473oqm, numberField_m7wyydmc, numberField_m7473oqi",travelAmount,totalSumAmount,totalSumAmount/totalBudgetedCost*100,totalApplyCost,totalApplyCost/totalBudgetedApply*100)))
                                    .build(),YDConf.FORM_OPERATION.update);

                            });
                        }
                        HashMap<String, Object> formData = new HashMap<>();
                        try {
                            formData.put("dateField_m9jm4pia",simpleDateFormat.parse(result.get("book_time").toString()).getTime());//预定时间
                            formData.put("textField_m9jm4pib",result.get("booker_name"));//预定人
                            formData.put("textField_m9jm4pic",result.get("traveler_name"));//出行人
                            formData.put("textField_m9jm4pid",result.get("cascade_department"));//联级部门
                            formData.put("textField_m9jm4pik",result.get("cost_center"));//成本中心名称
                            formData.put("textField_m9jm4pil",result.get("project_name"));//项目名称
                            formData.put("textField_m9jm4pim",result.get("project_code"));//项目编码
                            formData.put("textField_m9jrbcig",result.get("capital_direction"));//资金方向
                            formData.put("dateField_m9jm4pit",simpleDateFormat.parse(result.get("dept_date") + " 00:00:00").getTime());//起飞日期
                            formData.put("textField_m9jm4piu",result.get("dept_time"));//起飞时间
                            formData.put("dateField_m9jm4piv",simpleDateFormat.parse(result.get("arr_date") + " 00:00:00").getTime());//到达日期
                            formData.put("textField_m9jm4piw",result.get("arr_time"));//到达时间
                            formData.put("textField_m9jm4pj2",result.get("dept_city"));//起飞城市
                            formData.put("textField_m9jm4pj3",result.get("arr_city"));//到达城市
                            formData.put("textField_m9jm4pj4",result.get("cabin_class"));//舱等
                            formData.put("textField_m9jm4pj5",AIR_FEE_TYPE.get(result.get("fee_type").toString()));//费用类型
                            formData.put("numberField_m9jm4pjb",result.get("corp_pay_order_fee"));//订单金额
                            formData.put("numberField_m9jrbcih",result.get("settlement_fee"));//结算金额
                            formData.put("numberField_m9jrbcii",result.get("corp_settle_price"));//企业支付金额
                            formData.put("numberField_m9jrbcio",result.get("person_settle_price"));//个人支付金额
                            formData.put("numberField_m9jrbciq",result.get("refund_fee"));//退票手续费
                            formData.put("numberField_m9jrbcir",result.get("refund_upgrade_cost"));//改签退票手续费
                            formData.put("textField_m9jrbcit",result.get("discount"));//折扣率
                            formData.put("numberField_m9jrbciz",result.get("advance_day"));//提前预定天数
                            formData.put("textareaField_m9jm4pjf",result.get("business_trip_result"));//出差事由
                            formData.put("textareaField_m9jm4pjh",result.get("refund_reason"));//退订原因
                            formData.put("textareaField_m9jm4pjg",result.get("change_result"));//改签原因
                            formData.put("textareaField_m9jm4pjn",result.get("exceed_reason"));//超标原因
                            formData.put("textareaField_m9jm4pjo",result.get("remark"));//备注
                        } catch (ParseException e) {
                            throw new RuntimeException(e);
                        }
                        ydClient.operateData(YDParam.builder()
                                .appType(APP_TYPE)
                                .systemToken(SYSTRM_TOKEN)
                                .formUuid(airUUID)
                                .formDataJson(JSON.toJSONString(formData))
                                .build(), YDConf.FORM_OPERATION.create);
                    }
                });
            }
        }
    }

    //获取阿里商旅访问token
    public static String getBusinessTravelToken(){
        String result = HttpUtils.httpGet("https://btripopen.alibtrip.com/api/btrip-open-auth/v1/corp-token/action/take?app_key=pqm6bkfs0800&type=0&corp_id=open12pqm6bkfju87v16348dd896bc361558&app_secret=cHFtNmJrZnMwODAwXS1ceXpINzUsazUkVT1tejohZ1o");
        JSONObject jsonObject = JSONObject.parseObject(result);
        log.info("获取token:{}",jsonObject);
        if (ObjectUtil.isNotNull(jsonObject) && Boolean.parseBoolean(jsonObject.get("success").toString())){
            Object module = jsonObject.get("module");
            jsonObject = JSONObject.parseObject(module.toString());
            return jsonObject.get("token").toString();
        }
        return null;
    }
    //根据token和分页获取所有数据
    public static List<Object> getResult(String url,Map<String,Object> param){
        log.info("开始第一次获取总数据量:{}",param);
        int pageSize = 100;
        if (param.containsKey("page_size")){
            pageSize = Integer.parseInt(param.get("page_size").toString());
        }
        Map<String, Object> getTotalMap = new HashMap<>(param);
        getTotalMap.put("page_no",1);
        getTotalMap.put("page_size",1);
        JSONObject jsonObject = toRequest(url, getTotalMap);
        if (ObjectUtil.isNotNull(jsonObject)){
            List<Object> objects = new ArrayList<>();
            int totalNum = Integer.parseInt(jsonObject.get("total_num").toString());
            int totalPages = (int) Math.ceil(totalNum / pageSize) + 1;
            for (int i = 1; i <= totalPages; i++) {
                param.put("page_no",i);
                JSONObject result = toRequest(url, param);
                List<Object> dataList = (List<Object>) result.get("data_list");
                objects.addAll(dataList);
            }
            return objects;
        }
        return null;
    }
    //获取module里的数据
    @SneakyThrows
    public static JSONObject toRequest(String url, Map<String,Object> param){
        final String[] redirectUrl = {url};
        param.forEach((k,v)->{
            redirectUrl[0] = redirectUrl[0] + k + "=" + v + "&";
        });
        if (redirectUrl[0].endsWith("&")){
            redirectUrl[0] = redirectUrl[0].substring(0,redirectUrl[0].length()-1);
        }
        String result = HttpUtils.httpGet(redirectUrl[0]);
        JSONObject jsonObject = JSONObject.parseObject(result);
        boolean success = Boolean.parseBoolean(jsonObject.get("success").toString());
        while (!success){
            result = HttpUtils.httpGet(redirectUrl[0]);
            jsonObject = JSONObject.parseObject(result);
            success = Boolean.parseBoolean(jsonObject.get("success").toString());
            Thread.sleep(1000);
        }
        if (ObjectUtil.isNotNull(jsonObject) && success){
            Object module = jsonObject.get("module");
            jsonObject = JSONObject.parseObject(module.toString());
            return jsonObject;
        }
        return null;
    }
}
