package com.malk.huagao;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kingdee.bos.webapi.entity.IdentifyInfo;
import com.kingdee.bos.webapi.sdk.K3CloudApi;
import com.malk.huagao.KdEntity.BillQuery;
import com.malk.huagao.config.KDWebApiConf;
import com.malk.huagao.entity.KdYdMaterial;
import com.malk.huagao.mapper.KdYdMaterialMapper;
import com.malk.huagao.service.KdHuaGaoService;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.service.aliwork.YDClient;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@SpringBootTest
@RunWith(SpringRunner.class)
public class KdTest {
    @Autowired
    private KDWebApiConf kdWebApiConf;

    @Autowired
    private KdHuaGaoService kdHuaGaoService;

    @Autowired
    private YDClient ydClient;
    @Autowired
    private KdYdMaterialMapper kdYdMaterialMapper;
@Test
public void test50() throws Exception {
    LambdaQueryWrapper<KdYdMaterial> materialdel = new LambdaQueryWrapper<>();
//    materialdel.eq(KdYdMaterial::getOperationType, "3")  // 修正：使用 materialdel 而不是 materialqw
//            .eq(KdYdMaterial::getSyncStatus, "0");

    List<KdYdMaterial> kdYdMaterialdels = kdYdMaterialMapper.selectList(materialdel);
    int size =kdYdMaterialdels.size();
    System.out.println(size);
}
    @Test
    public void test() throws Exception {
        K3CloudApi client = new K3CloudApi(initIden());

        List<Map> result = new ArrayList<>();
        List<Map> list = new ArrayList<>();

        int startRow = 0;
        int limit = 2000;

        BillQuery billQuery = new BillQuery();
        billQuery.setFormId("BD_SerialMainFile");
        billQuery.setFieldKeys("FNumber");
        List<Map> filterString = new ArrayList<>();
        filterString.add(UtilMap.map("FieldName, Compare, Value, Left, Right, Logic","FStockId.FName","67","成品仓","","","0"));//仓库名称等于XX
        filterString.add(UtilMap.map("FieldName, Compare, Value, Left, Right, Logic","FStockLocId.FF100001.FName","67","默认仓位","(","","1"));//仓位等于XX
        filterString.add(UtilMap.map("FieldName, Compare, Value, Left, Right, Logic","FStockLocId.FF100001.FName","67","样机仓位","",")","0"));//仓位等于XX
        filterString.add(UtilMap.map("FieldName, Compare, Value, Left, Right, Logic","FStockStatus","29","0","(","","1"));//在库状态等于XX
        filterString.add(UtilMap.map("FieldName, Compare, Value, Left, Right, Logic","FStockStatus","29","1","",")","0"));//在库状态等于XX

        billQuery.setFilterString(filterString);
        billQuery.setLimit(limit);
        billQuery.setStartRow(startRow);

        do {
            billQuery.setStartRow(startRow);
            String s = client.billQuery(JSONObject.toJSONString(billQuery));
            result = (List<Map>)JSONObject.parse(s);
            list.addAll(result);

            startRow += limit;
        }while (result.size() == limit);

        System.out.println("111");
    }

    @Test
    public void test2() {
        kdHuaGaoService.syncBDSerialMainFile(null);
    }


