package com.malk.jianhui;

import com.alibaba.fastjson.JSONObject;
import com.malk.jianhui.service.JianhuiService;
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 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.ArrayList;
import java.util.List;
import java.util.Map;

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

    @Autowired
    private YDClient ydClient;

    @Autowired
    private JianhuiService jianhuiService;

    @Test
    public void test(){
        List<Map> ydFormDataList = getYdFormDataList("FORM-2A5CAB7EB91D493AAFC90D8C7479A7F5KPR7", "", YDConf.FORM_QUERY.retrieve_list);

        for (Map data : ydFormDataList) {
            String formInstId = data.get("formInstanceId").toString();
            Map formData = (Map) data.get("formData");
            String code = formData.get("textField_m6ak640v").toString();

            String type = code.substring(0,1).equals("C") ? "成品" : "配件";

            ydClient.operateData(YDParam.builder()
                    .formInstId(formInstId)
                    .updateFormDataJson(JSONObject.toJSONString(UtilMap.map("selectField_m83u6et1",type)))
                    .useLatestVersion(true)
                    .build(),YDConf.FORM_OPERATION.update);

        }


    }

    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;
    }

    @Test
    public void test2(){
        jianhuiService.syncMaterial();
    }

}
