package com.fs.erp.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fs.common.utils.StringUtils;
import com.fs.erp.domain.ErpOrder;
import com.fs.erp.domain.ErpRefundOrder;
import com.fs.erp.dto.*;
import com.fs.erp.dto.sdk.HzOMS.api.HzOMSClient;
import com.fs.erp.service.IErpOrderService;

import com.fs.his.domain.*;
import com.fs.his.service.*;
import com.fs.his.utils.PhoneUtil;
import com.fs.hisStore.domain.FsStoreOrderScrm;
import com.fs.hisStore.domain.FsStoreProductAttrValueScrm;
import com.fs.hisStore.domain.FsStoreProductScrm;
import com.fs.hisStore.service.IFsStoreProductAttrValueScrmService;
import com.fs.hisStore.service.IFsStoreProductScrmService;
import com.fs.live.domain.LiveOrder;
import com.fs.live.domain.LiveOrderItem;
import com.fs.live.mapper.LiveOrderItemMapper;
import com.fs.live.mapper.LiveOrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 瀚智OMS EPR订单对接服务实现类
 */
@Slf4j
@Service
public class HzOMSErpOrderServiceImpl implements IErpOrderService {

    @Autowired
    private IFsStoreOrderService fsStoreOrderService;

    @Autowired
    private IFsStoreOrderItemService fsStoreOrderItemService;

    @Autowired
    private IFsStoreProductService fsStoreProductService;

    @Autowired
    private IFsStoreProductAttrValueService fsStoreProductAttrValueService;

    @Autowired
    private IFsStoreAfterSalesService fsStoreAfterSalesService;

    @Autowired
    private IFsStoreService fsStoreService;

    @Autowired
    HzOMSClient hzOMSClient;

    @Autowired
    private LiveOrderMapper liveOrderMapper;

    @Autowired
    private LiveOrderItemMapper liveOrderItemMapper;

    @Autowired
    private IFsStoreProductScrmService fsStoreProductScrmService;

    @Autowired
    private IFsStoreProductAttrValueScrmService fsStoreProductAttrValueScrmService;

