package co.yixiang.yshop.module.order.service.storeaftersales;

import co.yixiang.yshop.framework.common.enums.OrderInfoEnum;
import co.yixiang.yshop.framework.common.pojo.PageResult;
import co.yixiang.yshop.module.member.controller.admin.user.vo.UserRespVO;
import co.yixiang.yshop.module.member.convert.user.UserConvert;
import co.yixiang.yshop.module.member.dal.dataobject.user.MemberUserDO;
import co.yixiang.yshop.module.member.dal.mysql.user.MemberUserMapper;
import co.yixiang.yshop.module.order.controller.admin.storeaftersales.vo.StoreAfterSalesPageReqVO;
import co.yixiang.yshop.module.order.controller.admin.storeaftersales.vo.StoreAfterSalesRespVO;
import co.yixiang.yshop.module.order.controller.admin.storeaftersales.vo.StoreAfterSalesUpdateReqVO;
import co.yixiang.yshop.module.order.convert.storeaftersales.StoreAfterSalesConvert;
import co.yixiang.yshop.module.order.dal.dataobject.storeaftersales.StoreAfterSalesDO;
import co.yixiang.yshop.module.order.dal.dataobject.storeaftersalesitem.StoreAfterSalesItemDO;
import co.yixiang.yshop.module.order.dal.dataobject.storeorder.StoreOrderDO;
import co.yixiang.yshop.module.order.dal.mysql.storeaftersales.StoreAfterSalesMapper;
import co.yixiang.yshop.module.order.dal.mysql.storeaftersalesitem.StoreAfterSalesItemMapper;
import co.yixiang.yshop.module.order.dal.mysql.storeorder.StoreOrderMapper;
import co.yixiang.yshop.module.order.dal.redis.ofterorder.AfterOrderRedisDAO;
import co.yixiang.yshop.module.order.enums.AfterChangeTypeEnum;
import co.yixiang.yshop.module.order.enums.AfterSalesStatusEnum;
import co.yixiang.yshop.module.order.enums.AfterTypeEnum;
import co.yixiang.yshop.module.order.service.storeaftersalesstatus.StoreAfterSalesStatusService;
import co.yixiang.yshop.module.order.service.storeorder.AppStoreOrderService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;

import static co.yixiang.yshop.framework.common.exception.util.ServiceExceptionUtil.exception;
import static co.yixiang.yshop.module.order.enums.ErrorCodeConstants.ORDER_ADDRESS_REQUERED;
import static co.yixiang.yshop.module.order.enums.ErrorCodeConstants.STORE_AFTER_SALES_NOT_EXISTS;

/**
 * 售后记录 Service 实现类
 *
 * @author yshop
 */
@Service
@Validated
public class StoreAfterSalesServiceImpl implements StoreAfterSalesService {

    @Resource
    private StoreAfterSalesMapper storeAfterSalesMapper;
    @Resource
    private StoreAfterSalesItemMapper storeAfterSalesItemMapper;
    @Resource
    private MemberUserMapper memberUserMapper;
    @Resource
    private StoreOrderMapper storeOrderMapper;
    @Resource
    private AfterOrderRedisDAO afterOrderRedisDAO;
    @Resource
    private AppStoreOrderService appStoreOrderService;
    @Resource
    private StoreAfterSalesStatusService storeAfterSalesStatusService;



    @Override
    public void updateStoreAfterSales(StoreAfterSalesUpdateReqVO updateReqVO) {
        // 校验存在
        validateStoreAfterSalesExists(updateReqVO.getId());

        this.salesCheck(updateReqVO.getId(),updateReqVO.getOrderCode(),
                updateReqVO.getType(),updateReqVO.getConsignee(),updateReqVO.getPhoneNumber(),updateReqVO.getAddress());

    }

