package com.zfire.mall.manager.logic.k3.bill;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.client.utils.JSONUtils;
import com.zfire.mall.manager.bean.k3.*;
import com.zfire.mall.manager.bean.k3.bill.CommonOrderBean;
import com.zfire.mall.manager.bean.k3.bill.SyncK3OtherReceBean;
import com.zfire.mall.manager.bean.k3.bill.result.BillItem;
import com.zfire.mall.manager.bean.k3.bill.result.ResultBean;
import com.zfire.mall.manager.bean.k3.bill.result.SuccessEntitys;
import com.zfire.mall.manager.constant.KingDeeCons;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.helper.KingDeeInvokeHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

@Slf4j
public abstract class CommonOrderLogic {

    private static final String queryId = "FID";

    private static final String queryBillNo = "FBillNo";

    public static String getQueryId() {
        return queryId;
    }

    public static String getQueryBillNo() {
        return queryBillNo;
    }

    /**
     * 同步订单
     * @param commonOrderBean
     * @param interfaceOrderType
     * @return
     * @throws Exception
     */
    ResultBean syncBillData(CommonOrderBean commonOrderBean, String interfaceOrderType, boolean isUnAudit) throws Exception {
        // 登录金蝶
//        this.loginKingDee(true);

        if (isUnAudit) {
            // 先检查单据是否存在，存在执行删除
            this.unAudit(queryBillNo, commonOrderBean.getBillNo(), interfaceOrderType);
        }

        // 准备请求数据
        RequestBillBean requestBean = new RequestBillBean();
        if (commonOrderBean.isPushUpdate()) {
            requestBean.setNeedUpDateFields(commonOrderBean.pushUpdateFields());
        }
        requestBean.setModel(commonOrderBean);

        String res = KingDeeInvokeHelper.Save(interfaceOrderType, JSONUtils.serializeObject(requestBean));
        ResultBean result = JSONObject.parseObject(res).getObject("Result", ResultBean.class);
        if (!result.getResponseStatus().isSuccess()) {
            throw new RemoteServiceException(result.getResponseStatus().getErrorInfo());
        }
        return result;
    }

    /**
     * 反审核并删除订单
     * @param queryKey
     * @param keyValue
     * @param interfaceOrderType
     * @return
     */
//    boolean unAudit(String queryKey, String keyValue, String interfaceOrderType) throws Exception {
//        return this.unAudit(queryKey, keyValue, interfaceOrderType, true);
//    }
    boolean unAudit(String queryKey, String keyValue, String interfaceOrderType) throws Exception {
        // 登录金蝶
//        this.loginKingDee(login);

        // 查询单据状态 C=审核 D=反审
        RequestApiBean requestApiBean = new RequestApiBean();
        requestApiBean.setFieldKeys("FDocumentStatus");
        requestApiBean.setFilterString(String.format(queryKey + " = '%s'", keyValue));
        requestApiBean.setFormId(interfaceOrderType);
        String res = KingDeeInvokeHelper.ExecuteBillQuery(null, JSONUtils.serializeObject(requestApiBean));
        JSONArray array = JSONArray.parseArray(res);
        if (array.size() > 0) {
            RequestUnAuditBean requestUnAuditBean = new RequestUnAuditBean();
            if (queryId.equals(queryKey)) {
                requestUnAuditBean.setIds(keyValue);
            } else {
                requestUnAuditBean.setNumbers(keyValue);
            }

            ResultBean result;
            // 金蝶销售订单存在，单据状态为已审核，调用反审核接口
            if (array.getJSONArray(0).getString(0).equals("C")) {
                res = KingDeeInvokeHelper.UnAudit(interfaceOrderType, JSONUtils.serializeObject(requestUnAuditBean));
                result = JSONObject.parseObject(res).getObject("Result", ResultBean.class);
                if (res.contains("\"IsSuccess\":false")) {
                    throw new RemoteServiceException(result.getResponseStatus().getErrorInfo());
                }
            }
            // 金蝶销售订单存在，单据状态为审核中，调用撤消接口
            if (array.getJSONArray(0).getString(0).equals("B")) {
                res = KingDeeInvokeHelper.Cancel(interfaceOrderType, JSONUtils.serializeObject(requestUnAuditBean));
                result = JSONObject.parseObject(res).getObject("Result", ResultBean.class);
                if (res.contains("\"IsSuccess\":false")) {
                    throw new RemoteServiceException(result.getResponseStatus().getErrorInfo());
                }
            }
            // 金蝶销售订单存在，单据状态为非审核，调用删除接口
            res = KingDeeInvokeHelper.Delete(interfaceOrderType, JSONUtils.serializeObject(requestUnAuditBean));
            result = JSONObject.parseObject(res).getObject("Result", ResultBean.class);
            if (res.contains("\"IsSuccess\":false")) {
                throw new RemoteServiceException(result.getResponseStatus().getErrorInfo());
            }
        }
        return true;
    }

