package com.fs.hisStore.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.fs.common.core.domain.R;
import com.fs.common.utils.StringUtils;
import com.fs.hisStore.domain.FsStoreAfterSalesItemScrm;
import com.fs.hisStore.domain.FsStoreAfterSalesScrm;
import com.fs.hisStore.enums.OrderInfoEnum;
import com.fs.hisStore.mapper.MergedOrderMapper;
import com.fs.hisStore.param.*;
import com.fs.hisStore.service.IFsStoreAfterSalesItemScrmService;
import com.fs.hisStore.service.IFsStoreAfterSalesScrmService;
import com.fs.hisStore.service.IFsStoreOrderScrmService;
import com.fs.hisStore.service.IMergedOrderService;
import com.fs.hisStore.vo.FsMergedOrderListQueryVO;
import com.fs.hisStore.vo.FsStoreOrderItemVO;
import com.fs.hisStore.vo.MergedAfterSalesVO;
import com.fs.live.domain.LiveAfterSales;
import com.fs.live.domain.LiveAfterSalesItem;
import com.fs.live.param.LiveAfterSalesDeliveryParam;
import com.fs.live.param.LiveAfterSalesParam;
import com.fs.live.param.LiveAfterSalesRevokeParam;
import com.fs.live.param.MergedOrderQueryParam;
import com.fs.live.service.ILiveAfterSalesItemService;
import com.fs.live.service.ILiveAfterSalesService;
import com.fs.live.service.ILiveOrderService;
import com.fs.live.vo.MergedOrderVO;
import com.fs.store.config.StoreConfig;
import com.fs.system.service.ISysConfigService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.*;

/**
 * 合并订单Service实现类
 *
 * @author fs
 * @date 2025-01-XX
 */
@Service
public class MergedOrderServiceImpl implements IMergedOrderService
{
    @Autowired
    private MergedOrderMapper mergedOrderMapper;

    /*
     * 后端合并
     * 根据订单类型筛选，选择不同的查询方式：
     * - orderTypeFilter = 1: 只查询销售订单
     * - orderTypeFilter = 2: 只查询商城订单
     * - orderTypeFilter = 3: 只查询直播订单
     * - orderTypeFilter = null: 使用视图查询全部订单
     * */
    @Override
    public List<MergedOrderVO> selectMergedOrderList(MergedOrderQueryParam param)
    {
        List<MergedOrderVO> list;

        // 根据订单类型筛选选择不同的查询方式
        if (param.getOrderTypeFilter() != null) {
            // 选择单个订单类型，只查询对应的表
            if (param.getOrderTypeFilter() == 1) {
                // 销售订单
                list = mergedOrderMapper.selectSalesOrderList(param);
            } else if (param.getOrderTypeFilter() == 2) {
                // 商城订单
                list = mergedOrderMapper.selectStoreOrderList(param);
            } else if (param.getOrderTypeFilter() == 3) {
                // 直播订单
                list = mergedOrderMapper.selectLiveOrderList(param);
            } else {
                // 未知类型，使用视图查询
                list = mergedOrderMapper.selectMergedOrderList(param);
            }
        } else {
            // 全部订单，使用视图查询优化性能
            list = mergedOrderMapper.selectMergedOrderList(param);
        }

        // 处理商品JSON
        for (MergedOrderVO vo : list)
        {
            if (StringUtils.isNotEmpty(vo.getItemJson()))
            {
                try
                {
                    JSONArray jsonArray = JSONUtil.parseArray(vo.getItemJson());
                    if (jsonArray != null && jsonArray.size() > 0)
                    {
                        vo.setItems(jsonArray);
                    }
                }
                catch (Exception e)
                {
                    // JSON解析失败，忽略
                }
            }
        }

        return list;
    }

    /**
     * 统计合并订单总数
     */
    @Override
    public long countMergedOrderList(MergedOrderQueryParam param)
    {
        return mergedOrderMapper.countMergedOrderList(param);
    }


