package com.malk.kuaikeli;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.malk.kuaikeli.service.KKLService;
import com.malk.kuaikeli.service.SupplierMaterialService;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.aliwork.YDSearch;
import com.malk.service.aliwork.YDClient;
import com.malk.service.aliwork.YDService;
import com.malk.utils.UtilMap;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.*;

@Slf4j
@SpringBootTest
@RunWith(SpringRunner.class)
public class DdTest {

    @Autowired
    private SupplierMaterialService supplierMaterialService;
    @Autowired
    private YDClient ydClient;

    @Test
    public void create() {
        supplierMaterialService.sync();
//        supplierMaterialService.syncPrice();
    }

    @Test
    public void kk(){
        String fid="FINST-W9D66Q61MLZKG5LAEDWCBBS61E1D3FQFYS1WLJWL";
        Map formData=(Map) ydClient.queryData(YDParam.builder().formInstId(fid).build(), YDConf.FORM_QUERY.retrieve_id).getFormData();
        Map addMap=new HashMap();
        String data=String.valueOf(formData.get("associationFormField_lln477nb_id"));
        System.out.println(data.substring(1,data.length()-1).replaceAll("\\\\",""));
        addMap.put("associationFormField_llndtdwg",JSONObject.parseArray(data.substring(1,data.length()-1).replaceAll("\\\\","")));// 项目点
        ydClient.operateData(YDParam.builder().formUuid("FORM-RK966E71T0LDSTW39WFHE9OQ5GU23FKRRDNLL2").formDataJson(JSONObject.toJSONString(addMap)).build(), YDConf.FORM_OPERATION.create);
    }

    String data="{\"name\":\"XM-20240429-015\",\"area\":\"早餐\",\"list\":[{\"textField_lnwktyzy\":\"已启用\",\"rowId\":\"H7D667C1X7YLJR02AX55E7EX76SB23XVXFEXL9J5\",\"textField_ln1ez5li\":\"20240615\",\"textField_llndm599\":\"五指毛桃\",\"numberField_lmqclyxa\":\"87.64\",\"textField_lptgvips\":\"KG\",\"dateField_ln1ez5lg\":1718380800000,\"numberField_lomyf89l\":\"1\",\"numberField_lns0dkzv\":\"0\",\"dateField_lqg8oid5\":1718467200000,\"numberField_lnrzzg03\":\"\",\"textField_lln3lmn2\":\"KG\",\"textField_lnrzzg04\":\"\",\"numberField_lmym5628\":\"0.45\",\"textField_lmk97m1v\":\"CS550\",\"textField_lnwxz9ji\":\"\",\"radioField_ln1ez5le\":\"否\",\"numberField_lmsvfftq\":\"79.67\",\"numberField_lln477o2\":\"450\",\"numberField_lqg8oid6\":\"0\",\"selectField_lmqclyx9\":\"蔬菜类\",\"textField_lm4m83rv\":\"块\",\"numberField_lmsvfftr\":\"10\"},{\"textField_lnwktyzy\":\"已启用\",\"rowId\":\"H7D667C1X7YLJR02AX55E7EX76SB23XVXFEXLAJ5\",\"textField_ln1ez5li\":\"20240615\",\"textField_llndm599\":\"水洗胡萝卜\",\"numberField_lmqclyxa\":\"2.42\",\"textField_lptgvips\":\"KG\",\"dateField_ln1ez5lg\":1718380800000,\"numberField_lomyf89l\":\"1\",\"numberField_lns0dkzv\":\"0\",\"dateField_lqg8oid5\":1718467200000,\"numberField_lnrzzg03\":\"\",\"textField_lln3lmn2\":\"KG\",\"textField_lnrzzg04\":\"\",\"numberField_lmym5628\":\"0.34\",\"textField_lmk97m1v\":\"CS00107\",\"textField_lnwxz9ji\":\"\",\"radioField_ln1ez5le\":\"否\",\"numberField_lmsvfftq\":\"2.2\",\"numberField_lln477o2\":\"340\",\"numberField_lqg8oid6\":\"0\",\"selectField_lmqclyx9\":\"蔬菜类\",\"textField_lm4m83rv\":\"无\",\"numberField_lmsvfftr\":\"10\"},{\"textField_lnwktyzy\":\"已启用\",\"rowId\":\"H7D667C1X7YLJR02AX55E7EX76SB23XVXFEXLBJ5\",\"textField_ln1ez5li\":\"20240615\",\"textField_llndm599\":\"红心红薯\",\"numberField_lmqclyxa\":\"7.25\",\"textField_lptgvips\":\"KG\",\"dateField_ln1ez5lg\":1718380800000,\"numberField_lomyf89l\":\"3\",\"numberField_lns0dkzv\":\"0\",\"dateField_lqg8oid5\":1718467200000,\"numberField_lnrzzg03\":\"\",\"textField_lln3lmn2\":\"KG\",\"textField_lnrzzg04\":\"\",\"numberField_lmym5628\":\"3\",\"textField_lmk97m1v\":\"CS00137\",\"textField_lnwxz9ji\":\"\",\"radioField_ln1ez5le\":\"否\",\"numberField_lmsvfftq\":\"6.59\",\"numberField_lln477o2\":\"3000\",\"numberField_lqg8oid6\":\"0\",\"selectField_lmqclyx9\":\"蔬菜类\",\"textField_lm4m83rv\":\"块\",\"numberField_lmsvfftr\":\"10\"}],\"approveFlag\":false,\"form\":{},\"user\":\"011467460262746600\",\"poid\":\"FINST-ENC66381W4YLM1DG73V7C7L7H3DJ2071T1EXLC3H\"}";

