package com.malk.kuaikeli.controller;

import com.alibaba.fastjson.JSON;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.common.McR;
import com.malk.service.aliwork.YDClient;
import com.malk.service.aliwork.YDService;
import com.malk.utils.UtilMap;
import com.malk.utils.UtilMc;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

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

    @Autowired
    private YDService ydService;

    /**
     * [动态] 发起单据, 分供应商进行流程推送
     */
    @PostMapping("supplier")
    McR supplier(HttpServletRequest request) {

        Map data = UtilServlet.getParamMap(request);
        log.info("supplier, {}", JSON.toJSONString(data));

        // ppExt: 供应商区分发起: 当前表：供应供子表组件ID，子表内供应商编号，名称，负责人
        String[] compIds_supplier = String.valueOf(data.get("compId_supplier")).split(", ");
        String compId_supplier = compIds_supplier[1];

        Map formData = (Map) JSON.parse(String.valueOf(data.get("formData")));
        List<Map> details = (List<Map>) formData.get(compIds_supplier[0]);

        // 供应商编号, 数据去重: 提取数据区分供应商发起
        List<Map> suppliers = UtilMc.distinctByKey(details, compId_supplier);
        for (Map supplier : suppliers) {
            List<Map> dataList = details.stream().filter(item -> supplier.get(compId_supplier).equals(item.get(compId_supplier))).collect(Collectors.toList());
            formData.put(compIds_supplier[0], dataList);
            // ppExt: 参数传递, 目标表组件ID, 对照当前表子表内的子表内供应商编号，名称，负责人已放置主表字段, 此处公共内容提前首条数据进行赋值
            for (int i = 1; i < compIds_supplier.length; i++) {
                formData.put(compIds_supplier[i], YDConf.getDataByCompId(dataList.get(0), compIds_supplier[i]));
            }
            data.put("formData", JSON.toJSONString(formData));
            ydService.copyFormData(data); // 发起流程
        }
        return McR.success();
    }

    @Autowired
    private YDClient ydClient;

    /**
     * 菜单计划, 编辑校验
     * -
     * 前端提交动作: 校验是否审批通过, 是否当日之前计划, 是否当日且在16点及以后时间, 均不允许提交
     * 后端校验返回、加任何产品都要走审批，减少20%以内直接过，每一个原材料
     */
    @PostMapping("validate")
    McR validate(@RequestBody Map data) {

        log.info("validate, {}", JSON.toJSONString(data));

        boolean approve = false;
        List<Map> dataList = UtilMap.getList(data, "list");
        for (Map row : dataList) {

            // 匹配切配工作单, 采购
            List<Map> formList = (List<Map>) ydClient.queryData(YDParam.builder()
                            .formUuid("FORM-RK966E71T0LDSTW39WFHE9OQ5GU23FKRRDNLL2")
                            .searchFieldJson(JSON.toJSONString(UtilMap.map("textField_lmsuq8am, textField_lm8zta2z, textField_ln1ez5li", data.get("name"), data.get("area"), row.get("textField_ln1ez5li"))))
                            .build(),
                    YDConf.FORM_QUERY.retrieve_search_form).getData();

            if (formList.size() == 0) {
                approve = true;
                break;
            }
            Map formData = (Map) formList.get(0).get("formData");
            float cur = UtilMap.getFloat(row, "numberField_lmym5628");
            float src = UtilMap.getFloat(formData, "numberField_lnrkgimz");
            if (cur > src || (src - cur) / src > 0.2f) {
                approve = true;
                break;
            }
        }

        if (approve) {
            // 发起菜单审批
            ydClient.operateData(YDParam.builder()
                    .formUuid("FORM-UP96637100HD036TA1M05B74GHLV3DRS54NLLC")
                    .processCode("TPROC--UP96637100HD036TA1M05B74GHLV3ERS54NLLD")
                    .formDataJson(JSON.toJSONString(data.get("form"))) // 前端数据组装
                    .userId(data.get("user").toString())
                    .build(), YDConf.FORM_OPERATION.start);

            // 更新计划状态
            ydService.operateData(YDParam.builder()
                    .formInstanceId(data.get("poid").toString())
                    .updateFormDataJson(JSON.toJSONString(UtilMap.map("textField_lm8znr9n", "执行中")))
                    .build(), YDConf.FORM_OPERATION.update);
        }

        return McR.success();
    }


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


        Map data = UtilServlet.getParamMap(request);

        log.info("xxxx, {}", data);

        return McR.success();
    }

}