    /**
     * 售后处理
     * @param salesId 售后id
     * @param orderCode 订单号
     * @param approvalStatus 审核状态1-同意 2-拒绝
     * @param consignee
     * @param phoneNumber
     * @param address
     */
    private void salesCheck(Long salesId, String orderCode, Integer approvalStatus, String consignee, String phoneNumber, String address) {
        StoreAfterSalesDO storeAfterSales = storeAfterSalesMapper.selectOne(Wrappers.<StoreAfterSalesDO>lambdaQuery()
                .eq(StoreAfterSalesDO::getOrderCode, orderCode).eq(StoreAfterSalesDO::getId, salesId));
        //审核成功
        if (AfterTypeEnum.TYPE_1.getValue().equals(approvalStatus)) {
            storeAfterSales.setState(AfterSalesStatusEnum.STATUS_1.getValue());
            //退货退款
            if(AfterTypeEnum.SERVICE_TYPE_1.getValue().equals(storeAfterSales.getServiceType())) {
                if (StringUtils.isEmpty(consignee) || StringUtils.isEmpty(phoneNumber) || StringUtils.isEmpty(address)) {
                    throw exception(ORDER_ADDRESS_REQUERED);
                }
                storeAfterSales.setConsignee(consignee);
                storeAfterSales.setPhoneNumber(phoneNumber);
                storeAfterSales.setAddress(address);

                storeAfterSalesStatusService.create(storeAfterSales.getUserId(),storeAfterSales.getId()
                        ,AfterChangeTypeEnum.STATE_1.getValue(),AfterChangeTypeEnum.STATE_1.getDesc());
                //退款退货得后面一步同意退款才退
            }else {
                //仅仅退款直接退款
                appStoreOrderService.orderRefund(storeAfterSales.getOrderCode(),storeAfterSales.getRefundAmount());

                storeAfterSales.setState(AfterSalesStatusEnum.STATUS_3.getValue());
                storeAfterSalesStatusService.create(storeAfterSales.getUserId(),storeAfterSales.getId()
                        ,AfterChangeTypeEnum.STATE_3.getValue(),AfterChangeTypeEnum.STATE_3.getDesc());
            }


        } else {//拒绝
            storeAfterSales.setState(AfterSalesStatusEnum.STATUS_3.getValue());
            storeAfterSales.setSalesState(AfterTypeEnum.TYPE_2.getValue());
            //操作记录
            storeAfterSalesStatusService.create(storeAfterSales.getUserId(),storeAfterSales.getId()
                    ,AfterChangeTypeEnum.STATE_4.getValue(),AfterChangeTypeEnum.STATE_4.getDesc());

            StoreOrderDO yxStoreOrder = storeOrderMapper.selectOne(Wrappers.<StoreOrderDO>lambdaQuery().eq(StoreOrderDO::getOrderId, storeAfterSales.getOrderCode()));
            String o = afterOrderRedisDAO.get(storeAfterSales.getOrderCode(),storeAfterSales.getUserId());
            yxStoreOrder.setStatus(o == null ? 0 : Integer.parseInt(o));
            yxStoreOrder.setRefundStatus(OrderInfoEnum.STATUS_0.getValue());
            storeOrderMapper.updateById(yxStoreOrder);

            afterOrderRedisDAO.delete(storeAfterSales.getOrderCode(),storeAfterSales.getUserId());
        }
        storeAfterSalesMapper.updateById(storeAfterSales);
    }


    /**
     * 立即退款
     * @param id 编号
     */
    @Override
    public void payStoreAfterSales(Long id){
        StoreAfterSalesDO storeAfterSales = storeAfterSalesMapper.selectOne(Wrappers.<StoreAfterSalesDO>lambdaQuery()
                .eq(StoreAfterSalesDO::getId, id));
        appStoreOrderService.orderRefund(storeAfterSales.getOrderCode(),storeAfterSales.getRefundAmount());

        storeAfterSales.setState(AfterSalesStatusEnum.STATUS_3.getValue());
        storeAfterSalesStatusService.create(storeAfterSales.getUserId(),storeAfterSales.getId()
                ,AfterChangeTypeEnum.STATE_3.getValue(),AfterChangeTypeEnum.STATE_3.getDesc());
    }


    private void validateStoreAfterSalesExists(Long id) {
        if (storeAfterSalesMapper.selectById(id) == null) {
            throw exception(STORE_AFTER_SALES_NOT_EXISTS);
        }
    }

    @Override
    public StoreAfterSalesDO getStoreAfterSales(Long id) {
        return storeAfterSalesMapper.selectById(id);
    }


    /**
     * 获得售后记录分页
     *
     * @param pageReqVO 分页查询
     * @return 售后记录分页
     */
    @Override
    public PageResult<StoreAfterSalesRespVO> getStoreAfterSalesPage(StoreAfterSalesPageReqVO pageReqVO) {
        PageResult<StoreAfterSalesDO> pageResult = storeAfterSalesMapper.selectPage(pageReqVO);
        PageResult<StoreAfterSalesRespVO> storeAfterSalesRespVOPageResult = StoreAfterSalesConvert.INSTANCE.convertPage(pageResult);
        for (StoreAfterSalesRespVO storeAfterSalesRespVO : storeAfterSalesRespVOPageResult.getList()) {
            LambdaQueryWrapper<StoreAfterSalesItemDO> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(StoreAfterSalesItemDO::getStoreAfterSalesId,storeAfterSalesRespVO.getId());
            List<StoreAfterSalesItemDO> storeAfterSalesItemDOS = storeAfterSalesItemMapper.selectList(wrapper);
            MemberUserDO memberUserDO = memberUserMapper.selectById(storeAfterSalesRespVO.getUserId());
            UserRespVO userRespVO = UserConvert.INSTANCE.convert4(memberUserDO);
            storeAfterSalesRespVO.setStoreOrderCartInfoDOList(storeAfterSalesItemDOS);
            storeAfterSalesRespVO.setUserRespVO(userRespVO);
        }
        return storeAfterSalesRespVOPageResult;
    }



}
