package com.yem.em.utils;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import kd.bos.bill.OperationStatus;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.operate.result.IOperateInfo;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.ShowType;
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;

/**
 * @author 夜子
 * @ClassName CarShopUtils
 * @description: 购物车帮助类
 * @date 2023年07月25日
 * @version: 1.0
 */
public class CarShopUtils {
    /**
     * 添加购物车
     *
     * @param goods
     *            商品
     * @param qty
     *            数量
     * @param user
     *            用户
     * @return 成功条数
     */
    public static int insertCarShop(DynamicObject goods, BigDecimal qty, Long user, String orgId) {

        if (goods != null) {
            // 购物车
            DynamicObject shopcartbill = BusinessDataServiceHelper.loadSingle("tpv_pur_shopcartbill",
                    "id,tpv_goods.id,tpv_qty",
                    new QFilter[] { new QFilter("tpv_goods.id", QCP.equals, goods.getPkValue().toString()) });

            // 已存在购物车中
            if (shopcartbill != null) {
                BigDecimal orderqty = shopcartbill.getBigDecimal("tpv_qty");
                if (orderqty != null && qty != null) {
                    BigDecimal countqty = orderqty.add(qty);
                    shopcartbill.set("tpv_qty", countqty);
                    Object[] objects = SaveServiceHelper.save(new DynamicObject[] { shopcartbill });
                    return objects.length;
                }
            }
            // DynamicObject material = BusinessDataServiceHelper.loadSingle(goods,
            // "bd_material");
            MainEntityType type = EntityMetadataCache.getDataEntityType("tpv_pur_shopcartbill");
            DynamicObject carShop = new DynamicObject(type);
            // 物料
            carShop.set("tpv_goods", goods);
            // 数量
            carShop.set("tpv_qty", qty);
            // 图片
            carShop.set("tpv_goodsimg", goods.getString("tpv_picture"));
            // 用户
            carShop.set("tpv_user", user);
            carShop.set("tpv_goodsource", "2");
            // 单据状态
            carShop.set("tpv_billstatus", "A");
            if (EmptyUtils.isNotEmpty(orgId)) {
                DynamicObject org = BusinessDataServiceHelper.loadSingle(orgId, "bos_adminorg");
                carShop.set("tpv_org", org);
            }
            Object[] objects = SaveServiceHelper.save(new DynamicObject[] { carShop });
            return objects.length;
        }
        return 0;

    }

    /**
     * 购物车增加数量
     *
     * @param goods
     *            商品
     * @param qty
     *            数量
     * @param user
     *            用户
     * @return 成功条数
     */
    public static int addtCarShop(DynamicObject goods, BigDecimal qty, Long user) {

        if (goods != null) {
            // 购物车
            DynamicObject shopcartbill = BusinessDataServiceHelper.loadSingle("tpv_pur_shopcartbill",
                    "id,tpv_goods.id,tpv_qty",
                    new QFilter[] { new QFilter("tpv_goods.id", QCP.equals, goods.getPkValue().toString()) });

            // 已存在购物车中
            if (shopcartbill != null) {
                if (qty != null) {
                    shopcartbill.set("tpv_qty", qty);
                    Object[] objects = SaveServiceHelper.save(new DynamicObject[] { shopcartbill });
                    return objects.length;
                }
            }
        }
        return 0;

    }

    /**
     * 查询我的购物车
     *
     * @param user
     * @return
     */
    public static int SelectCarShop(Long user, String orgid) {
        int count = 0;
        if (user > 0) {
            QFilter qFilter = new QFilter("tpv_user", QCP.equals, user).and("tpv_org", QCP.equals, orgid);

            DynamicObject[] shopcartbill = BusinessDataServiceHelper.load("tpv_pur_shopcartbill", "id",
                    new QFilter[] { qFilter });
            if (shopcartbill.length > 0) {
                count = shopcartbill.length;
            }
        }
        return count;
    }

    /**
     * 获取操作返回错误信息
     *
     * @param operate
     *            操作对象
     * @return 错误信息
     */
    private static String getErrorMessage(OperationResult operate) {
        StringBuilder errInfos = new StringBuilder();
        for (IOperateInfo errInfo : operate.getAllErrorOrValidateInfo()) {
            String detailMessage = errInfo.getMessage();
            errInfos.append(detailMessage).append("\r\n");
        }
        if (errInfos.length() == 0) {
            errInfos.append(operate.getMessage());
        }
        return errInfos.toString();
    }

    /**
     *
     * 删除购物车中的商品
     *
     * @param bills
     */
    public static String deleteCarShop(Object[] bills) {
        OperationResult deleteOperate = OperationServiceHelper.executeOperate("delete", "tpv_pur_shopcartbill", bills,
                OperateOption.create());
        if (deleteOperate.isSuccess()) {
            return "success";
        }
        return getErrorMessage(deleteOperate);

    }

    /**
     * 我的常购
     *
     * @param materialIds
     *            物料id 集合
     * @param userId
     *            当前用户
     * @return 成功条数
     */
    public static int myOftenBuy(List<Map<String, Object>> materialIds, Long userId) {
        boolean flag = false;
        Object[] objects = null;
        if (materialIds != null && materialIds.size() > 0) {
            for (Map<String, Object> materialId : materialIds) {
                // 购物车
                DynamicObject myOftenBuybill = BusinessDataServiceHelper.loadSingle("tpv_pur_oftenbuybill",
                        "id,tpv_goods.id", new QFilter[] { new QFilter("tpv_goods.id", QCP.equals, materialId) });
                if (myOftenBuybill != null) {
                    flag = true;
                } else {
                    MainEntityType type = EntityMetadataCache.getDataEntityType("tpv_pur_oftenbuybill");
                    DynamicObject oftenBuy = new DynamicObject(type);
                    // 物料
                    oftenBuy.set("tpv_goods", materialId.get("goodsId"));
                    // 用户
                    oftenBuy.set("tpv_user", userId);
                    // 单据状态
                    oftenBuy.set("tpv_billstatus", "A");
                    oftenBuy.set("tpv_org", materialId.get("orgId"));
                    objects = SaveServiceHelper.save(new DynamicObject[] { oftenBuy });
                }

            }
        }

        if (objects != null) {
            return objects.length;
        }
        if (flag) {
            return 0;
        }

        return 0;
    }

    /**
     *
     * 删除我的常购
     *
     * @param bills
     */
    public static String deleteOftenBuy(Object[] bills) {
        OperationResult deleteOperate = OperationServiceHelper.executeOperate("delete", "tpv_pur_oftenbuybill", bills,
                OperateOption.create());
        if (deleteOperate.isSuccess()) {
            return "success";
        }
        return getErrorMessage(deleteOperate);
    }

    /**
     * 跳转购物车
     *
     * @param view
     *            视图对象
     * @param formKey
     *            要弹出的单据标识
     * @param param
     *            区分购物和常用key
     */
    public static void showCarShop(IFormView view, String formKey, String param) {
        FormShowParameter showParameter = new FormShowParameter();
        showParameter.setStatus(OperationStatus.ADDNEW);
        showParameter.getOpenStyle().setShowType(ShowType.MainNewTabPage);
        showParameter.setCustomParam("billkey", param);
        showParameter.setFormId(formKey);
        view.showForm(showParameter);
    }
}