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

import com.alibaba.fastjson.JSONObject;
import kd.bos.algo.DataSet;
import kd.bos.algo.Row;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.db.DB;
import kd.bos.db.DBRoute;
import kd.bos.entity.operate.result.IOperateInfo;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.metadata.dao.MetaCategory;
import kd.bos.metadata.dao.MetadataDao;
import kd.bos.metadata.form.FormMetadata;
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.List;

/**
 * @author zhouc
 * @date 2024/5/13 11:25
 * @className OperationalUniversal
 * @description 根据单据编码调用单据操作
 */
@ApiController(desc = "OperationalUniversal", value = "EAS操作通用服务")
public class OperationalUniversal {
    @ApiPostMapping("/OperationalServre")
    public CustomApiResult<Object> OperationalServre(@NotNull @ApiParam("操作类型") @Valid String operateKey,
                                                     @NotNull @ApiParam("单据编号（外贸）") @Valid String billno,
                                                     @NotNull @ApiParam("单据标识") @Valid String entityName) throws IOException {
        try {
            QFilter qFilter = new QFilter("billno", QCP.equals, billno);
            DynamicObject bill = BusinessDataServiceHelper.loadSingle(entityName, "id", qFilter.toArray());
            if (bill != null) {
                DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle(bill.getPkValue(), bill.getDynamicObjectType().getName());
                if (dynamicObject != null) {
                    String operate = getoperateName(entityName, operateKey);
                    String id = MetadataDao.getIdByNumber(dynamicObject.getDynamicObjectType().getName(), MetaCategory.Form);
                    FormMetadata formMeta = (FormMetadata) MetadataDao.readRuntimeMeta(id, MetaCategory.Form);
                    String name = formMeta.getName().toString();
                    if (operate.length() > 0) {
                        OperationResult audit = OperationServiceHelper.executeOperate(operateKey, dynamicObject.getDynamicObjectType().getName(), new Object[]{dynamicObject.getPkValue()}, OperateOption.create());
                        if (!audit.isSuccess()) {
                            List<IOperateInfo> allErrorOrValidateInfo = audit.getAllErrorOrValidateInfo();
                            String message = audit.getMessage();
                            String msg = "【" + name + "】调用【" + operate + "】操作失败，失败原因为：\r\n";
                            CustomApiResult<Object> fail = CustomApiResult.fail("501", msg + message + "\r\n" + allErrorOrValidateInfo);
                            return fail;
                        } else {
                            if (operateKey.equals("unsubmit") || operateKey.equals("unaudit")) {
                                dynamicObject.set("yem_iseas", false);
                                dynamicObject.set("yem_synfalt", null);
                                dynamicObject.set("yem_synfalt_tag", null);
                                SaveServiceHelper.update(dynamicObject);
                            }
                        }
                    } else {
                        String errorMessage = "【" + name + "】不存在编码为【" + operateKey + "】的操作编码，请核对后重试！";
                        CustomApiResult<Object> fail = CustomApiResult.fail("501", errorMessage);
                        return fail;
                    }
                }
            }
        } catch (Exception e) {
            CustomApiResult<Object> fail = CustomApiResult.fail("501", e.getMessage());
            return fail;
        }
        CustomApiResult<Object> ces = CustomApiResult.success("成功");
        return ces;
    }

    public static String getoperateName(String entityName, String operateKey) {
        String sql = "select fdata from t_meta_entity  where fnumber='" + entityName + "' and fkey='" + operateKey + "'";
        DataSet dataDataSet = DB.queryDataSet("", DBRoute.meta, sql.toString());
        if (dataDataSet != null) {
            for (Row data : dataDataSet) {
                String fdata = data.get("fdata").toString();
                JSONObject jsonObject = JSONObject.parseObject(fdata);
                String name = jsonObject.getJSONObject("name").getString("zh_CN");
                return name;
            }
        }
        return "";
    }

    //PriceLibraryDisable
    //yem_pricelibrary
    //GMPJJGD2403000051
    //unaudit
    @ApiPostMapping("/PriceLibraryDisable")
    public CustomApiResult<Object> PriceLibraryDisable(@NotNull @ApiParam("单据编号（配件）") @Valid String billno) throws IOException {
        try {
            QFilter qFilter = new QFilter("billno", QCP.equals, billno);
            qFilter.and(new QFilter("yem_billtype.number", QCP.equals, "yem_pricelibrary_PJ"));
            DynamicObject bill = BusinessDataServiceHelper.loadSingle("yem_pricelibrary", "id", qFilter.toArray());
            if (bill != null) {
                DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle(bill.getPkValue(), bill.getDynamicObjectType().getName());
                if (dynamicObject != null) {
                    dynamicObject.set("yem_totaldisabledstatus", "1");
                    SaveServiceHelper.update(dynamicObject);
                } else {
                    String errorMessage = "【配件价格库】不存在编码为【" + billno + "】的操作编码，请核对后重试！";
                    CustomApiResult<Object> fail = CustomApiResult.fail("501", errorMessage);
                    return fail;
                }
            }
        } catch (
                Exception e) {
            CustomApiResult<Object> fail = CustomApiResult.fail("501", e.getMessage());
            return fail;
        }
        CustomApiResult<Object> ces = CustomApiResult.success("成功");
        return ces;
    }
}