    @Autowired
    private KKLService kklService;

    @Test
    public void test(){
        kklService.adjustCost(JSONObject.parseObject("{\"timeLimit\":\"1767024000000\",\"itemNumber\":\"XKL00332\",\"supId\":\"GYS-20241031-071\",\"typeTwo\":\"米面制品\",\"costPrice\":\"3.5\",\"typeOne\":\"粮油类\",\"state\":\"已启用\",\"nextCostPrice\":\"3.5\"}"));
//        kklService.validateApprove(JSONObject.parseObject(data));
//        kklService.additionMaterial(JSONObject.parseObject("{\"firstName\":\"水果其他\",\"gysNumber\":\"GYS-20241031-071\",\"state\":\"已启用\",\"goodNumber\":\"XKL02273\"}"));

//        kklService.planApproval(JSONObject.parseObject(data));
//        List<Map> table=null;
//        String formUuid="FORM-XHA66881J8KDA6V3FM6LZBUP9PDE37VESDNLL6";
//        Map formData=(Map) ydClient.queryData(YDParam.builder().formInstId(fid).build(), YDConf.FORM_QUERY.retrieve_id).getFormData();
//        List<Map> list=UtilMap.getList(formData,"tableField_lln477nw");
//        saveData(list,formData,formUuid,false);// -
//        saveData(table,formData,formUuid,true);// +
    }