    @Autowired
    private ISysConfigService configService;

    @Autowired
    private IFsStoreAfterSalesScrmService storeAfterSalesService;

    @Autowired
    private ILiveAfterSalesService liveAfterSalesService;

    @Autowired
    private IFsStoreOrderScrmService storeOrderService;

    @Autowired
    private ILiveOrderService liveOrderService;

    @Autowired
    private IFsStoreAfterSalesItemScrmService storeAfterSalesItemService;

    @Autowired
    private ILiveAfterSalesItemService liveAfterSalesItemService;

    /*
     * 小程序合并
     * */
    @Override
    public List<FsMergedOrderListQueryVO> selectMergedOrderListVO(FsMyStoreOrderQueryParam param)
    {
        List<FsMergedOrderListQueryVO> list = mergedOrderMapper.selectMergedOrderListVO(param);

        for (FsMergedOrderListQueryVO vo : list)
        {

            // 处理商品JSON
            if (StringUtils.isNotEmpty(vo.getItemJson()))
            {
                List<FsStoreOrderItemVO> items = new ArrayList<>();
                if (2 == vo.getOrderType()) {
                    FsStoreOrderItemVO bean = JSONUtil.toBean(vo.getItemJson(), FsStoreOrderItemVO.class);
                    items.add(bean);
                    vo.setItems(items);
                }else {
                    JSONArray jsonArray = JSONUtil.parseArray(vo.getItemJson());
                    items = JSONUtil.toList(jsonArray, FsStoreOrderItemVO.class);
                    if (items != null && items.size() > 0)
                    {
                        vo.setItems(items);
                    }
                }


            }

            // 处理是否可以申请售后
            vo.setIsAfterSales(0);
            if (vo.getStatus() != null && vo.getStatus().equals(OrderInfoEnum.STATUS_3.getValue()))
            {
                // 已完成订单
                vo.setIsAfterSales(1);
                if (vo.getFinishTime() != null)
                {
                    String json = configService.selectConfigByKey("his.store");
                    if (StringUtils.isNotEmpty(json))
                    {
                        StoreConfig storeConfig = JSONUtil.toBean(json, StoreConfig.class);
                        if (storeConfig != null && storeConfig.getStoreAfterSalesDay() != null && storeConfig.getStoreAfterSalesDay() > 0)
                        {
                            // 判断完成时间是否超过指定时间
                            Calendar calendar = new GregorianCalendar();
                            calendar.setTime(vo.getFinishTime());
                            calendar.add(Calendar.DATE, storeConfig.getStoreAfterSalesDay());
                            if (calendar.getTime().getTime() < new Date().getTime())
                            {
                                vo.setIsAfterSales(0);
                            }
                        }
                    }
                }
            }
            else if (vo.getStatus() != null && (vo.getStatus() == 1 || vo.getStatus() == 2))
            {
                vo.setIsAfterSales(1);
            }
        }

        return list;
    }

    @Override
    public List<MergedAfterSalesVO> selectMergedAfterSalesList(MergedAfterSalesQueryParam param) {
        List<MergedAfterSalesVO> list = mergedOrderMapper.selectMergedAfterSalesList(param);

        // 填充售后商品列表
        for (MergedAfterSalesVO vo : list) {
            if (vo.getAfterSalesType() != null && vo.getAfterSalesType() == 1) {
                // 商城售后
                FsStoreAfterSalesItemScrm itemParam = new FsStoreAfterSalesItemScrm();
                itemParam.setStoreAfterSalesId(vo.getId());
                List<FsStoreAfterSalesItemScrm> items = storeAfterSalesItemService.selectFsStoreAfterSalesItemList(itemParam);
                vo.setItems(items);
            } else if (vo.getAfterSalesType() != null && vo.getAfterSalesType() == 2) {
                // 直播售后
                List<LiveAfterSalesItem> items = liveAfterSalesItemService.selectLiveAfterSalesItemByAfterId(vo.getId());
                vo.setItems(items);
            }
        }

        return list;
    }