    /**
     * 订单下推
     * @param billNo
     * @param ruleId
     * @param interfaceOrderType
     * @param ruleId
     * @return
     * @throws Exception
     */
    ResultBean push(String billNo, List<String> entryIds, String interfaceOrderType, String ruleId) throws Exception {
        // 登录金蝶
//        this.loginKingDee(true);

        // 准备请求
        RequestPushBean requestPushBean = new RequestPushBean();
        requestPushBean.setNumbers(billNo);
        requestPushBean.setRuleId(ruleId);
        if (CollectionUtil.isNotEmpty(entryIds)) {
            // 如果entryIds有数据，numbers注空串，只针对处理同一客户下推时为一个单，否则会变多个单导致调用方业务异常
            requestPushBean.setNumbers("");
            requestPushBean.setEntryIds(StringUtils.join(entryIds, ","));
        }
        // 发送请求
        String res = KingDeeInvokeHelper.Push(interfaceOrderType, JSONUtils.serializeObject(requestPushBean));
        ResultBean result = JSONObject.parseObject(res).getObject("Result", ResultBean.class);
        if (!result.getResponseStatus().isSuccess()) {
            throw new RemoteServiceException(result.getResponseStatus().getErrorInfo());
        }
        if (CollectionUtil.isNotEmpty(result.getResponseStatus().getSuccessEntitys())
                && result.getResponseStatus().getSuccessEntitys().size() > 1) {
            // 多个单导致调用方业务异常，删除下游单据
            for (SuccessEntitys successEntity : result.getResponseStatus().getSuccessEntitys()) {
                if (interfaceOrderType.equals(KingDeeCons.SALE_ORDER)) {
                    this.unAudit(queryId, successEntity.getId(), KingDeeCons.SALE_OUT_STOCK);
                } else if (interfaceOrderType.equals(KingDeeCons.SALE_OUT_STOCK)) {
                    this.unAudit(queryId, successEntity.getId(), KingDeeCons.SALE_RET_BILL);
                }
            }
            throw new RemoteServiceException("下推时单据产生异常");
        }
        return result;
    }

    String pushSalesChangeNew(String id, List<String> ids) throws Exception {
        // 登录金蝶
//        this.loginKingDee(true);

        // 准备请求
        Map<String, Object> billNoMap = new HashMap<>();
        billNoMap.put("SaleOrderBillId", id);
//        billNoMap.put("SaleOrderBillNo", billNo);
//        billNoMap.put("SOEntryIds", ids);
        log.info("【销售变更单】request:{}",JSONUtil.toJsonStr(billNoMap));
        String res = KingDeeInvokeHelper.SaveXSaleOrder(null, JSONUtil.toJsonStr(billNoMap));
        log.info("【销售变更单】response:{}",res);
        //ResultBean result = JSONObject.parseObject(res).getObject("Result", ResultBean.class);
        Map map = JSONObject.parseObject(res, Map.class);
        Boolean isSuccess = (Boolean)map.get("IsSuccess");
        String message = (String)map.get("Message");
        if (!isSuccess) {
            throw new RemoteServiceException(message);
        }
        List<Map<String, Object>> datas = (List<Map<String, Object>>) map.get("Datas");
        String fBillNo = (String)datas.get(0).get("FBillNo");
        return fBillNo;
    }

    ResultBean takeEffectSalesChange(String id, String interfaceOrderType) throws Exception {
        Map<String, Object> takeEffectMap = new HashMap<>();
        takeEffectMap.put("FormId", interfaceOrderType);
        takeEffectMap.put("opNumber", "TakeEffect");
        takeEffectMap.put("data", new HashMap<String, Object>() {{
            this.put("Numbers", id);
        }});
        String res = KingDeeInvokeHelper.ExcuteOperation(interfaceOrderType, JSONUtil.toJsonStr(takeEffectMap), null);
        ResultBean result = JSONObject.parseObject(res).getObject("Result", ResultBean.class);
        if (!result.getResponseStatus().isSuccess()) {
            this.unAudit(queryId, id, interfaceOrderType);
            throw new RemoteServiceException(result.getResponseStatus().getErrorInfo());
        }
        return result;
    }


