package com.malk.cloudpure.controller;

import com.alibaba.fastjson.JSON;
import com.malk.cloudpure.service.CPClient;
import com.malk.server.common.McException;
import com.malk.server.common.McR;
import com.malk.server.xbongbong.XBBConf;
import com.malk.service.dingtalk.DDClient;
import com.malk.service.dingtalk.DDClient_Contacts;
import com.malk.service.xbongbong.XBBClient;
import com.malk.utils.UtilDateTime;
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.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 错误抛出与拦截详见 CatchException
 */
@Slf4j
@RestController
@RequestMapping("crm")
public class XBBController {

    @Autowired
    private XBBClient xbbClient;

    /**
     * 模糊查询归属权限下客户列表
     */
    @PostMapping("list/customer")
    McR customerList(@RequestBody Map<String, String> data) {

        log.info("客户列表, {}", data);
        McException.assertParamException_Null(data, "name, userId");

        List<Map> customers = new ArrayList<>();
        customers.addAll(_likeCustomerList(XBBConf.API_LIST_customer, "钉钉", data.get("name"), data.get("userId")));
        customers.addAll(_likeCustomerList(XBBConf.API_LIST_customer, "Teambition", data.get("name"), data.get("userId")));

        log.info("客户响应, {}", customers);
        return McR.success(customers);
    }

    /**
     * 模糊查询归属权限下, 指定字段类型 [后置查询]
     */
    private List<Map> _likeCustomerList(String url, String type, String name, String userId) {
        List<Map> rsp = xbbClient.getFormList(type, 1, 100);
        long formId = UtilMap.getLong(rsp.get(0), "formId");
        rsp = xbbClient.getFormDefine(formId, 0); // 表单定义
        String nameField = (rsp.stream().filter(item -> item.get("attrName").equals("客户名称")).findAny().get()).get("attr").toString();
        rsp = xbbClient.getDataList(url, formId, Arrays.asList(XBBConf.getConditionMap(nameField, "like", name)), null);
        return rsp.stream().filter(item -> {
            List<String> ownerId = (List<String>) JSON.parse(String.valueOf(((Map) item.get("data")).get("ownerId")));
            List<String> coUserId = (List<String>) JSON.parse(String.valueOf(((Map) item.get("data")).get("coUserId")));
            // 后置查询, 属于客户负责人和协同人
            return ownerId.contains(userId) || coUserId.contains(userId);
        }).map(item -> UtilMap.map("name", String.valueOf(((Map) item.get("data")).get(nameField)))).collect(Collectors.toList());
    }

    /**
     * 模糊查询归属权限下, 指定字段类型 [后置查询]
     */
    private List<Map> _likeContractList(String url, String type, String name, String userId) {
        List<Map> rsp = xbbClient.getFormList(type, 1, 201);
        long formId = UtilMap.getLong(rsp.get(0), "formId");
        rsp = xbbClient.getFormDefine(formId, 0); // 表单定义
        String nameField = (rsp.stream().filter(item -> item.get("attrName").equals("合同名称")).findAny().get()).get("attr").toString();
        String codeField = (rsp.stream().filter(item -> item.get("attrName").equals("合同编号")).findAny().get()).get("attr").toString();
        String cashField = (rsp.stream().filter(item -> item.get("attrName").equals("合同金额")).findAny().get()).get("attr").toString();
        rsp = xbbClient.getDataList(url, formId, Arrays.asList(XBBConf.getConditionMap(nameField, "like", name)), null);
        return rsp.stream().filter(item -> {
            List<String> ownerId = (List<String>) JSON.parse(String.valueOf(((Map) item.get("data")).get("ownerId")));
            List<String> coUserId = (List<String>) JSON.parse(String.valueOf(((Map) item.get("data")).get("coUserId")));
            // 后置查询, 属于客户负责人和协同人
            return ownerId.contains(userId) || coUserId.contains(userId);
        }).map(item -> {
            Map data = (Map) item.get("data");
            return UtilMap.map("name, value", data.get(nameField), data.get(codeField) + "/" + data.get(cashField));
        }).collect(Collectors.toList());
    }

    /**
     * 模糊查询归属权限下合同列表
     */
    @PostMapping("list/contract")
    McR contractList(@RequestBody Map<String, String> data) {

        log.info("合同列表, {}", data);
        McException.assertParamException_Null(data, "name, userId");

        List<Map> customers = new ArrayList<>();
        customers.addAll(_likeContractList(XBBConf.API_LIST_contract, "钉钉", data.get("name"), data.get("userId")));
        // prd 5.9 Teambition合同中台停用
        //customers.addAll(_likeContractList(XBBConf.API_LIST_contract, "Teambition", data.get("name"), data.get("userId")));

        log.info("合同响应, {}", customers);
        return McR.success(customers);
    }

    /**
     * 自动填充合同编号/合同金额
     */
    @PostMapping("code/contract")
    McR contractCode(@RequestBody Map<String, String> data) {

        String[] content = data.get("code").split("/");
        log.info("自动填充, {}, {}", content);
        return McR.success(UtilMap.map("code, cash", content[0], content[1]));
    }


    @Autowired
    private DDClient ddClient;

    @Autowired
    private DDClient_Contacts ddClient_contacts;

    @Autowired
    private CPClient cpClient;

    @PostMapping("test")
    McR test() {

        //ddClient_contacts.getUserInfoById(ddClient.getAccessToken(), "16608972969409067");
        LocalDate date = UtilDateTime.parseLocalDate("2024-05-15");
        cpClient.syncXBongBongForRecord_all(date);

        String sDate = UtilDateTime.formatDate(UtilDateTime.parseDate("2024-05-15"));
        cpClient.syncDingTalkLogForRecord(sDate);
        return McR.success();
    }
}


