package com.fs.store.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.fs.common.core.domain.R;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.DateUtils;
import com.fs.store.domain.*;
import com.fs.store.mapper.*;
import com.fs.store.param.FsIntegralOrderCreateParam;
import com.fs.store.param.FsIntegralOrderListUParam;
import com.fs.store.param.FsIntegralOrderParam;
import com.fs.store.service.IFsIntegralOrderService;
import com.fs.store.vo.FsIntegralOrderListUVO;
import com.fs.store.vo.FsIntegralOrderListVO;
import com.fs.store.vo.FsIntegralOrderPVO;
import com.fs.store.vo.FsStoreProductDeliverExcelVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 积分商品订单Service业务层处理
 *
 * @author fs
 * @date 2023-11-02
 */
@Service
public class FsIntegralOrderServiceImpl implements IFsIntegralOrderService
{
    @Autowired
    private FsIntegralOrderMapper fsIntegralOrderMapper;

    @Autowired
    private FsUserAddressMapper fsUserAddressMapper;

    @Autowired
    private FsUserMapper fsUserMapper;

    @Autowired
    private FsIntegralGoodsMapper fsIntegralGoodsMapper;
    @Autowired
    private FsUserIntegralLogsMapper fsUserIntegralLogsMapper;
    /**
     * 查询积分商品订单
     *
     * @param orderId 积分商品订单主键
     * @return 积分商品订单
     */
    @Override
    public FsIntegralOrder selectFsIntegralOrderByOrderId(Long orderId)
    {
        return fsIntegralOrderMapper.selectFsIntegralOrderByOrderId(orderId);
    }

    /**
     * 查询积分商品订单列表
     *
     * @param fsIntegralOrder 积分商品订单
     * @return 积分商品订单
     */
    @Override
    public List<FsIntegralOrder> selectFsIntegralOrderList(FsIntegralOrder fsIntegralOrder)
    {
        return fsIntegralOrderMapper.selectFsIntegralOrderList(fsIntegralOrder);
    }

    /**
     * 新增积分商品订单
     *
     * @param fsIntegralOrder 积分商品订单
     * @return 结果
     */
    @Override
    public int insertFsIntegralOrder(FsIntegralOrder fsIntegralOrder)
    {
        fsIntegralOrder.setCreateTime(DateUtils.getNowDate());
        return fsIntegralOrderMapper.insertFsIntegralOrder(fsIntegralOrder);
    }

    /**
     * 修改积分商品订单
     *
     * @param fsIntegralOrder 积分商品订单
     * @return 结果
     */
    @Override
    public int updateFsIntegralOrder(FsIntegralOrder fsIntegralOrder)
    {
        return fsIntegralOrderMapper.updateFsIntegralOrder(fsIntegralOrder);
    }

    /**
     * 批量删除积分商品订单
     *
     * @param orderIds 需要删除的积分商品订单主键
     * @return 结果
     */
    @Override
    public int deleteFsIntegralOrderByOrderIds(Long[] orderIds)
    {
        return fsIntegralOrderMapper.deleteFsIntegralOrderByOrderIds(orderIds);
    }

    /**
     * 删除积分商品订单信息
     *
     * @param orderId 积分商品订单主键
     * @return 结果
     */
    @Override
    public int deleteFsIntegralOrderByOrderId(Long orderId)
    {
        return fsIntegralOrderMapper.deleteFsIntegralOrderByOrderId(orderId);
    }

    @Override
    public List<FsIntegralOrderListVO> selectFsIntegralOrderListVO(FsIntegralOrderParam fsIntegralOrder) {
        return fsIntegralOrderMapper.selectFsIntegralOrderListVO(fsIntegralOrder);
    }

    @Override
    public int sendGoods(FsIntegralOrder fsIntegralOrder) {

        FsIntegralOrder order = fsIntegralOrderMapper.selectFsIntegralOrderByOrderId(fsIntegralOrder.getOrderId());

        if (order==null){
            throw new CustomException("订单不存在");
        }
        if (order.getStatus()!=1L){
            throw new CustomException("非法更改");
        }
        FsIntegralOrder o1 = new FsIntegralOrder();
        o1.setOrderId(fsIntegralOrder.getOrderId());
        o1.setStatus(2);
        o1.setUpdateTime(new DateTime());
        o1.setDeliveryCode(fsIntegralOrder.getDeliveryCode());
        o1.setDeliveryName(fsIntegralOrder.getDeliveryName());
        o1.setDeliverySn(fsIntegralOrder.getDeliverySn());
        o1.setDeliveryTime(DateUtils.getNowDate());

        return fsIntegralOrderMapper.updateFsIntegralOrder(o1);
    }

