package com.malk.hongfeng.controller;

/**
 * 错误抛出与拦截详见 CatchException
 */

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.common.McException;
import com.malk.server.common.McR;
import com.malk.server.dingtalk.DDConf;
import com.malk.service.aliwork.YDClient;
import com.malk.service.aliwork.YDService;
import com.malk.service.dingtalk.DDClient;
import com.malk.service.dingtalk.DDClient_Contacts;
import com.malk.utils.UtilMap;
import com.malk.utils.UtilServlet;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping
public class HFController {

    @Autowired
    private YDClient ydClient;

    @Autowired
    private DDClient ddClient;

    @Autowired
    private DDClient_Contacts ddClient_contacts;

    @PostMapping("user")
    McR user(HttpServletRequest request) {
        Map data = UtilServlet.getParamMap(request);
        log.info("部门信息, {}", data);

        long deptId = _getDptId(UtilMap.getString(data, "dept"), UtilMap.getString(data, "type"), null);        // 兼容用户创建
        Map extInfo = UtilMap.map("email", "hf@dingtalk.com");
        try {
            Map result = ddClient_contacts.createUser_dingTalk(ddClient.getAccessToken(), UtilMap.getString(data, "cardNo"), "dingtalk123", UtilMap.getString(data, "name"), Arrays.asList(deptId), extInfo);
            // 更新宜搭用户ID
            String instId = UtilMap.getString(data, "instId");
            ydClient.operateData(YDParam.builder()
                    .formInstanceId(instId)
                    .updateFormDataJson(JSON.toJSONString(UtilMap.map("employeeField_lozj5ga2, textField_lozi7dtc", Arrays.asList(result.get("userid")), deptId)))
                    .build(), YDConf.FORM_OPERATION.update);
        } catch (McException e) {
            log.error(e.getMessage(), e);  // 记录错误日志
        }
        return McR.success();
    }

    @PostMapping("dept")
    McR dept(HttpServletRequest request) {
        Map data = UtilServlet.getParamMap(request);
        log.info("部门信息, {}", data);

        _getDptId(UtilMap.getString(data, "dept"), UtilMap.getString(data, "type"), UtilMap.getString(data, "instId"));
        return McR.success();
    }

    // 获取部门ID, 不存在创建
    long _getDptId(String dept, String belong, String instId) {

        // 查询是否存在单位
        List<Map> dataList = (List<Map>) ydClient.queryData(YDParam.builder()
                .formUuid("FORM-F8666NB1TJPAM8J46DE07DC7BWUU2S8DM1RHL2")
                .searchFieldJson(JSON.toJSONString(UtilMap.map("textField_lhr1qpgw", dept)))
                .build(), YDConf.FORM_QUERY.retrieve_search_form).getData();
        if (dataList.size() > 0) {
            Map formData = null;
            if (dataList.size() == 1) {
                formData = (Map) dataList.get(0).get("formData");
            } else {
                // ppExt: 宜搭单行输入框, 会命中模糊查询
                formData = dataList.stream().filter(item -> dept.equals(item.get("textField_lhr1qpgw"))).findAny().get();
            }
            // 导入触发, 数据可立即查询到. 此时部门还未更新, 过滤
            if (StringUtils.isNotBlank(UtilMap.getString(formData, "textField_lozi7dtc"))) {
                return UtilMap.getLong(formData, "textField_lozi7dtc");
            }
        }
        // 不存在创建新部门
        long deptId = DDConf.TOP_DEPARTMENT;
        if ("虹口".equals(belong)) {
            deptId = 906069409L;
        }
        if ("虹峰".equals(belong)) {
            deptId = 906484067L;
        }
        Map result = ddClient_contacts.createDepartment(ddClient.getAccessToken(), dept, deptId, UtilMap.map("create_dept_group", false));
        long dept_id = UtilMap.getLong(result, "dept_id");
        // 更新宜搭部门ID
        if (StringUtils.isNotBlank(instId)) {
            ydClient.operateData(YDParam.builder()
                    .formInstanceId(instId)
                    .updateFormDataJson(JSON.toJSONString(UtilMap.map("textField_lozi7dtc", dept_id)))
                    .build(), YDConf.FORM_OPERATION.update);
        } else {
            // 兼容用户创建
            ydClient.operateData(YDParam.builder()
                    .formUuid("FORM-F8666NB1TJPAM8J46DE07DC7BWUU2S8DM1RHL2")
                    .formDataJson(JSON.toJSONString(UtilMap.map("textField_lozi7dtc, textField_lhr1qpgw, selectField_lhyev50s", dept_id, dept, belong)))
                    .build(), YDConf.FORM_OPERATION.create);
        }
        return dept_id;
    }

    @Autowired
    private YDService ydService;

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

        List<Map> dataList = ydService.queryFormData_all(YDParam.builder()
                .formUuid("FORM-CP7660811C7A9ZSIE41VABIL55Z72X2NMYPHLD1")
                .dynamicOrder(JSON.toJSONString(UtilMap.map("textField_lhr135cr", "+")))
                .build());
        log.info("同步数量, {}", dataList.size());
        dataList.forEach(item -> {

            log.info("修改人员, {}", item.get("textField_lhr135cl"));
            List<Map> details = (List<Map>) item.get("tableField_lnwm6abn");
            details = details.stream().filter(detail -> {
                if (ObjectUtil.isNotNull(detail.get("selectField_logsa5ru"))) {
                    detail.put("textField_logsa5rb", item.get("selectField_lozq62h7"));
                    return true;
                }
                return false;
            }).collect(Collectors.toList());
            Map data = UtilMap.map("tableField_lnwm6abn", details);
            if (StringUtils.isBlank(String.valueOf(item.get("selectField_loxqxuv7")))) {
                data.put("selectField_loxqxuv7", item.get("textField_lhr135dc"));
            }
            ydClient.operateData(YDParam.builder()
                    .formInstanceId(item.get("instanceId").toString())
                    .updateFormDataJson(JSON.toJSONString(data))
                    .useLatestVersion(true)
                    .build(), YDConf.FORM_OPERATION.update);
        });

        return McR.success();
    }
}
