package com.fs.his.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fs.common.constant.FsConstants;
import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
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.enums.BusinessTypeEnum;
import com.fs.his.enums.FsUserIntegralLogTypeEnum;
import com.fs.his.enums.PaymentMethodEnum;
import com.fs.his.mapper.*;
import com.fs.his.param.*;
import com.fs.his.service.IFsIntegralCartService;
import com.fs.his.service.IFsIntegralOrderService;
import com.fs.his.service.IFsStorePaymentService;
import com.fs.his.service.IFsUserIntegralLogsService;
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 com.fs.tzBankPay.doman.PayType;
import com.fs.ybPay.domain.OrderResult;
import com.fs.ybPay.dto.OrderQueryDTO;
import com.fs.ybPay.service.IPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 积分商品订单Service业务层处理
 *
 * @author fs
 * @date 2023-11-02
 */
@Slf4j
@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;
    @Autowired
    private IFsUserIntegralLogsService userIntegralLogsService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IPayService ybPayService;
    @Autowired
    private IFsStorePaymentService storePaymentService;
    @Autowired
    private IFsIntegralCartService cartService;

    /**
     * 查询积分商品订单
     *
     * @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 (Objects.isNull(user)) {
            return R.error("用户不存在");
        }
        if (Objects.isNull(address)) {
            return R.error("地址不存在");
        }
        if (Objects.isNull(integralGoods)) {
            return R.error("商品不存在");
        }
        if(integralGoods.getStock()<=0L){
            return R.error("库存不足");
        }
        if(user.getIntegral()<integralGoods.getIntegral()){
            return R.error("积分不足");
        }

        // 减库存
        if (fsIntegralGoodsMapper.subStock(integralGoods.getGoodsId(), 1) <= 0) {
            throw new CustomException("库存不足");
        }

        integralGoods.setNum(1);
        List<FsIntegralGoods> goodsItem = new ArrayList<>();
        goodsItem.add(integralGoods);

        // 创建订单
        return createOrder(user, address, integralGoods.getIntegral(),integralGoods.getCash(), goodsItem);
    }

    /**
     * 创建订单
     */
    private R createOrder(FsUser user, FsUserAddress address, Long totalIntegral, BigDecimal totalCash, List<FsIntegralGoods> goodsItem) {
        FsIntegralOrder order = new FsIntegralOrder();
        String orderSn = OrderCodeUtils.getOrderSn();
        if(StringUtils.isEmpty(orderSn)){
            throw new CustomException("订单生成失败，请重试");
        }

        // 现金
        if (totalCash.compareTo(BigDecimal.ZERO) > 0) {
            // 现金+积分
            order.setPayType(totalIntegral > 0 ? 3 : 2);
            order.setStatus(4);
            order.setIsPay(0);
            order.setPayMoney(totalCash);
        }
        // 积分
        else {
            order.setPayType(1);
            order.setStatus(1);
            order.setIsPay(1);
            order.setPayTime(LocalDateTime.now());
        }

        order.setOrderCode(orderSn);
        order.setUserId(user.getUserId());
        order.setBarCode(goodsItem.get(0).getBarCode());
        order.setIntegral(totalIntegral.toString());
        order.setItemJson(JSONUtil.toJsonStr(goodsItem));
        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){
            if (order.getPayType() != 2) {
                //写入日志
                FsUser userMap=new FsUser();
                userMap.setUserId(user.getUserId());
                userMap.setIntegral(user.getIntegral()-totalIntegral);
                fsUserMapper.updateFsUser(userMap);
                FsUserIntegralLogs logs = new FsUserIntegralLogs();
                logs.setIntegral(-totalIntegral);
                logs.setUserId(order.getUserId());
                logs.setBalance(userMap.getIntegral());
                logs.setLogType(5);
                logs.setBusinessId(order.getOrderId().toString());
                logs.setCreateTime(new Date());
                fsUserIntegralLogsMapper.insertFsUserIntegralLogs(logs);
            }

            // 积分支付
            if (order.getPayType() == 1) {
                // 首次完成积分商城下单
                FsUserAddIntegralTemplateParam integralParam = new FsUserAddIntegralTemplateParam();
                integralParam.setUserId(order.getUserId());
                integralParam.setLogType(FsUserIntegralLogTypeEnum.TYPE_22.getValue());
                integralParam.setBusinessId(order.getOrderId().toString());
                userIntegralLogsService.addIntegralTemplate(integralParam);

                return R.ok("兑换成功").put("order",order).put("isPay", 1);
            }
            // 现金 或 积分+现金
            else {
                String redisKey = String.valueOf(StrUtil.format("{}{}", FsConstants.REDIS_INTEGRAL_ORDER_UNPAY, order.getOrderId()));
                redisCache.setCacheObject(redisKey,order.getOrderId(),30, TimeUnit.MINUTES);
                return R.ok().put("order",order).put("isPay", 0);
            }
        }
        else{
            throw new CustomException("订单创建失败");
        }
    }

    /**
     * 创建购物车订单
     * @param param 参数
     * @return  R
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public R createCartOrder(FsIntegralCartOrderCreateParam param) {
        FsUser user=fsUserMapper.selectFsUserByUserId(param.getUserId());
        FsUserAddress address=fsUserAddressMapper.selectFsUserAddressByAddressId(param.getAddressId());

        if (Objects.isNull(user)) {
            throw new CustomException("用户不存在");
        }
        if (Objects.isNull(address)) {
            throw new CustomException("地址不存在");
        }

        Wrapper<FsIntegralCart> wrapper = Wrappers.<FsIntegralCart>lambdaQuery()
                .eq(FsIntegralCart::getUserId, user.getUserId())
                .in(FsIntegralCart::getId, param.getIds());
        List<FsIntegralCart> carts = cartService.list(wrapper);
        if (carts.isEmpty()) {
            throw new CustomException("请选择商品");
        }

        long totalIntegral = 0L;
        BigDecimal totalCash = BigDecimal.ZERO;
        List<FsIntegralGoods> goodsItem = new ArrayList<>();
        for (FsIntegralCart cart : carts) {
            FsIntegralGoods integralGoods = fsIntegralGoodsMapper.selectFsIntegralGoodsByGoodsId(cart.getGoodsId());
            if (Objects.isNull(integralGoods)) {
                throw new CustomException("商品不存在");
            }
            if(integralGoods.getStock() < cart.getCartNum()){
                throw new CustomException("库存不足");
            }

            // 减库存
            if (fsIntegralGoodsMapper.subStock(integralGoods.getGoodsId(), cart.getCartNum()) <= 0) {
                throw new CustomException("库存不足");
            }

            totalIntegral += integralGoods.getIntegral() * cart.getCartNum();
            totalCash = totalCash.add(integralGoods.getCash().multiply(BigDecimal.valueOf(cart.getCartNum())));

            integralGoods.setNum(cart.getCartNum());
            goodsItem.add(integralGoods);
        }

        return createOrder(user, address, totalIntegral, totalCash, goodsItem);
    }

    @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);
    }

    /**
     * 取消订单
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public R cannelOrder(Long orderId) {
        // 取消订单
        FsIntegralOrder order = fsIntegralOrderMapper.selectFsIntegralOrderByOrderId(orderId);
        if (!order.getStatus().equals(4)){
            return R.error("非法操作");
        }

        order.setStatus(5);
        fsIntegralOrderMapper.updateFsIntegralOrder(order);

        // 还原库存
        if (order.getItemJson().startsWith("[") && order.getItemJson().endsWith("]")){
            List<FsIntegralGoods> goodsItem = JSONUtil.toBean(order.getItemJson(), new TypeReference<List<FsIntegralGoods>>(){}, true);
            goodsItem.forEach(goods -> fsIntegralGoodsMapper.addStock(goods.getGoodsId(), Objects.isNull(goods.getNum()) ? 1 : goods.getNum()));
        } else {
            FsIntegralGoods integralGoods = JSONUtil.toBean(order.getItemJson(), FsIntegralGoods.class);
            fsIntegralGoodsMapper.addStock(integralGoods.getGoodsId(), Objects.isNull(integralGoods.getNum()) ? 1 : integralGoods.getNum());
        }

        // 还原积分
        FsUser user=fsUserMapper.selectFsUserByUserId(order.getUserId());
        FsUser userMap=new FsUser();
        userMap.setUserId(user.getUserId());
        userMap.setIntegral(user.getIntegral() + Long.parseLong(order.getIntegral()));
        fsUserMapper.updateFsUser(userMap);
        FsUserIntegralLogs logs = new FsUserIntegralLogs();
        logs.setIntegral(Long.parseLong(order.getIntegral()));
        logs.setUserId(order.getUserId());
        logs.setBalance(userMap.getIntegral());
        logs.setLogType(5);
        logs.setBusinessId(order.getOrderId().toString());
        logs.setCreateTime(new Date());
        fsUserIntegralLogsMapper.insertFsUserIntegralLogs(logs);

        return R.ok();
    }

    /**
     * 预支付
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public R payment(FsIntegralOrderDoPayParam param, PaymentMethodEnum paymentMethod) {
        FsIntegralOrder order = fsIntegralOrderMapper.selectFsIntegralOrderByOrderId(param.getOrderId());
        if (Objects.isNull(order) || !order.getStatus().equals(4)
                || order.getPayMoney().compareTo(BigDecimal.ZERO) <= 0){
            return R.error("非法操作");
        }

        PayOrderParam payOrderParam = buildPayOrderParam(paymentMethod, order);
        return storePaymentService.processPayment(payOrderParam);
    }

    /**
     * 构建参数
     */
    private static PayOrderParam buildPayOrderParam(PaymentMethodEnum paymentMethod, FsIntegralOrder order) {
        PayOrderParam payOrderParam = new PayOrderParam();
        payOrderParam.setOrderId(order.getOrderId());
        payOrderParam.setOrderCode(order.getOrderCode());
        payOrderParam.setAmount(order.getPayMoney());
        payOrderParam.setUserId(order.getUserId());
        payOrderParam.setCompanyId(order.getCompanyId());
        payOrderParam.setCompanyUserId(order.getCompanyUserId());
        payOrderParam.setPaymentMethod(paymentMethod);
        payOrderParam.setBusinessType(BusinessTypeEnum.INTEGRAL_ORDER);
        return payOrderParam;
    }

    /**
     * 支付回调
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public R payConfirm(String orderSn, String payCode, String tradeNo, String payType, int type,String bankTransactionId,String bankSerialNo){
        log.info("进入积分商城订单支付回调 orderSn: {}, payCode: {}, tradeNo: {}, payType: {}, type: {}",
                orderSn, payCode, tradeNo, payType, type);
        FsIntegralOrder order = null;
        if (type == 1) {
            FsStorePayment storePayment = storePaymentService.selectFsStorePaymentByPaymentCode(payCode);
            if (Objects.isNull(storePayment)) {
                log.info("支付单号不存在 payCode: {}", payCode);
                return R.error("支付单号不存在");
            }

            if(storePayment.getStatus() == 0){
                FsStorePayment paymentMap = new FsStorePayment();
                paymentMap.setPaymentId(storePayment.getPaymentId());
                paymentMap.setStatus(1);
                paymentMap.setPayTime(new Date());
                paymentMap.setTradeNo(tradeNo);
                paymentMap.setBankSerialNo(bankSerialNo);
                paymentMap.setBankTransactionId(bankTransactionId);
                if(payType.equals(PayType.WECHAT_MINI_PROGRAM_PAYMENT.getCode())){
                    paymentMap.setPayTypeCode(PayType.WECHAT_MINI_PROGRAM_PAYMENT.name());
                }
                else if(payType.equals(PayType.ALIPAY_BARCODE_PAYMENT.getCode())){
                    paymentMap.setPayTypeCode(PayType.ALIPAY_BARCODE_PAYMENT.name());
                }
                if (storePayment.getPayMode().equals("yb")){
                    OrderQueryDTO orderQueryDTO = new OrderQueryDTO();
                    orderQueryDTO.setUpOrderId(tradeNo);
                    OrderResult orderResult = ybPayService.getOrder(orderQueryDTO);
                    paymentMap.setBankSerialNo(orderResult.getBankOrderId());
                    paymentMap.setBankTransactionId(orderResult.getBankTrxId());
                }
                log.info("更新支付记录");
                storePaymentService.updateFsStorePayment(paymentMap);
                order = fsIntegralOrderMapper.selectFsIntegralOrderByOrderId(Long.parseLong(storePayment.getBusinessId()));
            }
        }
        else if (type == 2) {
            order = fsIntegralOrderMapper.selectFsIntegralOrderByOrderCode(orderSn);
        }

        if (Objects.isNull(order) || order.getStatus() != 4) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error("非法操作");
        }

        // 首次完成积分商城下单
        FsUserAddIntegralTemplateParam integralParam = new FsUserAddIntegralTemplateParam();
        integralParam.setUserId(order.getUserId());
        integralParam.setLogType(FsUserIntegralLogTypeEnum.TYPE_22.getValue());
        integralParam.setBusinessId(order.getOrderId().toString());
        userIntegralLogsService.addIntegralTemplate(integralParam);

        order.setIsPay(1);
        order.setStatus(1);
        order.setPayTime(LocalDateTime.now());
        fsIntegralOrderMapper.updateFsIntegralOrder(order);
        return R.ok();
    }

}
