package com.yem.wm.syn.eas.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.yem.ia.intebilllogon.Utils.BackfilljsonAssignUtils;
import com.yem.wm.syn.eas.api.dto.IntebilllogonAuditDTO;
import com.yem.wm.syn.eas.api.service.IYZJAuditService;
import com.yem.wm.syn.eas.api.service.impl.YZJAuditServiceImpl;
import com.yem.wm.utils.YunzhijiaUtils;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.operate.result.OperateErrorInfo;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.entity.validate.ValidateResult;
import kd.bos.entity.validate.ValidateResultCollection;
import kd.bos.openapi.common.custom.annotation.ApiController;
import kd.bos.openapi.common.custom.annotation.ApiParam;
import kd.bos.openapi.common.custom.annotation.ApiPostMapping;
import kd.bos.openapi.common.result.CustomApiResult;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import org.jetbrains.annotations.NotNull;

import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 云之家审批接口
 */
@ApiController(value = "bos", desc = "")
public class YZJAuditController {

    @ApiPostMapping("/audit")
    public CustomApiResult<Object> yzjaudit(@NotNull @ApiParam("参数") @Valid IntebilllogonAuditDTO data, @ApiParam("状态") Boolean success, @ApiParam("错误码") String errorCode) throws IOException {
        try {
            IYZJAuditService service = new YZJAuditServiceImpl();
            service.audit(data, success, errorCode);
        } catch (Exception e) {
            CustomApiResult<Object> fail = CustomApiResult.fail("501", e.getMessage());
            return fail;
        }
        CustomApiResult<Object> ces = CustomApiResult.success("审核成功");
        return ces;
    }

    /**
     * 云之家回写
     *
     * @param data json参数
     * @return
     * @throws IOException
     */
    @ApiPostMapping("/rewriting")
    public CustomApiResult<Object> rewriting(@NotNull @ApiParam("参数") String data) throws IOException {
        try {
            JSONObject json = JSONObject.parseObject(data);
//            JSONObject data1 = json.getJSONObject("data");
            JSONObject basicInfo = json.getJSONObject("basicInfo");
            String formCodeId = basicInfo.getString("formCodeId");
            //通过表单定义ID获取模板
            String formInstId = basicInfo.getString("formInstId");
            ArrayList<QFilter> qFilters = new ArrayList<>();
            qFilters.add(new QFilter("yem_yzjid", QCP.equals, formCodeId));
            qFilters.add(new QFilter("yem_isdisable", QCP.equals, false));
            DynamicObject yem_ia_intebilllogon = BusinessDataServiceHelper.loadSingle("yem_ia_intebilllogon", qFilters.toArray(new QFilter[0]));
            if (yem_ia_intebilllogon != null) {
                yem_ia_intebilllogon = BusinessDataServiceHelper.loadSingle(yem_ia_intebilllogon.getLong("id"), "yem_ia_intebilllogon");
            } else {
                return CustomApiResult.success("调用成功");
            }
            //单据类型
            String bos_entityobjectnum = yem_ia_intebilllogon.getString("yem_formid.number");
            //获取单据
            DynamicObject billObj = BusinessDataServiceHelper.loadSingle(bos_entityobjectnum, new QFilter[]{new QFilter("yem_forminstid", QCP.equals, formInstId)});
            if (billObj != null) {
                billObj = BusinessDataServiceHelper.loadSingle(billObj.get("id"), bos_entityobjectnum);
            }
            //通过表单实例ID获取日志对象
            DynamicObject ialog = BusinessDataServiceHelper.loadSingle("yem_ialog", new QFilter[]{new QFilter("yem_forminstid", QCP.equals, billObj.get("yem_forminstid"))});
            ialog.set("yem_writeback", data);

            //TODO 调用云之家获取审批结果接口
            JSONObject reqjson = new JSONObject();
            reqjson.put("flowInstId", billObj.get("yem_flowinstid"));
            String retStr = YunzhijiaUtils.doPost(YunzhijiaUtils.yzjurl + "/gateway/yun/common/approve", reqjson.toString());
            JSONObject retJson = JSONObject.parseObject(retStr);
            if ("DISAGREE".equals(retJson.getString("data"))) {
                OperationResult result = OperationServiceHelper.executeOperate("unsubmit", billObj.getDynamicObjectType().getName(), new Object[]{billObj.get("id")}, OperateOption.create());
                if (result.isSuccess()) {
                    billObj.set("yem_isyzjreject", true);
                    SaveServiceHelper.save(new DynamicObject[]{billObj});
                } else {
                    throw new Exception(result.getMessage());
                }
            } else if ("FINISH".equals(retJson.getString("data"))) {
                //回写数据
                BackfilljsonAssignUtils.BackfilljsonAssign(data);
                OperationResult result = OperationServiceHelper.executeOperate("audit", billObj.getDynamicObjectType().getName(), new Object[]{billObj.get("id")}, OperateOption.create());
                String audit = result(result, "audit");
                DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle(billObj.get("id"), billObj.getDynamicObjectType());
                if (audit != null) {
                    dynamicObject.set("yem_synfalt", "同步失败,点击按钮查看失败详情！");
                    dynamicObject.set("yem_synfalt_tag", "同步失败,失败原因:" + audit);
                    ialog.set("yem_error","调用单据审核失败");
                    ialog.set("yem_error_tag",audit);
                    ialog.set("yem_success",false);
                    SaveServiceHelper.update(dynamicObject);
//                    SaveServiceHelper.save(new DynamicObject[]{ialog});
                    OperationServiceHelper.executeOperate("unsubmit", billObj.getDynamicObjectType().getName(), new Object[]{billObj.get("id")}, OperateOption.create());
                    CustomApiResult<Object> fail = CustomApiResult.fail("501", audit);
                    return fail;
                } else {
                    ialog.set("yem_success",true);
                    ialog.set("yem_error"," ");
                    ialog.set("yem_error_tag"," ");
                    dynamicObject.set("yem_synfalt", "同步成功");
                    SaveServiceHelper.update(dynamicObject);
//                    SaveServiceHelper.save(new DynamicObject[]{ialog});
                }

            }
            SaveServiceHelper.save(new DynamicObject[]{ialog});
        } catch (Exception e) {
            CustomApiResult<Object> fail = CustomApiResult.fail("501", e.getMessage());
            return fail;
        }
        CustomApiResult<Object> ces = CustomApiResult.success("调用成功");
        return ces;
    }