    private void saveData(List<Map> list,Map formData,String formUuid,boolean isAdd){
        for(Map map:list){
            Map queryMap=new HashMap();
            queryMap.put("dateField_llndtdwl", Arrays.asList(map.get("dateField_ln1ez5lg"),map.get("dateField_ln1ez5lg")));// 日期
            queryMap.put("textField_llq9x6ov",formData.get("textField_lln477nh"));// 项目编号
            queryMap.put("textField_lmk97m1v",formData.get("textField_lmk97m1v"));// 档口编号
            Map upMap=new HashMap();
            upMap.put("numberField_llojyfy3",map.get("numberField_lmsvfftq"));// 成本单价
            upMap.put("numberField_llojyfy4",map.get("numberField_lmsvfftr"));// 服务费率
            upMap.put("dateField_llndtdwl",map.get("dateField_ln1ez5lg"));// 计划日期
            upMap.put("textField_llndm599",map.get("textField_llndm599"));// 原材料名称
            upMap.put("textField_lluj4hu1",map.get("textField_lln3lmn2"));// 单位
            upMap.put("textField_llq9x6ov",formData.get("textField_lln477nh"));// 项目编号
            upMap.put("textField_lm5z7kvo",map.get("textField_ln1ez5li"));// 计划日期（文本）
            upMap.put("textField_lm5z4ioi",formData.get("textField_lmsvfftp"));// 项目名称
            upMap.put("textField_lmk97m1v",map.get("textField_lmk97m1v"));// 原材料编号
            upMap.put("selectField_lmqclyx9",map.get("selectField_lmqclyx9"));// 第一分类
            upMap.put("numberField_lmqclyxa",map.get("numberField_lmqclyxa"));// 供货价
            upMap.put("textField_lnsmha2j",map.get("textField_lnwxz9ji"));// 品牌
            upMap.put("textField_lpjet322",formData.get("textField_lpjet322"));// 档口名称
            upMap.put("textField_lpjet321",formData.get("textField_lpjet321"));// 档口编号
            List<Map> list2=(List<Map>) ydClient.queryData(YDParam.builder().formUuid(formUuid).searchFieldJson(JSONObject.toJSONString(queryMap)).build(), YDConf.FORM_QUERY.retrieve_list).getData();
            if(list2==null||list2.size()<1){
                if(!isAdd){
                    log.info("未找到对应的计划采购单,退出");
                    continue;
                }
                upMap.put("numberField_lln477o2", map.get("numberField_lmym5628"));// 初始采购数量（kg）
                upMap.put("numberField_lm9008fq", map.get("numberField_lmym5628"));// 实际采购数量（kg）
                upMap.put("numberField_lns0dkzv", map.get("numberField_lns0dkzv"));// 投料数量（kg）
                ydClient.operateData(YDParam.builder().formUuid(formUuid).formDataJson(JSONObject.toJSONString(upMap)).build(), YDConf.FORM_OPERATION.create);
            }else{
                Map oldMap=UtilMap.getMap(list2.get(0),"formData");
                if(isAdd){
                    upMap.put("numberField_lln477o2", NumberUtil.add(UtilMap.getString(oldMap,"numberField_lln477o2"),UtilMap.getString(map,"numberField_lmym5628")));// 初始采购数量（kg）
                    upMap.put("numberField_lm9008fq", NumberUtil.add(UtilMap.getString(oldMap,("numberField_lm9008fq")),UtilMap.getString(map,("numberField_lmym5628"))));// 实际采购数量（kg）
                    upMap.put("numberField_lns0dkzv", NumberUtil.add(UtilMap.getString(oldMap,("numberField_lns0dkzv")),UtilMap.getString(map,("numberField_lns0dkzv"))));// 投料数量
                }else {
                    upMap.put("numberField_lln477o2", NumberUtil.sub(UtilMap.getString(oldMap, "numberField_lln477o2"), UtilMap.getString(map, "numberField_lmym5628")));// 初始采购数量（kg）
                    upMap.put("numberField_lm9008fq", NumberUtil.sub(UtilMap.getString(oldMap, ("numberField_lm9008fq")), UtilMap.getString(map, ("numberField_lmym5628"))));// 实际采购数量（kg）
                    upMap.put("numberField_lns0dkzv", NumberUtil.sub(UtilMap.getString(oldMap, ("numberField_lns0dkzv")), UtilMap.getString(map, ("numberField_lns0dkzv"))));// 投料数量
                }
                ydClient.operateData(YDParam.builder().formInstanceId(UtilMap.getString(list2.get(0),"formInstanceId")).updateFormDataJson(JSONObject.toJSONString(upMap)).build(), YDConf.FORM_OPERATION.update);
            }
        }
    }

    /***
     * 测试宜搭查询接口
     */
    @Test
    public void getYdData(){
        YDSearch ydSearch=new YDSearch("textField_llkb7kd2","XKL184","原材料编号", YDSearch.Type.TEXT_FIELD,YDSearch.Operator.EQ);
        List<Map> list2=(List<Map>) ydClient.queryData(YDParam.builder().formUuid("FORM-E6766M811CKD2PIXEAKOM9S2DKBM2PBQU1MLL5").searchCondition(JSONObject.toJSONString(
                Arrays.asList(ydSearch)
        )).build(), YDConf.FORM_QUERY.retrieve_list).getData();
        log.info("list2:{}",list2);
    }