    /**
     * 查询单据明细信息
     * @param queryKey
     * @param keyValue
     * @param fieldKeys
     * @param interfaceOrderType
     * @return
     * @throws Exception
     */
//    List<BillItem> queryBillItemRowInfo(String queryKey, String keyValue, String fieldKeys, String interfaceOrderType) throws Exception {
//        return this.queryBillItemRowInfo(queryKey, keyValue, fieldKeys, interfaceOrderType, true);
//    }
    List<BillItem> queryBillItemRowInfo(String queryKey, String keyValue, String fieldKeys, String interfaceOrderType) throws Exception {
        // 登录金蝶
//        this.loginKingDee(login);

        RequestApiBean requestApiBean = new RequestApiBean();
        requestApiBean.setFieldKeys(fieldKeys);
        requestApiBean.setFilterString(String.format(queryKey + " = '%s'", keyValue));
        requestApiBean.setFormId(interfaceOrderType);
        String billRes = KingDeeInvokeHelper.ExecuteBillQuery(null, JSONUtils.serializeObject(requestApiBean));
        JSONArray array = JSONArray.parseArray(billRes);
        if (CollectionUtil.isEmpty(array)) {
            throw new RemoteServiceException("单据无明细记录");
        }
        List<BillItem> billItems = new ArrayList<>();
        for (int i = 0; i < array.size(); i++) {
            String seqId = array.getJSONArray(i).getString(0);
            String entryId = array.getJSONArray(i).getString(1);
            String materialId = array.getJSONArray(i).getString(2);
            String supplyColVal = array.getJSONArray(i).getString(3);
            String parentId = "";
            if(array.getJSONArray(i).size() > 4) {
                if (Objects.nonNull(array.getJSONArray(i).get(4))) {
                    parentId = array.getJSONArray(i).getString(4);
                }
            }
            billItems.add(new BillItem(seqId, entryId, materialId, supplyColVal, parentId));
        }
        return billItems;
    }

    private void loginKingDee(boolean login) throws Exception {
        /**
         * 移到调用接口前判断是否需要登录
         */
        // 登录金蝶
//        if (login && !KingDeeInvokeHelper.Login(KingDeeUser.getDB(), KingDeeUser.getACCOUNT(), KingDeeUser.getPASSWORD(), KingDeeUser.getLANG())) {
//            throw new RemoteServiceException("登录金蝶失败");
//        }
    }


    /**
     * 批量同步订单
     * @param commonOrderBeans
     * @param interfaceOrderType
     * @return
     * @throws Exception
     */
    ResultBean syncBillDatabatch(List<SyncK3OtherReceBean> commonOrderBeans, String interfaceOrderType, boolean isUnAudit) throws Exception {
        // 登录金蝶
//        this.loginKingDee(true);

        if (isUnAudit) {
            // 先检查单据是否存在，存在执行删除
            for(CommonOrderBean commonOrderBean:commonOrderBeans){
                this.unAudit(queryBillNo, commonOrderBean.getBillNo(), interfaceOrderType);
            }
        }

        // 准备请求数据
        RequestBatchBillBean requestBean = new RequestBatchBillBean();
        if (null != commonOrderBeans && commonOrderBeans.get(0).isPushUpdate()) {
            requestBean.setNeedUpDateFields(commonOrderBeans.get(0).pushUpdateFields());
        }
        requestBean.setModel(commonOrderBeans);

        String res = KingDeeInvokeHelper.BatchSave(interfaceOrderType, JSONUtils.serializeObject(requestBean));
        ResultBean result = JSONObject.parseObject(res).getObject("Result", ResultBean.class);
        if (!result.getResponseStatus().isSuccess()) {
            throw new RemoteServiceException(result.getResponseStatus().getErrorInfo());
        }
        return result;
    }

    /**
     * 订单业务操作
     * @param bean
     * @param interfaceOrderType
     * @param type
     * @return
     * @throws Exception
     */
    void excuteOperation(RequestExcuteOperationBean bean, String interfaceOrderType, String type) throws Exception {
        // 发送请求
        String res = KingDeeInvokeHelper.ExcuteOperation(interfaceOrderType, JSONUtils.serializeObject(bean), type);
        ResultBean result = JSONObject.parseObject(res).getObject("Result", ResultBean.class);
        if (!result.getResponseStatus().isSuccess()) {
            throw new RemoteServiceException(result.getResponseStatus().getErrorInfo());
        }
    }


}