    @Test
    public void test3() {
        MDC.put("MDC_KEY_PID","1002");

        int year = 2025;
        int month = 9;

        List<Map> originList = new ArrayList<>();
        originList.add(UtilMap.map("cw, ssxl, zktsfl, year, month, value","成品仓","G100","0-30天",2023,1,1));
        originList.add(UtilMap.map("cw, ssxl, zktsfl, year, month, value","成品仓","G200","0-60天",2023,2,1));
        originList.add(UtilMap.map("cw, ssxl, zktsfl, year, month, value","成品仓","G300","0-30天",2023,3,1));
        originList.add(UtilMap.map("cw, ssxl, zktsfl, year, month, value","成品仓","G100","0-30天",2023,1,1));
        originList.add(UtilMap.map("cw, ssxl, zktsfl, year, month, value","成品仓","G100","0-90天",2023,1,1));
        originList.add(UtilMap.map("cw, ssxl, zktsfl, year, month, value","样机仓","G100","0-30天",2023,2,1));
        originList.add(UtilMap.map("cw, ssxl, zktsfl, year, month, value","样机仓","G200","0-30天",2023,1,1));
        originList.add(UtilMap.map("cw, ssxl, zktsfl, year, month, value","样机仓","G300","0-60天",2023,3,1));
        originList.add(UtilMap.map("cw, ssxl, zktsfl, year, month, value","样机仓","G100","0-30天",2023,1,1));
        originList.add(UtilMap.map("cw, ssxl, zktsfl, year, month, value","样机仓","G100","0-30天",2023,2,1));

        //删除宜搭历史最新库存信息
        List<Map> data = (List<Map>) ydClient.queryData(YDParam.builder()
                .formUuid("FORM-4CB51E04B8344622BE880C9D573F68CANKWU")
                .searchFieldJson(JSONObject.toJSONString(UtilMap.map("numberField_mev270x6, numberField_mev270x5",year, month)))
                .build(), YDConf.FORM_QUERY.retrieve_list).getData();

        List<String> formInstanceIdList = new ArrayList<>();

        for (Map datum : data) {
            formInstanceIdList.add(UtilMap.getString(datum,"formInstanceId"));
        }

        if(!formInstanceIdList.isEmpty()){
            ydClient.operateData(YDParam.builder()
                    .formUuid("FORM-4CB51E04B8344622BE880C9D573F68CANKWU")
                    .formInstanceIdList(formInstanceIdList)
                    .build(), YDConf.FORM_OPERATION.delete_batch);
        }

        List<Map> data2 = (List<Map>) ydClient.queryData(YDParam.builder()
                .formUuid("FORM-5764CC3F6D964FD3A165BD7D4D75999FO8NQ")
                .searchFieldJson(JSONObject.toJSONString(UtilMap.map("numberField_mev270x6",year)))
                .build(), YDConf.FORM_QUERY.retrieve_list).getData();

        List<String> formInstanceIdList2 = new ArrayList<>();

        for (Map datum : data2) {
            formInstanceIdList2.add(UtilMap.getString(datum,"formInstanceId"));
        }

        if(!formInstanceIdList2.isEmpty()){
            ydClient.operateData(YDParam.builder()
                    .formUuid("FORM-5764CC3F6D964FD3A165BD7D4D75999FO8NQ")
                    .formInstanceIdList(formInstanceIdList2)
                    .build(), YDConf.FORM_OPERATION.delete_batch);
        }

        //将最新库存信息写入宜搭
        List<Map> grouprList = originList.stream()
                .collect(Collectors.groupingBy(
                        item -> Arrays.asList(
                                item.get("cw"),
                                item.get("ssxl"),
                                item.get("zktsfl")
                        ),
                        Collectors.summingInt(item -> UtilMap.getInt(item, "value"))
                )).entrySet()
                .stream()
                .map(entry -> {
                    // 将分组键（List<Object>）和汇总值转换为 Map
                    List<Object> key = entry.getKey();
                    Map<String, Object> groupedItem = new LinkedHashMap<>();
                    groupedItem.put("textField_mev1n474", key.get(0));
                    groupedItem.put("textField_mev1n477", key.get(1));
                    groupedItem.put("selectField_mf205zr0", key.get(2));
                    groupedItem.put("numberField_mev270x6", year);
                    groupedItem.put("numberField_mev270x5", month);
                    groupedItem.put("numberField_mfat6egj", entry.getValue());
                    return groupedItem;
                }).collect(Collectors.toList());

        // 3. 打印原集合和分组结果
        System.out.println("=== 原集合（List<Map>）===");
        originList.forEach(System.out::println);

        System.out.println("\n=== 分组求和结果（List<Map>）===");
        grouprList.forEach(System.out::println);

        for (Map groupMap : grouprList) {
            ydClient.operateData(YDParam.builder()
                    .formUuid("FORM-4CB51E04B8344622BE880C9D573F68CANKWU")
                    .formDataJson(JSONObject.toJSONString(groupMap))
                    .build(), YDConf.FORM_OPERATION.create);

            ydClient.operateData(YDParam.builder()
                    .formUuid("FORM-5764CC3F6D964FD3A165BD7D4D75999FO8NQ")
                    .formDataJson(JSONObject.toJSONString(groupMap))
                    .build(), YDConf.FORM_OPERATION.create);
        }




    }

    @Test
    public void test4(){
        kdHuaGaoService.syncSTKInventory(null);
    }

    @Test
    public void test5(){
        kdHuaGaoService.syncPRDReturnMtrl(null);
    }

    @Test
    public void test6(){
        kdHuaGaoService.syncPendingProducts();
    }

    @Test
    public void test7(){
        kdHuaGaoService.syncDLVNotice(null);
    }

    @Test
    public void test8(){
        kdHuaGaoService.syncReport("成品库存天数看板","344749020127590108");
    }

    @Test
    public void test9(){
        String s = "更新成品库存天数看板异常：McException(success=false, code=InvalidpageSize, message=Specified parameter pageSize is not valid., source=dingtalk_new)  时间：2025-12-01 10:28:09";
        Map<String, Object> aaa = UtilMap.map("aaa, aa", s,"");

        System.out.println("aaa"+JSONObject.toJSONString(aaa));
    }

    @Test
    public void test10(){
        kdHuaGaoService.syncPUROrder(null);
    }

    private IdentifyInfo initIden(){
        //注意 1：此处不再使用参数形式传入用户名及密码等敏感信息，改为在登录配置文件中设置。
        //注意 2：必须先配置第三方系统登录授权信息后，再进行业务操作，详情参考各语言版本SDK介绍中的登录配置文件说明。
        //读取配置，初始化SDK
        IdentifyInfo iden = new IdentifyInfo();
        iden.setUserName(kdWebApiConf.getXKDApiUserName());
        iden.setAppId(kdWebApiConf.getXKDApiAppID());
        iden.setdCID(kdWebApiConf.getXKDApiAcctID());
        iden.setAppSecret(kdWebApiConf.getXKDApiAppSec());
        iden.setServerUrl(kdWebApiConf.getXKDApiServerUrl());

        return iden;
    }



}