    /***
     * 菜品管理原材料数据矫正
     */
    @Test
    public void testData(){
        List<String> list= FileUtil.readUtf8Lines("/home/ids.txt");
        List<String> errList=new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            log.info("处理进度：{}/{}",i+1,list.size());
            Map formData = ydClient.queryData(YDParam.builder().formInstId(list.get(i)).build(), YDConf.FORM_QUERY.retrieve_id).getFormData();
            List<Map> list1=UtilMap.getList(formData,"tableField_llm1i9yy");
            String pid=UtilMap.getString(formData,"textField_lln3lmn1");
            for (int j = 0; j < list1.size(); j++) {
                String yclId=UtilMap.getString(list1.get(j),"textField_lmk94yf5");
                YDSearch ydSearch=new YDSearch("textField_llkb7kd2",yclId,"原材料编号", YDSearch.Type.TEXT_FIELD,YDSearch.Operator.EQ);
                YDSearch ydSearch2=new YDSearch("textField_llm1vtjm",pid,"项目编号", YDSearch.Type.TEXT_FIELD,YDSearch.Operator.EQ);
                List<Map> list2=(List<Map>) ydClient.queryData(YDParam.builder().formUuid("FORM-E6766M811CKD2PIXEAKOM9S2DKBM2PBQU1MLL5").searchCondition(JSONObject.toJSONString(
                        Arrays.asList(ydSearch,ydSearch2)
                )).build(), YDConf.FORM_QUERY.retrieve_list).getData();
                if(list2!=null&&list2.size()==1){
                    String fid=UtilMap.getString(list2.get(0),"formInstanceId");
                    String data=String.valueOf(list1.get(j).get("associationFormField_lln3lmmv_id"));
                    JSONArray ass= JSONObject.parseArray(data.substring(1,data.length()-1).replaceAll("\\\\",""));
                    list1.get(j).put("associationFormField_lln3lmmv",Arrays.asList(ass.getJSONObject(0).fluentPut("instanceId",fid)));
                }else{
                    errList.add(list.get(i)+"|"+ UtilMap.getString(formData,"serialNumberField_llm1i9yr")+"|"+ pid + "|" + yclId);
                }
            }
            ydClient.operateData(YDParam.builder().formInstId(list.get(i)).updateFormDataJson(JSONObject.toJSONString(UtilMap.map("tableField_llm1i9yy", list1))).build(), YDConf.FORM_OPERATION.update);
        }
        log.info("errList:{}",JSONObject.toJSONString(errList));
    }

    @Autowired
    private YDService ydService;
    @Test
    public void t() throws InterruptedException {
        projectMaterials("GYS-20240621-017","半成品");
//        Thread.sleep(30*1000);
    }
    List<Map> projectMaterials(String code, String type) {
        List<Map> dataList = ydService.queryFormData_all(YDParam.builder()
                .formUuid("FORM-E6766M811CKD2PIXEAKOM9S2DKBM2PBQU1MLL5")
                .searchFieldJson(JSON.toJSONString(UtilMap.map("textField_llzzbyj1, selectField_llkk6cms", code, type)))
                .build());
        log.info("projectMaterials, {}", dataList.get(0).get("formInstanceId"));

        return dataList;
    }


    @Test
    public void tt(){
        String formInstId="565d8ad9-fe5e-4262-98f7-432bd9c06e82";
        Map data=ydClient.queryData(YDParam.builder().formInstId(formInstId).build(), YDConf.FORM_QUERY.retrieve_id).getFormData();
        log.info("data：{}",JSONObject.toJSONString(data));
        List<Map> list=UtilMap.getList(data,"tableField_llq9pqlu");

        String totalAmt="0";
        Map<String,Map> typeAmt=new HashMap<>();
        for (Map map:list){
            String amt=UtilMap.getString(map,"numberField_m2448gru_value");
            totalAmt=NumberUtil.add(amt,totalAmt).toString();
            String type=UtilMap.getString(map,"selectField_llkb7kd5");
            Map typeAmtMap=typeAmt.containsKey(type)?typeAmt.get(type):new HashMap();
            typeAmtMap.put("textField_lrhhan54",type); // 第一分类
            typeAmtMap.put("numberField_lrhhan58",UtilMap.getString(map,"numberField_lmjzdeh2_value")); // 预算
            typeAmtMap.put("numberField_lrhhan59",NumberUtil.add(amt,UtilMap.getString(typeAmtMap,"numberField_lrhhan59")).toString());// 采购
            typeAmt.put(type,typeAmtMap);
        }
        List typeTable=new ArrayList();
        for (String str:typeAmt.keySet()){
            typeTable.add(typeAmt.get(str));
        }

        Map upmap=UtilMap.map("numberField_m2448grv, tableField_lrhhan53",totalAmt,typeTable);

//        ydClient.operateData(YDParam.builder().formInstanceId("69237090-699f-43e6-a5d5-f36d421b1c13").updateFormDataJson(JSONObject.toJSONString(upmap)).build(), YDConf.FORM_OPERATION.update);
    }

    @Test
    public void ydTest(){
//        kklService.syncPrice();
        List<Map> dataList2 = ydService.queryFormData_all(YDParam.builder()
                .formUuid("FORM-12EB6BCE3C264630824721E7BBABCC03L8U9")
                .build());
        int i=0;
        for (Map record : dataList2) {
            log.info("项目进度：{}/{}",i,dataList2.size());
            i++;
            try {
                ydClient.operateData(YDParam.builder()
                        .formInstanceId(String.valueOf(record.get("formInstanceId")))
                        .updateFormDataJson(JSON.toJSONString(new HashMap<>()))
                        .useLatestVersion(true)
                        .build(), YDConf.FORM_OPERATION.update);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
