package com.malk.mc.controller;


import com.alibaba.fastjson.JSONObject;
import com.malk.mc.service.McYdService;
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.DDR_New;
import com.malk.service.aliwork.YDClient;
import com.malk.service.aliwork.YDService;
import com.malk.utils.PublicUtil;
import com.malk.utils.UtilMap;
import com.malk.utils.UtilServlet;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/***
 * 宜搭服务
 */
@Slf4j
@RestController
@RequestMapping("/yd/")
public class McYdController {

    @Autowired
    private YDService ydService;
    @Autowired
    private YDClient ydClient;

    @Autowired
    private McYdService mcYdService;


    /***
     * 复制表单数据到另一个表
     * @param param
     * @return
     */
    @PostMapping("copy")
    public McR copy(@RequestBody JSONObject param) {
        if (PublicUtil.isNull(param, "instanceId", "formUuid")) {
            return McR.errorNullPointer();
        }
        ydService.mirrorFormData(param.getString("instanceId"), param.getString("formUuid"), param.getString("processCode"), param.getString("processUserId"),
                param.getJSONObject("updateData"), param.getString("updateInstanceId"));
        return McR.success();
    }

    /***
     * 保存关联表单数据
     * @param param
     * @return
     */
    @PostMapping("saveGl")
    public McR saveGl(@RequestBody JSONObject param) {
        if (PublicUtil.isNull(param, "formInstId", "formUuid", "title", "saveFormInstId", "compId", "appType")) {
            return McR.errorNullPointer();
        }
        ydClient.operateData(YDParam.builder().updateFormDataJson(JSONObject.toJSONString(UtilMap.map(param.getString("compId"), Arrays.asList(
                UtilMap.map("appType, formType, instanceId, title, subTitle, formUuid", param.getString("appType"), "receipt", param.getString("formInstId")
                        , param.getString("title"), param.getString("subTitle"), param.getString("formUuid")))
        ))).formInstId(param.getString("saveFormInstId")).build(), YDConf.FORM_OPERATION.update);
        return McR.success();
    }

    /**
     * 根据筛选条件获取表单数据
     *
     * @param
     * @return
     */
    @GetMapping("getFromData")
    public Map getFromData(String formUuid, String fieldCode, String fileValue) {
        log.info("formUuid:{},fieldCode:{},fileValue:{}", formUuid, fieldCode, fileValue);
        MDC.put("MDC_KEY_PID", "1004");
//        McProject.addYida("1004",new String[] {"APP_YMOUJB8W36ZVCJ9BUE77","YE966DA1CKMCAWSRAM78Y5K6NESA27LKXC9KL6C2"});

        fileValue = Objects.nonNull(fileValue) ? fileValue : "";

        List<Map> ydFormDataList = getYdFormDataList(formUuid, JSONObject.toJSONString(UtilMap.map(fieldCode, fileValue)), YDConf.FORM_QUERY.retrieve_list);

        Map<String, Object> resultMap = new HashMap<>();

        resultMap.put("data", ydFormDataList);

        return resultMap;
    }


    private List<Map> getYdFormDataList(String formUuid, String searchCondition, YDConf.FORM_QUERY formQuery) {
        List<Map> list = new ArrayList<>();
        DDR_New ddrNew;
        int pageNumber = 1;
        int pageSize = 100;
        do {
            ddrNew = ydClient.queryData(YDParam.builder().formUuid(formUuid)
                    .searchCondition(searchCondition)
                    .pageNumber(pageNumber)
                    .pageSize(pageSize).build(), formQuery);

            list.addAll((List<Map>) ddrNew.getData());
            pageNumber++;
        } while (ddrNew.getTotalCount() > ddrNew.getPageNumber() * pageSize);
        return list;
    }

    /**
     * 更新表单数据版本
     *
     * @param map
     * @return
     */
    @PostMapping("/updateFormDataVersion")
    public McR updateFormDataVersion(@RequestBody Map map) {
        mcYdService.updateFormDataVersion(map);

        return McR.success();
    }

    /**
     * 批量更新符合条件的指定数量的实例（批量上限100条）
     * @param map
     * @return
     */
    @PostMapping("/batchUpdateSpecifiedQuantityData")
    public McR batchUpdateSpecifiedQuantityData(@RequestBody Map map){
        mcYdService.batchUpdateSpecifiedQuantityData(map);
        return McR.success();
    }

    /**
     * 发起审批
     *
     * @param map
     * @return
     */
    @PostMapping("initiateApproval")
    public McR initiateApproval(@RequestBody Map map) {
        return mcYdService.initiateApproval(map);
    }

    //子表数值转化为文本，添加千位分隔符
    @PostMapping("/convertSubTableNumber")
    public McR convertSubTableNumber(@RequestBody Map map) {
        return mcYdService.convertSubTableNumber(map);
    }

    @PostMapping("/saveApproverToForm")
    public McR saveApproverToForm(@RequestBody Map map) {
        McException.assertParamException_Null(map, "formInstId", "key");
        return mcYdService.saveApproverToForm(map);
    }

    //海天二期开发部分(出库)
    @PostMapping("/multiLocationOutbound")
    public McR multiLocationOutbound(@RequestBody Map map) {
//        return mcYdService.multiLocationOutbound(map);
        return mcYdService.multiLocationOutboundAI(map);
    }

    //海天二期开发部分（入库）
    @PostMapping("/WarehouseStorage")
    public McR WarehouseStorage(@RequestBody Map map) {
//        return mcYdService.WarehouseStorage(map);
        return mcYdService.WarehouseStorageAI(map);
    }

    //海天二期开发（退货）
    @PostMapping("/ProductReturn")
    public McR ProductReturn(@RequestBody Map map) {
        return mcYdService.ProductReturn(map);
    }

    //海天二期开发(调拨)
    @PostMapping("/allocateTransfer")
    public McR allocateTransfer(@RequestBody Map map) {
        return mcYdService.allocateTransfer(map);
    }

    //海天二期开发（进货退货）
    @PostMapping("/goodsInandOut")
    public McR goodsInandOut(@RequestBody Map map){
        return mcYdService.goodsInandOut(map);
    }

    //海天二期开发（开票）
    @PostMapping("/Invoicing")
    public  McR Invoicing(@RequestBody Map map){return mcYdService.Invoicing(map);}

    //海天二期开发（收票）
    @PostMapping("/receiveInvoice")
    public McR receiveInvoice(@RequestBody Map map){return mcYdService.receiveInvoice(map);}

    /**
     * 分享数据权限
     * @param map compId 表单分享权限所属, userIds 分享人及被分享人, userId 分享人, content 代办标题, atUserId 被分享人, appUrl 移动端地址, pcUrl PC端地址
     * @param header POC下MC服务项目pid
     * @return
     */
    @PostMapping("/shareRecord")
    public McR shareRecord(@RequestBody Map map, @RequestHeader Map header) {
        map.put("pid",header.get("pid").toString());
        return mcYdService.shareRecord(map);
    }

    //同意或拒绝宜搭审批任务
    @PostMapping("/approveTask")
    public McR approveTask(@RequestBody Map map) {
        return mcYdService.approveTask(map);
    }

    //同步宜搭权限矩阵
    @PostMapping("/syncYdAuth")
    public McR syncYdAuth(@RequestBody Map map) {
        return mcYdService.syncYdAuth(map);
    }

    //删除宜搭权限矩阵
    @PostMapping("/delYdAuth")
    public McR delYdAuth(@RequestBody Map map) {
        return mcYdService.delYdAuth(map);
    }

}
