package com.malk.yzl.controller;

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.common.McR;
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 lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

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

@RestController
@Slf4j
@RequestMapping("/zzw/")
public class ZzwController {

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

    @PostMapping("/schedule/create")
    public McR createSchedule(@RequestBody JSONObject jsonObject){
        log.info("创建日程接口：{}",jsonObject);
        if(!PublicUtil.isNull(jsonObject,"sId")){
            return McR.success("已创建日程");
        }
        if(PublicUtil.isNull(jsonObject,"summary","start","end","createUid","fid")){
            return McR.error("201","参数不能为空！");
        }
        List<String> userIds=new ArrayList<>();
        Map<String,Map> userSaveMap=new HashMap<>();
        Map formdata=ydClient.queryData(YDParam.builder().formInstId(jsonObject.getString("fid")).build(), YDConf.FORM_QUERY.retrieve_id).getFormData();
        List<Map> mapList=ydConf.associationForm(String.valueOf(formdata.get("associationFormField_mn774naw_id")));
        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")){
                userIds.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"),"未操作",jsonObject.getLong("end")));
            }
        }
        Map map=new HashMap();
        map.put("summary",jsonObject.getString("summary"));
        map.put("start",getDate(jsonObject.getLong("start")));
        map.put("end",getDate(jsonObject.getLong("end")));
        map.put("userIds", userIds);
        if(!PublicUtil.isNull(jsonObject,"location")){
            map.put("location", UtilMap.map("displayName",jsonObject.getString("location")));
        }
        String result=ddClientSchedule.eventsSchedule(ddClient.getAccessToken(),jsonObject.getString("createUid"),map);
        JSONObject obj=JSONObject.parseObject(result);
        if(obj.containsKey("id")&& !PublicUtil.isNull(obj.get("id"))){
            log.info("创建成功：{}",obj);
            ydClient.operateData(YDParam.builder().updateFormDataJson(JSONObject.toJSONString(UtilMap.map("textField_mowj9rop, textField_moxsll4l",obj.getString("id"),"是"))).formInstId(jsonObject.getString("fid")).build(), YDConf.FORM_OPERATION.update);
            JSONArray attendees =  obj.getJSONArray("attendees");
            for (int i = 0; i < attendees.size(); i++) {
                JSONObject attendee=attendees.getJSONObject(i);
                String name=attendee.getString("displayName");
                save(obj.getString("id"),name,getStatus(attendee.getString("responseStatus")),userSaveMap.get(name));
            }
        }else {
            log.info("请求失败！{}",obj.getString("message"));
            return McR.error("201",obj.getString("message"));
        }
        return McR.success("已创建日程");
    }

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

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

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

}