    @Override
    public List<FsIntegralOrderListUVO> selectFsIntegralOrderListUVO(FsIntegralOrderListUParam param) {
        return fsIntegralOrderMapper.selectFsIntegralOrderListUVO(param);
    }

    @Override
    @Transactional
    public R createOrder(FsIntegralOrderCreateParam param) {

        FsUser user=fsUserMapper.selectFsUserByUserId(param.getUserId());
        FsUserAddress address=fsUserAddressMapper.selectFsUserAddressById(param.getAddressId());
        FsIntegralGoods integralGoods=fsIntegralGoodsMapper.selectFsIntegralGoodsByGoodsId(param.getGoodsId());
        if(integralGoods.getStock()<=0l){
            return R.error("库存不足");
        }
        if(user.getIntegral().compareTo(BigDecimal.valueOf(integralGoods.getIntegral()))<0 ){
            return R.error("积分不足");
        }
        FsIntegralOrder order=new FsIntegralOrder();
        String orderSn = IdUtil.getSnowflake(0, 0).nextIdStr();
        order.setOrderCode(orderSn);
        order.setUserId(user.getUserId());
        order.setStatus(1);
        order.setBarCode(integralGoods.getBarCode());
        order.setIntegral(integralGoods.getIntegral().toString());
        order.setItemJson(JSONUtil.toJsonStr(integralGoods));
        order.setUserName(address.getRealName());
        order.setUserAddress(address.getProvince()+address.getCity()+address.getDistrict()+address.getDetail());
        order.setUserPhone(address.getPhone());
        order.setCreateTime(new Date());
        if(fsIntegralOrderMapper.insertFsIntegralOrder(order)>0){
            //写入日志
            FsUser userMap=new FsUser();
            userMap.setUserId(user.getUserId());
            userMap.setIntegral(user.getIntegral().subtract(BigDecimal.valueOf(integralGoods.getIntegral())));
            fsUserMapper.updateFsUser(userMap);
            FsUserIntegralLogs logs = new FsUserIntegralLogs();
            logs.setIntegral(BigDecimal.valueOf(integralGoods.getIntegral()).negate());
            logs.setUserId(order.getUserId());
            logs.setBalance(userMap.getIntegral());
            logs.setLogType(4);
            logs.setBusinessId(order.getOrderId().toString());
            logs.setCreateTime(new Date());
            fsUserIntegralLogsMapper.insertFsUserIntegralLogs(logs);
            return R.ok("兑换成功").put("order",order);
        }
        else{

            return R.error("订单创建失败");
        }
    }

    @Override
    public String importProductDeliver(List<FsStoreProductDeliverExcelVO> list) {
        if (com.fs.common.utils.StringUtils.isNull(list) || list.size() == 0)
        {
            throw new CustomException("导入商品数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (FsStoreProductDeliverExcelVO vo : list)
        {
            try
            {
                FsIntegralOrder o = fsIntegralOrderMapper.selectFsIntegralOrderByOrderCode(vo.getOrderCode());
                if (o==null){
                throw new CustomException("没有此订单");
                }
                if (o.getStatus()!=1){
                    throw new CustomException("订单状态不为待发货");
                }
                // 判断每个字段是否为null或为空字符串
                if (vo.getOrderCode() == null || vo.getOrderCode().isEmpty()) {
                    throw new CustomException("订单编号为空");
                }

                if (vo.getDeliveryName() == null || vo.getDeliveryName().isEmpty()) {
                    throw new CustomException("快递名称为空");
                }

                if (vo.getDeliverySn() == null || vo.getDeliverySn().isEmpty()) {
                    throw new CustomException("快递单号为空");
                }
                FsIntegralOrder order = new FsIntegralOrder();
                order.setOrderId(o.getOrderId());
                order.setDeliverySn(vo.getDeliverySn());
                order.setDeliveryName(vo.getDeliveryName());
                order.setDeliveryTime(DateUtils.getNowDate());
                order.setDeliveryCode(vo.getDeliveryCode());

                order.setOrderCode(vo.getOrderCode());
                order.setStatus(2);

                int i = fsIntegralOrderMapper.updateFsIntegralOrder(order);
                successNum++;
                successMsg.append("<br/>" + successNum + "、订单编号 " + vo.getOrderCode() + " 导入成功");

            }
            catch (Exception e)
            {

                failureNum++;
                String msg = "<br/>" + failureNum + "、订单编号 " + vo.getOrderCode()  + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public FsIntegralOrderPVO selectFsIntegralOrderPVO(Long orderId) {
        return fsIntegralOrderMapper.selectFsIntegralOrderPVO(orderId);
    }
}
