package org.dromara.mall.trade.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.mall.trade.domain.MallAfterSale;
import org.dromara.mall.trade.domain.bo.MallAfterSaleBo;
import org.dromara.mall.trade.domain.vo.MallAfterSaleVo;
import org.dromara.mall.trade.mapper.MallAfterSaleMapper;
import org.dromara.mall.trade.service.MallAfterSaleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * 售后申请Service业务层处理
 *
 * @author pengles
 */
@RequiredArgsConstructor
@Service
public class MallAfterSaleServiceImpl implements MallAfterSaleService {

    private final MallAfterSaleMapper baseMapper;

    /**
     * 查询售后申请
     */
    @Override
    public MallAfterSaleVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 根据售后单号查询
     */
    @Override
    public MallAfterSaleVo queryByAfterSaleNo(String afterSaleNo) {
        LambdaQueryWrapper<MallAfterSale> lqw = new LambdaQueryWrapper<>();
        lqw.eq(MallAfterSale::getAfterSaleNo, afterSaleNo);
        return baseMapper.selectVoOne(lqw);
    }

    /**
     * 查询售后申请列表
     */
    @Override
    public TableDataInfo<MallAfterSaleVo> queryPageList(MallAfterSaleBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<MallAfterSale> lqw = buildQueryWrapper(bo);
        Page<MallAfterSaleVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询售后申请列表
     */
    @Override
    public List<MallAfterSaleVo> queryList(MallAfterSaleBo bo) {
        LambdaQueryWrapper<MallAfterSale> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<MallAfterSale> buildQueryWrapper(MallAfterSaleBo bo) {
        LambdaQueryWrapper<MallAfterSale> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StringUtils.isNotBlank(bo.getAfterSaleNo()), MallAfterSale::getAfterSaleNo, bo.getAfterSaleNo());
        lqw.eq(bo.getOrderId() != null, MallAfterSale::getOrderId, bo.getOrderId());
        lqw.eq(StringUtils.isNotBlank(bo.getOrderNo()), MallAfterSale::getOrderNo, bo.getOrderNo());
        lqw.eq(bo.getOrderItemId() != null, MallAfterSale::getOrderItemId, bo.getOrderItemId());
        lqw.eq(bo.getUserId() != null, MallAfterSale::getUserId, bo.getUserId());
        lqw.eq(bo.getType() != null, MallAfterSale::getType, bo.getType());
        lqw.eq(bo.getStatus() != null, MallAfterSale::getStatus, bo.getStatus());
        lqw.orderByDesc(MallAfterSale::getCreateTime);
        return lqw;
    }

    /**
     * 生成售后单号
     */
    private String generateAfterSaleNo() {
        return "AS" + System.currentTimeMillis() + IdUtil.fastSimpleUUID().substring(0, 6).toUpperCase();
    }

    /**
     * 新增售后申请
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(MallAfterSaleBo bo) {
        MallAfterSale add = MapstructUtils.convert(bo, MallAfterSale.class);
        validEntityBeforeSave(add);

        // 设置用户ID（移动端用户）
        if (add.getUserId() == null) {
            add.setUserId(LoginHelper.getUserId());
        }

        // 生成售后单号
        if (StringUtils.isBlank(add.getAfterSaleNo())) {
            add.setAfterSaleNo(generateAfterSaleNo());
        }

        // 设置默认状态为待审核
        if (add.getStatus() == null) {
            add.setStatus(0);
        }

        // 设置申请时间
        if (add.getApplyTime() == null) {
            add.setApplyTime(new Date());
        }

        // 设置默认数量
        if (add.getQuantity() == null) {
            add.setQuantity(1);
        }

        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改售后申请
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(MallAfterSaleBo bo) {
        MallAfterSale update = MapstructUtils.convert(bo, MallAfterSale.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MallAfterSale entity) {
        // 可以添加业务校验逻辑
    }

    /**
     * 批量删除售后申请
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // 可以添加业务校验逻辑
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 审核售后申请（同意/拒绝）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean audit(Long id, Integer status, String refuseReason) {
        MallAfterSale afterSale = baseMapper.selectById(id);
        if (afterSale == null) {
            throw new ServiceException("售后申请不存在");
        }
        if (afterSale.getStatus() != 0) {
            throw new ServiceException("售后申请已审核，不能重复审核");
        }
        if (status == null || (status != 1 && status != 2)) {
            throw new ServiceException("审核状态不正确");
        }

        afterSale.setStatus(status);
        afterSale.setAuditTime(new Date());

        if (status == 2) {
            // 拒绝
            if (StringUtils.isBlank(refuseReason)) {
                throw new ServiceException("拒绝原因不能为空");
            }
            afterSale.setRefuseReason(refuseReason);
        } else if (status == 1) {
            // 同意
            if (afterSale.getType() == 1 || afterSale.getType() == 2) {
                // 退货或换货，状态变为待退货
                afterSale.setStatus(3);
            }
            // 退款类型，状态保持为已同意，等待退款处理
        }

        return baseMapper.updateById(afterSale) > 0;
    }

    /**
     * 用户填写退货物流信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean fillLogistics(Long id, String logisticsCompany, String logisticsNo) {
        MallAfterSale afterSale = baseMapper.selectById(id);
        if (afterSale == null) {
            throw new ServiceException("售后申请不存在");
        }
        if (afterSale.getStatus() != 3) {
            throw new ServiceException("当前状态不能填写物流信息");
        }
        if (afterSale.getType() == 0) {
            throw new ServiceException("退款类型不需要填写物流信息");
        }

        afterSale.setLogisticsCompany(logisticsCompany);
        afterSale.setLogisticsNo(logisticsNo);
        afterSale.setReturnTime(new Date());
        afterSale.setStatus(4); // 待收货

        return baseMapper.updateById(afterSale) > 0;
    }

    /**
     * 确认收货（商家确认收到退货）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean confirmReceive(Long id) {
        MallAfterSale afterSale = baseMapper.selectById(id);
        if (afterSale == null) {
            throw new ServiceException("售后申请不存在");
        }
        if (afterSale.getStatus() != 4) {
            throw new ServiceException("当前状态不能确认收货");
        }

        afterSale.setReceiveTime(new Date());
        // 状态变为已完成（退款或换货完成需要调用支付中心退款接口或换货接口）
        // 这里暂时设置为已完成，实际业务中需要调用支付中心退款接口
        afterSale.setStatus(5);

        return baseMapper.updateById(afterSale) > 0;
    }

    /**
     * 完成售后（退款完成或换货完成）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean complete(Long id) {
        MallAfterSale afterSale = baseMapper.selectById(id);
        if (afterSale == null) {
            throw new ServiceException("售后申请不存在");
        }
        if (afterSale.getStatus() == 5 || afterSale.getStatus() == 6) {
            throw new ServiceException("售后申请已完成或已取消");
        }

        afterSale.setStatus(5);
        if (afterSale.getType() == 0 || afterSale.getType() == 1) {
            // 退款或退货，设置退款时间
            afterSale.setRefundTime(new Date());
        }

        return baseMapper.updateById(afterSale) > 0;
    }

    /**
     * 取消售后申请
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean cancel(Long id) {
        MallAfterSale afterSale = baseMapper.selectById(id);
        if (afterSale == null) {
            throw new ServiceException("售后申请不存在");
        }
        if (afterSale.getStatus() == 5 || afterSale.getStatus() == 6) {
            throw new ServiceException("售后申请已完成或已取消");
        }
        if (afterSale.getStatus() == 4) {
            throw new ServiceException("商家已收货，不能取消");
        }

        afterSale.setStatus(6);
        return baseMapper.updateById(afterSale) > 0;
    }

}