    @Override
    public R applyForAfterSales(String userId, MergedAfterSalesParam param) {
        // 根据订单号判断是商城订单还是直播订单
        try {
            // 先尝试查询商城订单
            com.fs.hisStore.domain.FsStoreOrderScrm storeOrder = storeOrderService.selectFsStoreOrderByOrderCode(param.getOrderCode());
            if (storeOrder != null) {
                // 商城订单，调用商城售后服务
                FsStoreAfterSalesParam storeParam = new FsStoreAfterSalesParam();
                BeanUtils.copyProperties(param, storeParam);
                return storeAfterSalesService.applyForAfterSales(Long.parseLong(userId), storeParam);
            }
        } catch (Exception e) {
            // 商城订单不存在，继续尝试直播订单
        }

        // 尝试查询直播订单
        com.fs.live.domain.LiveOrder liveOrder = liveOrderService.selectLiveOrderByOrderCode(param.getOrderCode());
        if (liveOrder != null) {
            // 直播订单，调用直播售后服务
            LiveAfterSalesParam liveParam = new LiveAfterSalesParam();
            liveParam.setOrderCode(param.getOrderCode());
            liveParam.setServiceType(param.getServiceType());
            liveParam.setReasons(param.getReasons());
            liveParam.setExplains(param.getExplains());
            liveParam.setExplainImg(param.getExplainImg());
            liveParam.setRefundAmount(param.getRefundAmount());
            // 转换商品列表
            if (param.getProductList() != null) {
                List<com.fs.live.param.LiveAfterSalesProductParam> liveProductList = new ArrayList<>();
                for (FsStoreAfterSalesProductParam product : param.getProductList()) {
                    com.fs.live.param.LiveAfterSalesProductParam liveProduct = new com.fs.live.param.LiveAfterSalesProductParam();
                    liveProduct.setProductId(product.getProductId());
                    liveProduct.setNum(product.getNum());
                    liveProductList.add(liveProduct);
                }
                liveParam.setProductList(liveProductList);
            }
            return liveAfterSalesService.applyForAfterSales(userId, liveParam);
        }

        return R.error("订单不存在");
    }

    @Override
    public R revokeAfterSales(String userId, MergedAfterSalesRevokeParam param) throws ParseException {
        if (param.getAfterSalesType() != null && param.getAfterSalesType() == 1) {
            // 商城售后
            return storeAfterSalesService.revoke(Long.parseLong(userId), param.getSalesId());
        } else if (param.getAfterSalesType() != null && param.getAfterSalesType() == 2) {
            // 直播售后
            LiveAfterSalesRevokeParam liveParam = new LiveAfterSalesRevokeParam();
            liveParam.setId(param.getSalesId());
            return liveAfterSalesService.revoke(userId, liveParam);
        }
        return R.error("售后类型错误");
    }

    @Override
    public R addDelivery(MergedAfterSalesDeliveryParam param) {
        if (param.getAfterSalesType() != null && param.getAfterSalesType() == 1) {
            // 商城售后
            FsStoreAfterSalesDeliveryParam storeParam = new FsStoreAfterSalesDeliveryParam();
            storeParam.setUserId(param.getUserId());
            storeParam.setSalesId(param.getSalesId());
            storeParam.setDeliverySn(param.getDeliverySn());
            storeParam.setDeliveryName(param.getDeliveryName());
            return storeAfterSalesService.addDelivery(storeParam);
        } else if (param.getAfterSalesType() != null && param.getAfterSalesType() == 2) {
            // 直播售后
            LiveAfterSalesDeliveryParam liveParam = new LiveAfterSalesDeliveryParam();
            liveParam.setUserId(param.getUserId());
            liveParam.setId(param.getSalesId());
            liveParam.setDeliverySn(param.getDeliverySn());
            liveParam.setDeliveryName(param.getDeliveryName());
            return liveAfterSalesService.addDelivery(liveParam);
        }
        return R.error("售后类型错误");
    }

