package com.malk.yzl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.aliwork.YDSearch;
import com.malk.server.dingtalk.DDR_New;
import com.malk.service.aliwork.YDClient;
import com.malk.service.dingtalk.DDClient;
import com.malk.service.dingtalk.DDClient_Schedule;
import com.malk.utils.PublicUtil;
import com.malk.utils.UtilMap;
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.lang.reflect.Array;
import java.util.*;

import static com.malk.utils.ISO8601Converter.toISO8601;

@SpringBootTest
@RunWith(SpringRunner.class)
public class JdTest {


    @Autowired
    private YDClient ydClient;
    @Autowired
    private YDConf ydConf;
    @Autowired
    private DDClient_Schedule ddClientSchedule;
    @Autowired
    private DDClient ddClient;


    @Test
    public void test(){
        Map map=new HashMap();
//        map.put("summary","日程名称");
        map.put("start",getDate(1778292000000L));
        map.put("end",getDate(1778295600000L));
        map.put("userIds", Arrays.asList("153620324221442254"));
        map.put("location", UtilMap.map("displayName","甬水商务中心"));
        String result=ddClientSchedule.eventsSchedule(ddClient.getAccessToken(),"tom",map);
        JSONObject obj=JSONObject.parseObject(result);
        if(obj.containsKey("id")&& !PublicUtil.isNull(obj.get("id"))){

        }else {
            System.out.println("请求失败！"+obj.getString("message"));
        }
        System.out.println(result);


//        ddClientSchedule.queryAttendees(ddClient.getAccessToken(),"h1TfGwHiP1Nj7U3mXWoptkgiEiE","RFZQRU1JN2NNOFpMRTNNckRhL1ZEZz09");
    }

    private Map getDate(long time){
        return UtilMap.map("dateTime, timeZone",toISO8601(time, "Asia/Shanghai"),"Asia/Shanghai");
    }

    @Test
    public void queryOrder2(){
        List<String> users=new ArrayList<>();
        Map<String,Map> userSaveMap=new HashMap<>();

        Map formdata=ydClient.queryData(YDParam.builder().formInstId("FINST-LX966EB1ZTY4NI2SNVIU787ICN2B2R4OUTGOMUE8").build(), YDConf.FORM_QUERY.retrieve_id).getFormData();
        System.out.println(formdata);
        List<Map> mapList=ydConf.associationForm(String.valueOf(formdata.get("associationFormField_mn774naw_id")));
        System.out.println(mapList);
        for (Map map : mapList) {
            String instanceId=UtilMap.getString(map, "instanceId");
            Map user=ydClient.queryData(YDParam.builder().formInstId(instanceId).build(), YDConf.FORM_QUERY.retrieve_id).getFormData();
            if(user!=null&&user.containsKey("employeeField_mogigdaq_id")){
                users.addAll(UtilMap.getList(user, "employeeField_mogigdaq_id"));
                userSaveMap.put(UtilMap.getString(user,"textField_mn6syci3"),UtilMap.map("textField_mowiqmgq, associationFormField_mn774naw, textField_mowj9roq, selectField_mowiqmgr, dateField_mn6vz0hj",
                        UtilMap.getString(formdata,"serialNumberField_mn6vz0ha"),Arrays.asList(map),UtilMap.getString(user,"textField_mn6syci3"),"未操作",null));
            }
        }
        save("","","未操作",userSaveMap);
    }

    private void save(String sid,String uname,String status,Map saveMap){
        if(saveMap==null||saveMap.isEmpty()){
            saveMap=new HashMap();
        }
        if(PublicUtil.isNull(uname)){
            return;
        }
        saveMap.put("textField_mowj9rop", sid);
        saveMap.put("selectField_mowiqmgr", status);
        ydClient.operateData(YDParam.builder().formDataJson(JSONObject.toJSONString(saveMap)).formUuid("FORM-CD59959AAB334321A2542558A8285D5BMZ2K").searchCondition(JSONObject.toJSONString(Arrays.asList(
                ydConf.searchCondition_TextFiled("textField_mowj9rop",sid,"eq"),ydConf.searchCondition_TextFiled("textField_mowj9roq",uname,"eq")
        ))).build(), YDConf.FORM_OPERATION.upsert);
    }

    @Test
    public void sync(){
        long now = System.currentTimeMillis();
        List<Map> dataList = (List<Map>)ydClient.queryData(YDParam.builder().formUuid("FORM-F99DB628726944A18721E5F7B08B196CZ8F3").searchCondition(JSONObject.toJSONString(Arrays.asList(
                new YDSearch("textField_moxsll4l","是","是否已创建日程",YDSearch.Type.TEXT_FIELD, YDSearch.Operator.EQ),
                new YDSearch("dateField_mn6vz0hj",now,"截至时间",YDSearch.Type.DATE_FIELD, YDSearch.Operator.GE)
        ))).build(), YDConf.FORM_QUERY.retrieve_list).getData();
        for (Map map : dataList) {
            Map formData=UtilMap.getMap(map,"formData");
            List userIds=UtilMap.getList(formData,"employeeField_moglrzqk_id");
            if(userIds==null||userIds.size()<1){
                continue;
            }
            String sid=UtilMap.getString(formData,"textField_mowj9rop");
            String result=ddClientSchedule.queryAttendees(ddClient.getAccessToken(),String.valueOf(userIds.get(0)),sid);
            JSONObject obj=JSONObject.parseObject(result);
            if(obj.containsKey("attendees")&& !PublicUtil.isNull(obj.get("attendees"))){
                JSONArray attendees =  obj.getJSONArray("attendees");
                for (int i = 0; i < attendees.size(); i++) {
                    JSONObject attendee=attendees.getJSONObject(i);
                    String name=attendee.getString("displayName");
                    save(sid,name,getStatus(attendee.getString("responseStatus")),null);
                }
            }else {
                System.out.println("请求失败！"+obj.getString("message"));
            }
        }
    }

    private String getStatus(String code){
        switch (code){
            case "needsAction": return "未操作";
            case "accepted": return "已接受";
            case "declined": return "已拒绝";
            case "tentative": return "暂定接受";
        }
        return "";
    }
}