    @Override
    public ErpOrderResponse addOrder(ErpOrder order) {
        try {
            JSONObject hzOrder = buildHzOMSOrder(order.getPlatform_code());

            JSONObject omsOpenPtorderCreate = hzOMSClient.send("oms_open_ptorder_create", hzOrder);
            ErpOrderResponse res = new ErpOrderResponse();
            res.setCode("hzomssuccess");
            return res;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    @Override
    public ErpOrderResponse addOrderScrm(ErpOrder order) {
        return addOrder( order);
    }

    @Override
    public ErpOrderResponse addLiveOrder(ErpOrder order) {
        try {
            JSONObject hzOrder = buildHzOMSOrderLive(order.getPlatform_code());

            JSONObject omsOpenPtorderCreate = hzOMSClient.send("oms_open_ptorder_create", hzOrder);
            ErpOrderResponse res = new ErpOrderResponse();
            res.setCode("hzomssuccess");
            return res;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    private JSONObject buildHzOMSOrderLive(String orderCode) {
        //通过订单号查询更多订单信息
        LiveOrder liveOrder = liveOrderMapper.selectLiveOrderByOrderCode(orderCode);
        FsStore fsStore = fsStoreService.selectFsStoreByStoreId(liveOrder.getStoreId());

        JSONObject obj = new JSONObject();
        String iordertype = "2"; // 直播订单默认B2C快递配送
        //订单类型 0 O2O配送订单; 1 O2O 自提订单; 2 B2C 快递配送
        obj.put("iordertype", iordertype);
        //订单单号
        obj.put("cptordercode", liveOrder.getOrderCode());
        //平台店铺编码 todo 测试环境只能写死 110111 用于联调测试 liveOrder.getStoreId()
        obj.put("cptshopcode", 110111);
        //平台店铺名称
        obj.put("cptshopname", fsStore.getStoreName());
        Integer iorderstatus = null;
        //自提且已经支付
        if ("1".equals(iordertype) && Integer.valueOf(1).equals(liveOrder.getIsPay())) {
            iorderstatus = 30;
        } else {
            if (Integer.valueOf(1).equals(liveOrder.getStatus())) {
                iorderstatus = 0;
            } else if (Integer.valueOf(2).equals(liveOrder.getStatus())) {
                iorderstatus = 5;
            }
        }
        //订单状态 0待接单 5待拣货 10待配送 15配送中 20已完成 25已取消 30待自提
        obj.put("iorderstatus", iorderstatus);

        String userAddress = liveOrder.getUserAddress();
        String[] s = null;
        if (StringUtils.isNotBlank(userAddress)) {
            s = userAddress.split(" ");
        } else {
            throw new RuntimeException("用户收货地址有问题");
        }

        //收货省
        obj.put("cprovince", s[0]);
        //收货市
        obj.put("ccity", s[1]);
        //收货区
        obj.put("carea", s[2]);
        //收货人密文 无密文填写明文
        obj.put("creceivers", liveOrder.getRealName());
        //收货人联系电话密文 无密文填写明文
        obj.put("creceiversphone", liveOrder.getUserPhone());
        //收货人详细地址密文 无密文填写明文
        obj.put("creceiversaddress", userAddress);
        //收货人脱敏信息
        obj.put("cdesenreceivers", liveOrder.getRealName());
        //收货联系电话脱敏信息
        obj.put("cdesenreceiversphone", PhoneUtil.decryptPhone(liveOrder.getUserPhone()));
        //收货联系地址脱敏信息
        obj.put("cdesenreceiversaddress", userAddress);
        //订单总金额 单位元
        obj.put("forderamount", liveOrder.getTotalPrice());
        //支付金额 单位元
        obj.put("fpayamount", liveOrder.getPayPrice());
        //订单总优惠 单位元
        obj.put("fdiscamount", liveOrder.getDiscountMoney());
        //运费
        obj.put("ffreight", liveOrder.getPayDelivery());
        //下单时间 格式 yyyy-MM-dd hh:mm:ss 如：2025-01-01 00:11:22
        obj.put("dorderstarttime", liveOrder.getCreateTime());
        //是否处方 0 否 1 是 可选
        obj.put("iisprescription", 0);
        //买家备注
        obj.put("corderremark", liveOrder.getRemark());
        //支付时间  格式 yyyy-MM-dd hh:mm:ss 如：2025-01-01 00:11:22
        obj.put("dpurchasetime", liveOrder.getPayTime());
        List<LiveOrderItem> liveOrderItems = liveOrderItemMapper.selectLiveOrderItemByOrderId(liveOrder.getOrderId());
        int totalOrderItemCount = liveOrderItems.size();
        BigDecimal divide = liveOrder.getDiscountMoney().divide(BigDecimal.valueOf(totalOrderItemCount), 2, BigDecimal.ROUND_HALF_UP);
        JSONArray goodArr = new JSONArray();

        liveOrderItems.forEach(liveOrderItem -> {
            JSONObject goodItem = new JSONObject();
            //商品编码
            goodItem.put("cptgoodsid", liveOrderItem.getProductId());
            //商品规格编码
            goodItem.put("cptspeccode", liveOrderItem.getProductAttrValueId());

            FsStoreProductScrm fsStoreProduct = fsStoreProductScrmService.selectFsStoreProductById(liveOrderItem.getProductId());
            FsStoreProductAttrValueScrm fsStoreProductAttrValue = new FsStoreProductAttrValueScrm();
            //判断是否含有商品规格信息 有则查询商品规格信息 没有取商品的价格
            if(null != liveOrderItem.getProductAttrValueId()){
                fsStoreProductAttrValue = fsStoreProductAttrValueScrmService.selectFsStoreProductAttrValueById(liveOrderItem.getProductAttrValueId());
            }else{
                fsStoreProductAttrValue.setPrice(fsStoreProduct.getPrice());
            }
            //商品名称
            goodItem.put("cgoodsname", fsStoreProduct.getProductName());
            //购买数量
            goodItem.put("fqty", liveOrderItem.getNum());
            //原单价
            goodItem.put("fnormprice", fsStoreProductAttrValue.getPrice());

            //实售单价 优惠后的单价 单位元
            goodItem.put("fprice", fsStoreProductAttrValue.getPrice().subtract(divide));
            goodArr.add(goodItem);
        });
        //订单商品信息
        obj.put("ptorder_goods_list", goodArr);

        return obj;
    }

    @Override
    public ErpOrderResponse refundOrder(ErpRefundOrder order) {
        String orderCode = order.getOrderCode();
        Long storeAfterSalesId = order.getAfterSalesId();
        JSONObject jsonObject = buildRefundOrder(orderCode, storeAfterSalesId);
        JSONObject omsOpenPtreturnorderCreate = hzOMSClient.send("oms_open_ptreturnorder_create", jsonObject);
        return null;
    }

    @Override
    public ErpOrderResponse refundOrderScrm(ErpRefundOrder order) {
        return null;
    }

    @Override
    public ErpOrderResponse refundLiveOrder(ErpRefundOrder order) {
        return null;
    }

    @Override
    public ErpDeliverysResponse getDeliver(ErpDeliverysRequest param) {
        return null;
    }

    @Override
    public ErpOrderQueryResponse getOrder(ErpOrderQueryRequert param) {
        return null;
    }

    @Override
    public ErpOrderQueryResponse getScrmOrder(ErpOrderQueryRequert param) {
        return null;
    }

    @Override
    public ErpOrderQueryResponse getLiveOrder(ErpOrderQueryRequert param) {
        return null;
    }

    @Override
    public BaseResponse refundUpdate(ErpRefundUpdateRequest param) {

        String orderCode = param.getTid();
        Long storeAfterSalesId = param.getStoreAfterSalesId();
        FsStoreAfterSales fsStoreAfterSales = fsStoreAfterSalesService.selectFsStoreAfterSalesById(storeAfterSalesId);

        FsStoreOrder fsStoreOrder = fsStoreOrderService.selectFsStoreOrderByOrderCode(orderCode);

        JSONObject jsonObject = new JSONObject();
        //平台店铺编码 todo 测试环境只能写死 110111 用于联调测试 fsStoreOrder.getStoreId()
        jsonObject.put("cptshopcode", 110111);
        //平台订单号
        jsonObject.put("cptordercode", orderCode);
        //平台售后单号
        jsonObject.put("cptretruncode", fsStoreAfterSales.getId());
        //申请退款金额
        jsonObject.put("frefundamt", fsStoreAfterSales.getRefundAmount());

        Integer iaftersalesstatus = null;
        //退货退款
        if (Integer.valueOf(1).equals(fsStoreAfterSales.getRefundType())) {
            if (fsStoreAfterSales.getSalesStatus().equals(1)) {
                //用户取消申请
                iaftersalesstatus = 30;
            } else if (fsStoreAfterSales.getSalesStatus().equals(2)) {
                //商家拒绝
                iaftersalesstatus = 50;
            } else if (fsStoreAfterSales.getSalesStatus().equals(3) && fsStoreAfterSales.getStatus().equals(4)) {
                //已完成&&退款成功
                iaftersalesstatus = 60;
            } else {
                //售后中
                //售后中对应erp依然是申请阶段不需要做任何操作
                BaseResponse baseResponse = new BaseResponse();
                baseResponse.setSuccess(true);
                return baseResponse;
            }
        } else if (Integer.valueOf(0).equals(fsStoreAfterSales.getRefundType())) {
            if (fsStoreAfterSales.getSalesStatus().equals(1)) {
                //用户取消申请
                iaftersalesstatus = 30;
            } else if (fsStoreAfterSales.getSalesStatus().equals(2)) {
                //商家拒绝
                iaftersalesstatus = 35;
            } else if (fsStoreAfterSales.getSalesStatus().equals(3) && fsStoreAfterSales.getStatus().equals(4)) {
                //已完成&&退款成功
                iaftersalesstatus = 25;
            } else {
                //售后中
                //售后中对应erp依然是申请阶段不需要做任何操作
                BaseResponse baseResponse = new BaseResponse();
                baseResponse.setSuccess(true);
                return baseResponse;
            }
        }
        //售后状态 10 申请部分退款;15 申请全额退款;25 同意退款;30 取消申请;35 驳回退款;40 申请退货退款;45 同意退货退款;50 驳回退货退款;55 退货成功;60 退款成功
        jsonObject.put("iaftersalesstatus", iaftersalesstatus);
        JSONObject omsOpenPtreturnorderStatuschange = hzOMSClient.send("oms_open_ptreturnorder_statuschange", jsonObject);
        BaseResponse res = new BaseResponse();
        res.setSuccess(true);
        return res;
    }

    @Override
    public BaseResponse refundUpdateScrm(ErpRefundUpdateRequest param) {
        return null;
    }

    @Override
    public BaseResponse refundUpdateLive(ErpRefundUpdateRequest param) {
        return null;
    }

    @Override
    public ErpOrderResponse finishOrder(ErpOrder order) {
        return null;
    }

    @Override
    public void getOrderDeliveryStatus(FsStoreOrder order) {

    }

    @Override
    public void getOrderScrmDeliveryStatus(FsStoreOrderScrm order) {

    }

    @Override
    public void getOrderLiveDeliveryStatus(LiveOrder order) {

    }

    /**
     * 构建瀚智创建订单参数
     *
     * @param orderCode
     * @return
     */
    private JSONObject buildHzOMSOrder(String orderCode) {
        //通过订单号查询更多订单信息
        FsStoreOrder fsOrder = fsStoreOrderService.selectFsStoreOrderByOrderCode(orderCode);
        FsStore fsStore = fsStoreService.selectFsStoreByStoreId(fsOrder.getStoreId());

        JSONObject obj = new JSONObject();
        String iordertype = "";
        if (Integer.valueOf(1).equals(fsOrder.getShippingType())) {
            iordertype = "2";
        } else if (Integer.valueOf(2).equals(fsOrder.getShippingType())) {
            iordertype = "1";
        }
        //订单类型 0 O2O配送订单; 1 O2O 自提订单; 2 B2C 快递配送
        obj.put("iordertype", iordertype);
        //订单单号
        obj.put("cptordercode", fsOrder.getOrderCode());
        //平台店铺编码 todo 测试环境只能写死 110111 用于联调测试 fsOrder.getStoreId()
        obj.put("cptshopcode", 110111);
        //平台店铺名称
        obj.put("cptshopname", fsStore.getStoreName());
        Integer iorderstatus = null;
        //自提且已经支付
        if ("1".equals(iordertype) && Integer.valueOf(1).equals(fsOrder.getIsPay())) {
            iorderstatus = 30;
        } else {
            if (Integer.valueOf(1).equals(fsOrder.getStatus())) {
                iorderstatus = 0;
            } else if (Integer.valueOf(2).equals(fsOrder.getStatus())) {
                iorderstatus = 5;
            }
        }
        //订单状态 0待接单 5待拣货 10待配送 15配送中 20已完成 25已取消 30待自提
        obj.put("iorderstatus", iorderstatus);

        String userAddress = fsOrder.getUserAddress();
        String[] s = null;
        if (StringUtils.isNotBlank(userAddress)) {
            s = userAddress.split(" ");
        } else {
            throw new RuntimeException("用户收货地址有问题");
        }

        //收货省
        obj.put("cprovince", s[0]);
        //收货市
        obj.put("ccity", s[1]);
        //收货区
        obj.put("carea", s[2]);
        //收货城镇乡 f
//        obj.put("ctown", "");
        //收货人密文 无密文填写明文
        obj.put("creceivers", fsOrder.getUserName());
        //收货人联系电话密文 无密文填写明文
        obj.put("creceiversphone", fsOrder.getUserPhone());
        //收货人详细地址密文 无密文填写明文
        obj.put("creceiversaddress", userAddress);
        //收货人脱敏信息
        obj.put("cdesenreceivers", fsOrder.getUserName());
        //收货联系电话脱敏信息
        obj.put("cdesenreceiversphone", PhoneUtil.decryptPhone(fsOrder.getUserPhone()));
        //收货联系地址脱敏信息
        obj.put("cdesenreceiversaddress", userAddress);
        //订单总金额 单位元
        obj.put("forderamount", fsOrder.getTotalPrice());
        //支付金额 单位元
        obj.put("fpayamount", fsOrder.getPayPrice());
        //订单总优惠 单位元 f
        obj.put("fdiscamount", fsOrder.getDiscountMoney());
        //商家优惠 f
//        obj.put("fpoidisc", "");
        //平台优惠 f
//        obj.put("fplatformdisc", "");
        //运费优惠 f
//        obj.put("ffreightdiscount", "");
        //运费 f
        obj.put("ffreight", fsOrder.getDeliveryPayMoney());
        //下单时间 格式 yyyy-MM-dd hh:mm:ss 如：2025-01-01 00:11:22
        obj.put("dorderstarttime", fsOrder.getCreateTime());
        //是否处方 0 否 1 是 可选
        obj.put("iisprescription", fsOrder.getIsPrescribe());
        //买家备注 f
        obj.put("corderremark", fsOrder.getRemark());
        //商家备注 f
//        obj.put("csellermessage", "");
        //自提订单自提码 f
//        obj.put("ctakecode", "");
        //订单旗帜 1 红 2 黄 3 绿 4 蓝 5 紫 f
//        obj.put("corderflag", "");
        //支付时间  格式 yyyy-MM-dd hh:mm:ss 如：2025-01-01 00:11:22 f
        obj.put("dpurchasetime", fsOrder.getPayTime());
        //预计送达时间 格式 yyyy-MM-dd hh:mm:ss 如：2025-01-01 00:11:22 f
//        obj.put("dpredeliverytime", "");
        //实际送达时间  格式 yyyy-MM-dd hh:mm:ss 如：2025-01-01 00:11:22 f
//        obj.put("dconfirmtime", "");
        List<FsStoreOrderItem> fsStoreOrderItems = fsStoreOrderItemService.selectFsStoreOrderItemListByOrderId(fsOrder.getOrderId());
        int totalOrderItemCount = fsStoreOrderItems.size();
        BigDecimal divide = fsOrder.getDiscountMoney().divide(BigDecimal.valueOf(totalOrderItemCount), 2, BigDecimal.ROUND_HALF_UP);
        JSONArray goodArr = new JSONArray();

        fsStoreOrderItems.forEach(fsStoreOrderItem -> {
            JSONObject goodItem = new JSONObject();
            //商品编码
            goodItem.put("cptgoodsid", fsStoreOrderItem.getProductId());
            //商品规格编码 f
            goodItem.put("cptspeccode", fsStoreOrderItem.getProductAttrValueId());

            FsStoreProduct fsStoreProduct = fsStoreProductService.selectFsStoreProductById(fsStoreOrderItem.getProductId());
            FsStoreProductAttrValue fsStoreProductAttrValue = new FsStoreProductAttrValue();
            //判断是否含有商品规格信息 有则查询商品规格信息 没有取商品的价格
            if(null != fsStoreOrderItem.getProductAttrValueId()){
                fsStoreProductAttrValue = fsStoreProductAttrValueService.selectFsStoreProductAttrValueById(fsStoreOrderItem.getProductAttrValueId());
            }else{
                fsStoreProductAttrValue.setPrice(fsStoreProduct.getPrice());
            }
            //商品名称
            goodItem.put("cgoodsname", fsStoreProduct.getProductName());
            //商品规格名称 f
//            goodItem.put("cspecname", );
            //购买数量
            goodItem.put("fqty", fsStoreOrderItem.getNum());
            //原单价
            goodItem.put("fnormprice", fsStoreProductAttrValue.getPrice());

            //实售单价 优惠后的单价 单位元
            goodItem.put("fprice", fsStoreProductAttrValue.getPrice().subtract(divide));
            //商品优惠金额 f
//            goodItem.put("fdiscprice", new BigDecimal(0));
            //商品条码 f
//            goodItem.put("cbarcode", "");
            goodArr.add(goodItem);
        });
        //订单商品信息
        obj.put("ptorder_goods_list", goodArr);

        return obj;
    }

    /**
     * 构建申请售后订单参数
     *
     * @param orderCode
     * @return
     */
    private JSONObject buildRefundOrder(String orderCode, Long storeAfterSalesId) {
        //通过订单号查询更多订单信息
        FsStoreOrder fsOrder = fsStoreOrderService.selectFsStoreOrderByOrderCode(orderCode);

        Long orderId = fsOrder.getOrderId();
        FsStoreAfterSales fsStoreAfterSales = fsStoreAfterSalesService.selectFsStoreAfterSalesById(storeAfterSalesId);

        JSONObject obj = new JSONObject();
        //平台店铺编码 todo 测试环境只能写死 110111 用于联调测试 fsStoreAfterSales.getStoreId()
        obj.put("cptshopcode", 110111);
        //平台订单号
        obj.put("cptordercode", orderCode);
        //平台售后单号
        obj.put("cptretruncode", fsStoreAfterSales.getId());
        Integer iretruntype = null;
        if (Integer.valueOf(0).equals(fsStoreAfterSales.getRefundType())) {
            iretruntype = 5;
        } else if (Integer.valueOf(1).equals(fsStoreAfterSales.getRefundType())) {
            iretruntype = 1;
        }
        //售后类型 1 退货退款 5 仅退款
        obj.put("iretruntype", iretruntype);
        //申请类型 0 部分退款 1 全部退款
        obj.put("iservicetype", Integer.valueOf(1));
        Integer iaftersalesstatus = null;
        //退货退款
        if (iretruntype.equals(1)) {
            if (fsStoreAfterSales.getStatus().equals(0)) {
                //申请退货退款
                iaftersalesstatus = 40;
            }
        } else if (iretruntype.equals(5)) {
            if (fsStoreAfterSales.getStatus().equals(0)) {
                //申请全额退款
                iaftersalesstatus = 15;
            }
        }

        //售后状态10 申请部分退款;15 申请全额退款 25 同意退款 30 取消申请 35 驳回退款申请 40 申请退货退款 45 同意退货退款 50 驳回退货退款申请 55 退货成功 60 退款成功
        obj.put("iaftersalesstatus", iaftersalesstatus);
        //申请退款金额
        obj.put("frefundamt", fsStoreAfterSales.getRefundAmount());
        //申请原因 f
        obj.put("creason", fsStoreAfterSales.getReasons());
        //售后图片url地址 f
        obj.put("cimgurl", fsStoreAfterSales.getExplainImg());

        JSONArray goodsList = new JSONArray();

        List<FsStoreOrderItem> fsStoreOrderItems = fsStoreOrderItemService.selectFsStoreOrderItemListByOrderId(fsOrder.getOrderId());
        int totalOrderItemCount = fsStoreOrderItems.size();
        BigDecimal divide = fsOrder.getDiscountMoney().divide(BigDecimal.valueOf(totalOrderItemCount), 2, BigDecimal.ROUND_HALF_UP);
        fsStoreOrderItems.forEach(fsStoreOrderItem -> {
            JSONObject goodItem = new JSONObject();
            //商品编码
            goodItem.put("cptgoodsid", fsStoreOrderItem.getProductId());
            //商品规格编码 f
            goodItem.put("cptspeccode", fsStoreOrderItem.getProductAttrValueId());

            FsStoreProduct fsStoreProduct = fsStoreProductService.selectFsStoreProductById(fsStoreOrderItem.getProductId());
            FsStoreProductAttrValue fsStoreProductAttrValue = fsStoreProductAttrValueService.selectFsStoreProductAttrValueById(fsStoreOrderItem.getProductAttrValueId());
            //商品名称
            goodItem.put("cgoodsname", fsStoreProduct.getProductName());
            //商品规格名称 f
//            goodItem.put("cspecname", );
            //本次申请数量
            goodItem.put("fqty", fsStoreOrderItem.getNum());
            //原单价
            goodItem.put("fnormprice", fsStoreProductAttrValue.getPrice());
            //本次申请退款单价 单位元
            goodItem.put("fprice", fsStoreProductAttrValue.getPrice().subtract(divide));

            goodsList.add(goodItem);
        });
        //售后商品信息
        obj.put("ptreturnorder_goods_list", goodsList);

        return obj;
    }

}
