package com.malk.service.teambition.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.common.McException;
import com.malk.server.dingtalk.DDR_New;
import com.malk.service.aliwork.YDClient;
import com.malk.service.teambition.TBClient;
import com.malk.service.teambition.TBService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class TBServiceImpl implements TBService {

    @Autowired
    private TBClient tbClient;

    @Autowired
    private YDConf ydConf;

    @Autowired
    private YDClient ydClient;


    // 查询操作人在tb的userId
    @Override
    public List<String> convertUserIdWithSearch(String search) {
        List<Map> users = tbClient.userSearch(search);
        McException.assertAccessException(users.isEmpty(), search + ": 未匹配到TB用户, 请联系管理员添加");
        return users.stream().map(item -> String.valueOf(item.get("userId"))).collect(Collectors.toList());
    }

    // 钉钉用户唯一键转同步用户ID
    @Override
    public List<String> convertUserIdWithSearch_bulk(Map<String, Object> data) {
        List<String> userIds = new ArrayList<>();
        for (String unique : (List<String>) data.get("usersUnique")) {
            userIds.addAll(convertUserIdWithSearch(unique));
        }
        return userIds;
    }

    @SneakyThrows
    @Async
    @Override
    public void updateProject_YD_TB(Map projectInfo, String userName) {
        // Map projectInfo = tbClient.projectDetail(null, "R1", null).get(0);
        Thread.sleep(2000);
        // 查询宜搭项目
        JSONObject condition = new JSONObject();
        condition.put("textField_l9m4krcc", projectInfo.get("name"));
        DDR_New projectData = ydClient.queryData(YDParam.builder()
                .appType(ydConf.getAppType())
                .formUuid("FORM-NC966W81NXY4NPSVAFXCC8THGDOX3VY1F3M9LI")
                .searchCondition(JSONObject.toJSONString(condition))
                .build(), YDConf.FORM_QUERY.retrieve_list);
        List<Map> dataList = (List<Map>) projectData.getData();
        // 更新宜搭项目
        if (dataList.size() > 0) {
            JSONObject update = new JSONObject();
            update.put("textField_l9t7eqe1", projectInfo.get("id"));
            update.put("textField_l9t7eqe3", projectInfo.get("logo"));
            update.put("textField_l9t7eqe6", projectInfo.get("isSuspended"));
            update.put("radioField_l9t7eqeb", Boolean.TRUE.equals(projectInfo.get("isSuspended")) ? "是" : "否");
            update.put("textField_l9t7eqe4", projectInfo.get("isTemplate"));
            update.put("radioField_l9t7eqec", Boolean.TRUE.equals(projectInfo.get("isTemplate")) ? "是" : "否");
            update.put("textField_l9t7eqe5", projectInfo.get("creatorId"));
            update.put("textField_l9t7eqed", projectInfo.get("tasklistIds"));
            ydClient.operateData(YDParam.builder()
                    .appType(ydConf.getAppType())
                    .formInstanceId((String) dataList.get(0).get("formInstanceId"))
                    .updateFormDataJson(JSONObject.toJSONString(update))
                    .build(), YDConf.FORM_OPERATION.update);
        }
        // 更新tb项目
        Map formData = (Map) (dataList.get(0)).get("formData");
        Map info = new HashMap();
        info.put("description", formData.get("textareaField_l9m4krcy"));
        if (ObjectUtil.isNotNull(formData.get("dateField_l9t7eqe9"))) {
            info.put("startDate", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format((Long.valueOf(String.valueOf(formData.get("dateField_l9t7eqe9"))))));
        }
        if (ObjectUtil.isNotNull(formData.get("dateField_l9t7eqea"))) {
            info.put("endDate", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format((Long.valueOf(String.valueOf(formData.get("dateField_l9t7eqea"))))));
        }
        String operatorId = convertUserIdWithSearch(userName).get(0);
        tbClient.projectUpdate(String.valueOf(projectInfo.get("id")), info, operatorId);
    }
}