    @Override
    public MergedAfterSalesVO selectMergedAfterSalesById(Long salesId, Integer afterSalesType) {
        MergedAfterSalesVO vo = new MergedAfterSalesVO();

        if (afterSalesType != null && afterSalesType == 1) {
            // 商城售后
            FsStoreAfterSalesScrm storeAfterSales = storeAfterSalesService.selectFsStoreAfterSalesById(salesId);
            if (storeAfterSales != null) {
                BeanUtils.copyProperties(storeAfterSales, vo);
                vo.setAfterSalesType(1);
                vo.setAfterSalesTypeName("商城售后");
                vo.setOrderCode(storeAfterSales.getOrderCode());

                // 填充商品列表
                FsStoreAfterSalesItemScrm itemParam = new FsStoreAfterSalesItemScrm();
                itemParam.setStoreAfterSalesId(salesId);
                List<FsStoreAfterSalesItemScrm> items = storeAfterSalesItemService.selectFsStoreAfterSalesItemList(itemParam);
                vo.setItems(items);
            }
        } else if (afterSalesType != null && afterSalesType == 2) {
            // 直播售后
            LiveAfterSales liveAfterSales = liveAfterSalesService.selectLiveAfterSalesById(salesId);
            if (liveAfterSales != null) {
                BeanUtils.copyProperties(liveAfterSales, vo);
                vo.setAfterSalesType(2);
                vo.setAfterSalesTypeName("直播售后");

                // 查询订单号
                com.fs.live.domain.LiveOrder liveOrder = liveOrderService.selectLiveOrderByOrderId(String.valueOf(liveAfterSales.getOrderId()));
                if (liveOrder != null) {
                    vo.setOrderCode(liveOrder.getOrderCode());
                }

                // 填充商品列表
                List<LiveAfterSalesItem> items = liveAfterSalesItemService.selectLiveAfterSalesItemByAfterId(salesId);
                vo.setItems(items);
            }
        }

        return vo;
    }

    @Override
    public R deleteOrder(String userId, MergedOrderDeleteParam param) {
        Long orderId = param.getOrderId();
        Integer orderType = param.getOrderType();

        if (orderType == null) {
            return R.error("订单类型不能为空");
        }

        if (orderType == 1) {
            // 商城订单
            com.fs.hisStore.domain.FsStoreOrderScrm storeOrder = storeOrderService.selectFsStoreOrderById(orderId);
            if (storeOrder == null) {
                return R.error("订单不存在");
            }
            // 检查订单是否属于当前用户
            if (!storeOrder.getUserId().equals(Long.parseLong(userId))) {
                return R.error("无权删除该订单");
            }
            // 逻辑删除：设置 isDel = 1
            storeOrder.setIsDel(1);
            int result = storeOrderService.updateFsStoreOrder(storeOrder);
            if (result > 0) {
                return R.ok("删除成功");
            } else {
                return R.error("删除失败");
            }
        } else if (orderType == 2) {
            // 直播订单
            com.fs.live.domain.LiveOrder liveOrder = liveOrderService.selectLiveOrderByOrderId(String.valueOf(orderId));
            if (liveOrder == null) {
                return R.error("订单不存在");
            }
            // 检查订单是否属于当前用户
            if (!liveOrder.getUserId().equals(userId)) {
                return R.error("无权删除该订单");
            }
            // 逻辑删除：设置 isDel = "1"
            liveOrder.setIsDel("1");
            int result = liveOrderService.updateLiveOrder(liveOrder);
            if (result > 0) {
                return R.ok("删除成功");
            } else {
                return R.error("删除失败");
            }
        } else {
            return R.error("订单类型错误");
        }
    }
}