    /**
     * 云之家整机合同驳回
     *
     * @param data
     * @return
     * @throws IOException
     */
    @ApiPostMapping("/CompleteCallback")
    public CustomApiResult<Object> CompleteCallback(@NotNull @ApiParam("参数") String data) throws IOException {
        try {
            JSONObject json = JSONObject.parseObject(data);
//            JSONObject data1 = json.getJSONObject("data");
            JSONObject basicInfo = json.getJSONObject("basicInfo");
            String formCodeId = basicInfo.getString("formCodeId");
            //通过表单定义ID获取模板
            String formInstId = basicInfo.getString("formInstId");
            ArrayList<QFilter> qFilters = new ArrayList<>();
            qFilters.add(new QFilter("yem_yzjid", QCP.equals, formCodeId));
            qFilters.add(new QFilter("yem_isdisable", QCP.equals, false));
            DynamicObject yem_ia_intebilllogon = BusinessDataServiceHelper.loadSingle("yem_ia_intebilllogon", qFilters.toArray(new QFilter[0]));
            if (yem_ia_intebilllogon != null) {
                yem_ia_intebilllogon = BusinessDataServiceHelper.loadSingle(yem_ia_intebilllogon.getLong("id"), "yem_ia_intebilllogon");
            } else {
                return CustomApiResult.success("调用成功");
            }
            //单据类型
            String bos_entityobjectnum = yem_ia_intebilllogon.getString("yem_formid.number");
            //获取单据
            DynamicObject billObj = BusinessDataServiceHelper.loadSingle(bos_entityobjectnum, new QFilter[]{new QFilter("yem_sigforminstid", QCP.equals, formInstId)});
            if (billObj != null) {
                billObj = BusinessDataServiceHelper.loadSingle(billObj.get("id"), bos_entityobjectnum);
                //通过表单实例ID获取日志对象 yem_sigforminstid
                DynamicObject ialog = BusinessDataServiceHelper.loadSingle("yem_ialog", new QFilter[]{new QFilter("yem_forminstid", QCP.equals, billObj.get("yem_sigforminstid"))});
                ialog.set("yem_writeback", data);
                SaveServiceHelper.save(new DynamicObject[]{ialog});
                //TODO 调用云之家获取审批结果接口
                JSONObject reqjson = new JSONObject();
                reqjson.put("flowInstId", billObj.get("yem_sigflowinstid"));
                String retStr = YunzhijiaUtils.doPost(YunzhijiaUtils.yzjurl + "/gateway/yun/common/approve", reqjson.toString());
                JSONObject retJson = JSONObject.parseObject(retStr);
                //状态码 FINISH：同意已完成
                // DISAGRE：不同意已完成
                // RUNNING：待审批
                // SUSPEND：挂起
                // RETURNED：待提交(审批人退回到发起节点)
                // TOSUBMIT：待提交(发起人自己撤回)
                // ABANDON：废弃
                // DELETE：已删除
                //驳回更新 合同签章同步状态
                if ("DISAGREE".equals(retJson.getString("data"))) {
                    billObj.set("yem_sigstatus", false);//合同签章同步状态
                    billObj.set("yem_sigmag", null);//合同签章同步说明
                    billObj.set("yem_sigforminstid", null);//合同签章云之家表单实例id
                    billObj.set("yem_sigflowinstid", null);//合同签章云之家流程实例id
                    SaveServiceHelper.save(new DynamicObject[]{billObj});
                } else {
                    return CustomApiResult.success("根据云之家审批示例ID获取到的状态为【" + retJson.getString("data") + "】,无需更新！");
                }
            } else {
                return CustomApiResult.fail("501", "未获取到合同签章云之家表单实例id为【" + formInstId + "】的数据！");
            }
        } catch (Exception e) {
            CustomApiResult<Object> fail = CustomApiResult.fail("501", e.getMessage());
            return fail;
        }
        CustomApiResult<Object> ces = CustomApiResult.success("调用成功");
        return ces;
    }


    private String result(OperationResult result, String operation) {
        if (!result.isSuccess()) {
            ValidateResultCollection validateResult = result.getValidateResult();
            List<ValidateResult> validateErrors = validateResult.getValidateErrors();
            StringBuilder stringBuilder = new StringBuilder();
            if (result.getMessage() != null) {
                stringBuilder.append(result.getMessage());
            }
            for (ValidateResult validateError : validateErrors) {
                List<OperateErrorInfo> allErrorInfos = validateError.getAllErrorInfo();
                for (OperateErrorInfo allErrorInfo : allErrorInfos) {

                    String message = allErrorInfo.getMessage();
                    stringBuilder.append(message + ";");
                }
            }
            List<OperateErrorInfo> allErrorInfos = result.getAllErrorInfo();
            for (OperateErrorInfo allErrorInfo : allErrorInfos) {
                String message = allErrorInfo.getMessage();
                stringBuilder.append(message);
            }
            return operation + stringBuilder;
            //throw new KDBizException(operation+stringBuilder);
        }
        return null;
    }
}
