package com.fs.his.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fs.common.core.domain.R;
import com.fs.common.exception.CustomException;
import com.fs.common.exception.ServiceException;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.StringUtils;
import com.fs.core.utils.OrderCodeUtils;
import com.fs.his.domain.*;
import com.fs.his.mapper.*;
import com.fs.his.param.FsIntegralOrderCreateParam;
import com.fs.his.param.FsIntegralOrderListUParam;
import com.fs.his.param.FsIntegralOrderParam;
import com.fs.his.service.IFsIntegralOrderService;
import com.fs.his.vo.FsIntegralOrderListUVO;
import com.fs.his.vo.FsIntegralOrderListVO;
import com.fs.his.vo.FsIntegralOrderPVO;
import com.fs.his.vo.FsStoreProductDeliverExcelVO;
import com.fs.qw.domain.QwUser;
import com.fs.qw.mapper.QwUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
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;

    @Autowired
    private QwUserMapper qwUserMapper;

    /**
     * 查询积分商品订单
     *
     * @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.selectFsUserAddressByAddressId(param.getAddressId());
        FsIntegralGoods integralGoods=fsIntegralGoodsMapper.selectFsIntegralGoodsByGoodsId(param.getGoodsId());
        if(integralGoods.getStock()<=0l){
            return R.error("库存不足");
        }
        if(user.getIntegral()<integralGoods.getIntegral()){
            return R.error("积分不足");
        }
        FsIntegralOrder order=new FsIntegralOrder();
        String orderSn =  OrderCodeUtils.getOrderSn();
        if(StringUtils.isEmpty(orderSn)){
            return R.error("订单生成失败，请重试");
        }
        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());

        //判断当前用户是否有关联企微ID
        if(ObjectUtil.isNotNull(user.getQwUserId())){
            //获取企微信息
            QwUser qwUser=qwUserMapper.selectOne(new LambdaQueryWrapper<QwUser>().select(QwUser::getId,QwUser::getCompanyId,QwUser::getCompanyUserId).eq(QwUser::getId,user.getQwUserId()));
            if(ObjectUtil.isNotNull(qwUser)){
                //写入企业微信ID、销售ID、公司id
                order.setQwUserId(qwUser.getId());
                order.setCompanyId(ObjectUtil.isNotNull(qwUser.getCompanyId())?qwUser.getCompanyId():null);
                order.setCompanyUserId(ObjectUtil.isNotNull(qwUser.getCompanyUserId())?qwUser.getCompanyUserId():null);
            }
        }

        if(fsIntegralOrderMapper.insertFsIntegralOrder(order)>0){
            //写入日志
            FsUser userMap=new FsUser();
            userMap.setUserId(user.getUserId());
            userMap.setIntegral(user.getIntegral()-integralGoods.getIntegral());
            fsUserMapper.updateFsUser(userMap);
            FsUserIntegralLogs logs = new FsUserIntegralLogs();
            logs.setIntegral(-integralGoods.getIntegral());
            logs.setUserId(order.getUserId());
            logs.setBalance(userMap.getIntegral().longValue());
            logs.setLogType(5);
            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 (StringUtils.isNull(list) || list.size() == 0)
        {
            throw new ServiceException("导入商品数据不能为空！");
        }
        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 ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

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