package com.malk.harrison.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.malk.harrison.config.HarrisonConfig;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.common.McException;
import com.malk.server.dingtalk.DDConf;
import com.malk.service.aliwork.YDClient;
import com.malk.utils.UtilServlet;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

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

    @Autowired
    private YDClient ydClient;

    @Autowired
    private DDConf ddConf;

    @Autowired
    private HarrisonConfig harrisonConfig;

    /**
     * 动态审批人
     */
    @PostMapping("sds/test")
    List<String> sdsTest(HttpServletRequest request) {
        Map param = UtilServlet.getParamMap(request);

        if (true) {
            return Arrays.asList(ddConf.getOperator());
        }

        McException.assertParamException_Null(param, "compId", "BusinessType");
        Map condition = new HashMap();

        String compId = param.get("compId").toString();
        //数据条件参数
        condition.put("textField_lisbeacj", param.get("BusinessType"));
        condition.put("selectField_lisbeack", param.get("City"));
        condition.put("selectField_lisbeacm", param.get("CompanyCode"));
        //宜搭参数赋值
        YDParam ydParam = YDParam.builder()
                .formUuid("FORM-PR8667D1QWKB5AYJEKDJ18IKE6IE3JUNDBSIL2")
                .searchFieldJson(JSON.toJSONString(condition))
                .build();
        List<Map> list = (List<Map>) ydClient.queryData(ydParam, YDConf.FORM_QUERY.retrieve_search_form).getData();

        return emailList(list, ydParam, compId);
    }

    //获取人员ID的公用方法
    List<String> emailList(List<Map> list, YDParam ydParam, String ProcessCoding) {
        List<String> userIds = new ArrayList<>();
        for (Map row : list) {
            Map mailCondition = new HashMap();
            Map formData = (Map) row.get("formData");
            //String mail1 = String.valueOf(formData.getDefault("textField_lisbeacp"));
            String mail1 = String.valueOf(formData.get(ProcessCoding));
            for (String mail : mail1.split(";#")) {
                if (mail.contains("@")) {
                    mailCondition.put("textField_lg22sfep", mail);
                    ydParam.setFormUuid("FORM-MFA66S91RAO8YAB1CUTCED77NK9133TR5XQEL8");
                    ydParam.setSearchFieldJson(JSON.toJSONString(mailCondition));
                    //调用宜搭接口
                    List<Map> users = (List<Map>) ydClient.queryData(ydParam, YDConf.FORM_QUERY.retrieve_search_form).getData();
                    if (users.size() > 0) {
                        Map userData = (Map) users.get(0).get("formData");
                        List<String> userId = (List<String>) userData.get("employeeField_lisbbxca_id");
                        userIds.addAll(userId);
                    }
                }
            }
        }
        return userIds;
    }

    /**
     * 回写招聘子表
     */
    @PostMapping("sds/update")
    Map sdsUpdate(HttpServletRequest request) {

        // 查询招聘申请
        Map param = UtilServlet.getParamMap(request);
        McException.assertParamException_Null(param, "formInstId");
        YDParam ydParam = YDParam.builder()
                .appType(harrisonConfig.getYida().getAppType())
                .systemToken(harrisonConfig.getYida().getSystemToken())
                .formInstId(String.valueOf(param.get("formInstId")))
                .build();
        Map rsp = (Map) ydClient.operateData(ydParam, YDConf.FORM_OPERATION.update);
        Map formData = (Map) rsp.get("formData");
        log.info("索迪斯回写子表, {}, {}", param, formData);

        // 组装分发子表数据
        Map detail = new HashMap();
        detail.put("associationFormField_lf7pkag4", JSON.parse(String.valueOf(formData.get("associationFormField_lg54gbt9_id")))); // 职位组
        detail.put("textField_lf7pkag5", formData.get("textField_lg54gbta")); // 新员工姓名
        detail.put("dateField_lf7pkag6", formData.get("dateField_lg54gbtf")); // 入职日期

        // todo: 成员, 附件, 关联表单
        List<Map> association = JSON.parseArray(String.valueOf(JSON.parse(String.valueOf(formData.get("associationFormField_lg0gmbi8_id")))), Map.class);
        String formInstId = String.valueOf(association.get(0).get("instanceId"));
        ydParam.setFormInstId(formInstId);
        Map rspSrc = (Map) ydClient.operateData(ydParam, YDConf.FORM_OPERATION.update);
        Map formDataSrc = (Map) rspSrc.get("formData");
        List<Map> list = new ArrayList<>();
        if (ObjectUtil.isNotNull(formDataSrc.get("tableField_lf7pkag3"))) {
            list = (List<Map>) formDataSrc.get("tableField_lf7pkag3");
        }

        // 更新流程数据
        Map form = new HashMap();
        list.add(detail);
        form.put("tableField_lf7pkag3", list);
        form.put("numberField_lfj9d501", 2);
        ydParam.setUpdateFormDataJson(JSON.toJSONString(form));
        ydClient.operateData(ydParam, YDConf.FORM_OPERATION.update);

        log.info("更新, {}, {}", formInstId, form);

        Map r = new HashMap();
        r.put("success", true);
        return r;
    }
}
