package com.malk.guyuan.controller;

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.DDR_New;
import com.malk.service.aliwork.YDClient;
import com.malk.service.aliyun.ALYInvoice;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

    @Autowired
    private ALYInvoice invoice;

    @Autowired
    private YDClient ydClient;

    /**
     * 阿里发票验真
     */
    @PostMapping("/invoice/check")
    McR invoiceCheckPDF(@RequestBody Map<String, String> param) {
        log.info("阿里发票验真, 文件, {}", param);
        McException.assertParamException_Null(param, "url");
        return McR.success(invoice.invoiceCheckPDF("4e2c048bfe1d4feea7354a66c7944fd1", param.get("url")));
    }

    /**
     * 阿里发票验真: image
     */
    @PostMapping("invoice/ocr")
    McR invoiceCheckImage(@RequestBody Map<String, String> param) {
        log.info("阿里发票验真, 图片, {}", param);
        return McR.success(invoice.invoiceCheckOCR("4e2c048bfe1d4feea7354a66c7944fd1", param.get("url")));
    }

    /**
     * 宜搭临时免登地址: 钉钉平台
     */
    @PostMapping("openUrl")
    McR openUrl(@RequestBody Map<String, String> param) {
        McException.assertParamException_Null(param, "url");
        return McR.success(ydClient.convertTemporaryUrl(param.get("url")));
    }

    /**
     * 全局查询子表单
     */
    @PostMapping("queryAll")
    McR queryAll(@RequestBody YDParam ydParam) {
        return McR.success(ydClient.queryData(ydParam, YDConf.FORM_QUERY.retrieve_list_all));
    }

    /**
     * 全局查询(不匹配子表单)
     */
    @PostMapping("validate")
    McR queryAll(HttpServletRequest request) {
        Map<String, ?> param = UtilServlet.getParamMap(request);
        log.info("全局查询(不匹配子表单), {}", param);
        if (ObjectUtil.isNull(param.get("uniques"))) {
            return McR.success();
        }
        McException.assertParamException_Null(param, "uniques", "formUuid", "compId");
        // 容错 - 尾部分号的空格会被输入框忽略
        String[] uniques = String.valueOf(param.get("uniques")).replace("; ", ";").split(";");
        for (String val : uniques) {
            // 查重校验: 单张发票唯一标识 + 审批已通过 / 审批中
            List<Map> conditions = new ArrayList<>();
            Map unique = new HashMap();
            unique.put("key", param.get("compId"));
            unique.put("value", val.split(": ")[1]);
            unique.put("type", "TEXT");
            unique.put("operator", "like");
            unique.put("componentName", "TextField");
            conditions.add(unique);

            Map approve = new HashMap();
            approve.put("key", "processApprovedResult");
            approve.put("value", new String[]{"agree"});
            approve.put("type", "ARRAY");
            approve.put("operator", "in");
            approve.put("componentName", "SelectField");
            conditions.add(approve);
            YDParam ydParam = YDParam.builder()
                    .appType("APP_FKRK7Y94DPI1S9DV1605")
                    .systemToken("FN7666A1ZD0STZZ75W4CKD1GD07X3PUW2FBRKT")
                    .formUuid(String.valueOf(param.get("formUuid")))
                    .searchCondition(JSON.toJSONString(conditions))
                    .build();
            DDR_New ddr_new = ydClient.queryData(ydParam, YDConf.FORM_QUERY.retrieve_list);
            log.info("审批通过匹配结果, {}, {}", ddr_new.getTotalCount(), ddr_new.getData());
            if (ddr_new.getTotalCount() > 0) {
                return McR.errorAccess("发票已被使用, 请勿重复提交!");
            }

            conditions.remove(approve);
            Map status = new HashMap();
            status.put("key", "processInstanceStatus");
            status.put("value", new String[]{"RUNNING"});
            status.put("type", "ARRAY");
            status.put("operator", "in");
            status.put("componentName", "SelectField");
            conditions.add(status);
            ydParam.setSearchCondition(JSON.toJSONString(conditions));
            ddr_new = ydClient.queryData(ydParam, YDConf.FORM_QUERY.retrieve_list);
            log.info("审批通过匹配结果, {}, {}", ddr_new.getTotalCount(), ddr_new.getData());
            if (ddr_new.getTotalCount() > 0) {
                return McR.errorAccess("发票已在流程中, 请勿重复提交!");
            }
        }
        return McR.success();
    }

    /**
     * 服务状态返回
     */
    @PostMapping("validateTips")
    McR validateTaxNo(HttpServletRequest request) {
        Map data = UtilServlet.getParamMap(request);
        if (!data.get("status").equals(1)) {
            return McR.errorAccess("error");
        }
        return McR.success(data);
    }
}
