package com.malk.gewu.service.impl;

import com.alibaba.fastjson.JSON;
import com.malk.gewu.service.GWService;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.dingtalk.DDConf;
import com.malk.service.aliwork.YDClient;
import com.malk.service.dingtalk.DDClient;
import com.malk.service.dingtalk.DDClient_Contacts;
import com.malk.service.dingtalk.DDClient_Personnel;
import com.malk.service.dingtalk.DDClient_Schedule;
import com.malk.utils.UtilDateTime;
import com.malk.utils.UtilFile;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class GWImplService implements GWService {

    @Autowired
    private DDClient ddClient;

    @Autowired
    private DDConf ddConf;

    @Autowired
    private DDClient_Contacts ddClient_contacts;

    @Autowired
    private DDClient_Personnel ddClient_personnel;

    @Autowired
    private YDClient ydClient;

    /**
     * 同步花名册信息 ppExt:: 格屋临时添加, 后续上线限流重试功能
     */
    @Override
    public void syncRoster() {

        // 花名册元数据
        List<Map> metaList = (List<Map>) UtilFile.readJsonObjectFromResource("static/json/personnel"); // 本地匹配了宜搭组件ID
//        List<Map> metaList = ddClient_personnel.getPersonnelMeta(ddClient.getAccessToken(), ddConf.getAgentId());
        // 同步全量人员
        ddClient_contacts.getDepartmentId_all(ddClient.getAccessToken(), true).forEach(deptId -> {
            List<String> userIds = ddClient_contacts.listDepartmentUserId(ddClient.getAccessToken(), deptId);
            log.info("dept, {}, userIds, {}", deptId, userIds.size());
            if (userIds.size() == 0) {
                return;
            }
            // 员工花名册信息
            ddClient_personnel.getEmployeeInfos(ddClient.getAccessToken(), userIds, ddConf.getAgentId(), null).forEach(employeeInfo -> {
                // 通过元数据字段code, 匹配员工花名册value
                List<Map> employeeField = (List<Map>) employeeInfo.get("field_data_list");
                // 宜搭表单数据
                Map formData = UtilMap.map("employeeField_limrznyp", Arrays.asList(employeeInfo.get("userid"))); // 成员权限
                metaList.forEach(meta -> {
                    boolean isDetail = UtilMap.getBoolean(meta, "detail");
                    List<Map> metaField = (List<Map>) meta.get("field_meta_info_list");
                    Map detail = new HashMap(); // 明细行
                    metaField.forEach(field -> {
                        // 元数据内一些系统字段无 field_code, sys00 基本信息分组下 使用 field_name
                        Optional optional = employeeField.stream().filter(employee -> field.get("field_code").equals(employee.get("field_code")) || employee.get("field_name").equals(field.get("field_name"))).findAny();
                        if (optional.isPresent()) {
                            // 数据组装
                            Map employee = (Map) optional.get();
                            String value = UtilMap.getString(((List<Map>) employee.get("field_value_list")).get(0), "label");
                            log.info("分组 -> {}, 是否明细 -> {}; 字段 -> {}, 值 -> {}", meta.get("group_name"), meta.get("detail"), field.get("field_name"), value);
                            // 值处理
                            if (field.containsKey("comp_id")) {
                                if (isDetail) {
                                    detail.put(field.get("comp_id"), value);
                                } else {
                                    formData.put(field.get("comp_id"), value);
                                }
                            }
                        }
                    });
                    // 明细表
                    if (isDetail && meta.containsKey("comp_id")) {
                        formData.put(meta.get("comp_id"), Arrays.asList(detail));
                    }
                });
                // 宜搭更新
                YDParam ydParam = YDParam.builder()
                        .searchFieldJson(JSON.toJSONString(UtilMap.map("employeeField_limrznyp", formData.get("employeeField_limrznyp"))))
                        .formUuid("FORM-EA866E71M5ICA9TSABIFG9V1QMRN2PFL786KL8")
                        .build();
                List<String> formInstIds = (List<String>) ydClient.queryData(ydParam, YDConf.FORM_QUERY.retrieve_search_form_id).getData();
                if (formInstIds.size() > 0) {
                    ydParam.setFormInstanceId(formInstIds.get(0));
                    ydParam.setUpdateFormDataJson(JSON.toJSONString(formData));
                    ydClient.operateData(ydParam, YDConf.FORM_OPERATION.update);
                } else {
                    ydParam.setFormDataJson(JSON.toJSONString(formData));
                    ydClient.operateData(ydParam, YDConf.FORM_OPERATION.create);
                }
            });
        });
    }

    @Autowired
    private DDClient_Schedule ddClient_schedule;

    /**
     * 创建钉钉日程
     */
    @Override
    public void createSchedule(String summary, String description, List<String> usrIds, Date sTime, Date eTIme, String organizer) {
        String startTime = UtilDateTime.format(sTime, UtilDateTime.DATE_TIME_ISO).replace("+0800", "+08:00");
        String endTime = UtilDateTime.format(eTIme, UtilDateTime.DATE_TIME_ISO).replace("+0800", "+08:00");
        // ppExt: start 与 end 不能使用同一个map对象, 会报错date不能为空.
        Map start = UtilMap.map("dateTime, timeZone", startTime, "Asia/Shanghai");
        Map end = UtilMap.map("dateTime, timeZone", endTime, "Asia/Shanghai");
        Map body = UtilMap.map("summary, description, start, end, userIds", summary, description, start, end, usrIds);
        ddClient_schedule.eventsSchedule(ddClient.getAccessToken(), organizer, body);
    }

    /// test
    @Override
    public void test() {

        ddClient_personnel.getPersonnelMeta(ddClient.getAccessToken(), ddConf.getAgentId());
    }
}
