package com.liquidnet.client.admin.zhengzai.kylin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liquidnet.client.admin.zhengzai.kylin.utils.DataUtils;
import com.liquidnet.commons.lang.util.BeanUtil;
import com.liquidnet.service.kylin.constant.KylinTableStatusConst;
import com.liquidnet.service.kylin.dao.OrderRefundDao;
import com.liquidnet.service.kylin.dto.param.RefundApplyParam;
import com.liquidnet.service.kylin.dto.param.RefundCallbackParam;
import com.liquidnet.service.kylin.dto.param.RefundSearchParam;
import com.liquidnet.service.kylin.dto.vo.KylinOrderRefundsVo;
import com.liquidnet.service.kylin.entity.KylinOrderRefunds;
import com.liquidnet.service.kylin.entity.KylinOrderTicketEntities;
import com.liquidnet.service.kylin.entity.KylinOrderTicketStatus;
import com.liquidnet.service.kylin.entity.KylinOrderTickets;
import com.liquidnet.service.kylin.mapper.KylinOrderRefundsMapper;
import com.liquidnet.service.kylin.mapper.KylinOrderTicketEntitiesMapper;
import com.liquidnet.service.kylin.mapper.KylinOrderTicketStatusMapper;
import com.liquidnet.service.kylin.mapper.KylinOrderTicketsMapper;
import com.liquidnet.service.kylin.service.IKylinOrderRefundsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 订单退款表 服务实现类
 * </p>
 *
 * @author jiangxiulong
 * @since 2021-05-26
 */
@Slf4j
@Service
public class KylinOrderRefundsServiceImpl extends ServiceImpl<KylinOrderRefundsMapper, KylinOrderRefunds> implements IKylinOrderRefundsService {
    @Autowired
    private KylinOrderTicketsMapper kylinOrderTicketsMapper;

    @Autowired
    private KylinRefundsStatusServiceImpl kylinRefundsStatusServiceImpl;

    @Autowired
    private KylinOrderRefundsMapper kylinOrderRefundsMapper;

    @Autowired
    private KylinOrderTicketStatusMapper kylinOrderTicketStatusMapper;

    @Autowired
    private KylinOrderTicketEntitiesMapper kylinOrderTicketEntitiesMapper;

    @Autowired
    MongoTemplate mongoTemplate;

    public Boolean refundApply(RefundApplyParam refundApplyParam) throws Exception {
        /*int count = 0;
        count = kylinOrderTicketsMapper.selectCount(
                new UpdateWrapper<KylinOrderTickets>().eq("order_tickets_id", refundApplyParam.getOrderTicketsId()).eq("coupon_type", "no")
        );
        if (count > 0) {
            throw new Exception("使用满减券 暂不能退款");
        }*/
        String orderTicketsId = refundApplyParam.getOrderTicketsId();
        List<String> ticketEntityIds = refundApplyParam.getTicketEntityIds();
        double RefundPriceExpress = refundApplyParam.getRefundPriceExpress();

        KylinOrderTickets orderInfo = kylinOrderTicketsMapper.selectOne(
                new QueryWrapper<KylinOrderTickets>().eq("order_tickets_id", orderTicketsId)
        );
        KylinOrderTicketStatus orderStatus = kylinOrderTicketStatusMapper.selectOne(
                new QueryWrapper<KylinOrderTicketStatus>().eq("order_id", orderTicketsId)
        );
        int thisOrderStatus = orderStatus.getStatus();
        int thisPayStatus = orderStatus.getPayStatus();
        double priceExpress = orderInfo.getPriceExpress().doubleValue();

        // todo 转增是否能退

        // 订单状态需已付款
        if (thisOrderStatus != KylinTableStatusConst.ORDER_STATUS1) {
            throw new HttpException("订单状态信息有误");
        }
        // 订单支付状态需为已支付
        if (thisPayStatus != KylinTableStatusConst.ORDER_PAY_STATUS1) {
            throw new HttpException("订单支付信息有误");
        }
        // 传的快递费不能大于实际的快递费
        if (RefundPriceExpress > priceExpress) {
            throw new HttpException("快递费不能大于实际的快递费");
        }
        // 该订单正在退款或已有退款
        QueryWrapper<KylinOrderRefunds> refundingCountQuery = new QueryWrapper<KylinOrderRefunds>()
                .eq("order_tickets_id", orderTicketsId)
                .ne("status", KylinTableStatusConst.ORDER_REFUND_STATUS_CANCEL);
        for (String v : ticketEntityIds) {
            refundingCountQuery.like("order_ticket_entities_ids", v);
        }
        int refundingCount = kylinOrderRefundsMapper.selectCount(refundingCountQuery);
        if (refundingCount > 0) {
            throw new HttpException("该订单正在退款或已有退款");
        }

        // 该订单的入场人未付款/正在退款/已退款
        // TODO: 2021/5/27 出票未出票不知是否要处理
        /*QueryWrapper<KylinOrderTicketEntities> notPayCountQuery = new QueryWrapper<KylinOrderTicketEntities>()
                .in("order_ticket_entities_id", ticketEntityIds)
                .in("is_payment", new Integer[]{
                        KylinTableStatusConst.ENTITIES_IS_PAYMENT0,
                        KylinTableStatusConst.ENTITIES_IS_PAYMENT2,
                        KylinTableStatusConst.ENTITIES_IS_PAYMENT3});
        int notPayCount = kylinOrderTicketEntitiesMapper.selectCount(notPayCountQuery);*/

        // 选择退款的入场人是否正确
        // TODO: 2021/5/27 出票未出票不知是否要处理
        QueryWrapper<KylinOrderTicketEntities> choiceCountQuery = new QueryWrapper<KylinOrderTicketEntities>()
                .eq("order_id", orderTicketsId)
                .eq("is_payment", KylinTableStatusConst.ENTITIES_IS_PAYMENT1)
                .in("order_ticket_entities_id", ticketEntityIds);
        int choiceCount = kylinOrderTicketEntitiesMapper.selectCount(choiceCountQuery);
        int ticketEntityCount = ticketEntityIds.size();
        if (choiceCount < 0 || choiceCount != ticketEntityCount) {
            throw new HttpException("入场人订单有误或不存在");
        }

        boolean res = kylinRefundsStatusServiceImpl.orderTicketRefunding(
                refundApplyParam, orderInfo, orderTicketsId,
                RefundPriceExpress, priceExpress,
                ticketEntityCount, ticketEntityIds
        );
        if (res) {
            return true;
        } else {
            return false;
        }
    }

    public Boolean refundCancel(RefundApplyParam refundApplyParam) throws Exception {
        List<String> orderRefundsIdList = refundApplyParam.getIds();
        Integer[] orderRefundStatus = {KylinTableStatusConst.ORDER_REFUND_STATUS_APPLY, KylinTableStatusConst.ORDER_REFUND_STATUS_REJECT, KylinTableStatusConst.ORDER_REFUND_STATUS_REFUSE};
        List<KylinOrderRefunds> refundList = kylinOrderRefundsMapper.selectList(
                new QueryWrapper<KylinOrderRefunds>()
                        .eq("type", KylinTableStatusConst.ORDER_REFUND_TYPE_APPLY)
                        .in("order_refunds_id", orderRefundsIdList)
                        .in("status", orderRefundStatus)
        );
        if (orderRefundsIdList.size() != refundList.size()) {
            throw new Exception("订单需未审核、已驳回、已回绝，非自动退款订单");
        }

        boolean res = kylinRefundsStatusServiceImpl.orderTicketRefundCancel(refundList);
        if (res) {
            return true;
        } else {
            return false;
        }
    }

    public Boolean refundReapply(RefundApplyParam refundApplyParam) throws Exception {
        List<String> orderRefundsIdList = refundApplyParam.getIds();
        Integer[] orderRefundStatus = {KylinTableStatusConst.ORDER_REFUND_STATUS_REJECT, KylinTableStatusConst.ORDER_REFUND_STATUS_REFUSE};
        List<KylinOrderRefunds> refundList = kylinOrderRefundsMapper.selectList(
                new QueryWrapper<KylinOrderRefunds>()
                        .eq("type", KylinTableStatusConst.ORDER_REFUND_TYPE_APPLY)
                        .in("order_refunds_id", orderRefundsIdList)
                        .in("status", orderRefundStatus)
        );
        if (orderRefundsIdList.size() != refundList.size()) {
            throw new Exception("订单需一审驳回或二审驳回");
        }

        boolean res = kylinRefundsStatusServiceImpl.orderTicketRefundReapply(refundList);
        if (res) {
            return true;
        } else {
            return false;
        }
    }

    public Boolean refundApproved(RefundApplyParam refundApplyParam) throws Exception {
        List<String> orderRefundsIdList = refundApplyParam.getIds();
        if (orderRefundsIdList.size() <= 0) {
            throw new Exception("无退款订单");
        }
        String reject = refundApplyParam.getReject();
        Integer[] orderRefundStatus = {KylinTableStatusConst.ORDER_REFUND_STATUS_APPLY, KylinTableStatusConst.ORDER_REFUND_STATUS_REJECT, KylinTableStatusConst.ORDER_REFUND_STATUS_REFUSE};
        List<KylinOrderRefunds> refundList = kylinOrderRefundsMapper.selectList(
                new QueryWrapper<KylinOrderRefunds>()
                        .eq("type", KylinTableStatusConst.ORDER_REFUND_TYPE_APPLY)
                        .in("order_refunds_id", orderRefundsIdList)
                        .in("status", orderRefundStatus)
        );
        if (orderRefundsIdList.size() != refundList.size()) {
            throw new Exception("订单需未审核、已驳回、已回绝，请检查订单状态");
        }

        boolean res = kylinRefundsStatusServiceImpl.orderTicketRefundApproved(refundList, reject);
        if (res) {
            return true;
        } else {
            return false;
        }
    }

    public Boolean refundReject(RefundApplyParam refundApplyParam) throws Exception {
        List<String> orderRefundsIdList = refundApplyParam.getIds();
        String reject = refundApplyParam.getReject();
        Integer[] orderRefundStatus = {KylinTableStatusConst.ORDER_REFUND_STATUS_APPLY, KylinTableStatusConst.ORDER_REFUND_STATUS_APPROVED, KylinTableStatusConst.ORDER_REFUND_STATUS_REFUSE};
        List<KylinOrderRefunds> refundList = kylinOrderRefundsMapper.selectList(
                new QueryWrapper<KylinOrderRefunds>()
                        .eq("type", KylinTableStatusConst.ORDER_REFUND_TYPE_APPLY)
                        .in("order_refunds_id", orderRefundsIdList)
                        .in("status", orderRefundStatus)
        );
        if (orderRefundsIdList.size() != refundList.size()) {
            throw new Exception("订单需未审核、已审核、已回绝，请检查订单状态");
        }

        boolean res = kylinRefundsStatusServiceImpl.orderTicketRefundReject(refundList, reject);
        if (res) {
            return true;
        } else {
            return false;
        }
    }

    public Boolean refundUnfilled(RefundApplyParam refundApplyParam) throws Exception {
        List<String> orderRefundsIdList = refundApplyParam.getIds();
        String refuse = refundApplyParam.getRefuse();
        Integer[] orderRefundStatus = {KylinTableStatusConst.ORDER_REFUND_STATUS_APPROVED, KylinTableStatusConst.ORDER_REFUND_STATUS_ERROR};
        List<KylinOrderRefunds> refundList = kylinOrderRefundsMapper.selectList(
                new QueryWrapper<KylinOrderRefunds>()
                        .eq("type", KylinTableStatusConst.ORDER_REFUND_TYPE_APPLY)
                        .in("order_refunds_id", orderRefundsIdList)
                        .in("status", orderRefundStatus)
        );
        if (orderRefundsIdList.size() != refundList.size()) {
            throw new Exception("订单需已审核、退款失败，请检查订单状态");
        }

        boolean res = kylinRefundsStatusServiceImpl.orderTicketRefundUnfilled(refundList, refuse);
        if (res) {
            return true;
        } else {
            return false;
        }
    }

    public Boolean refundRefuse(RefundApplyParam refundApplyParam) throws Exception {
        List<String> orderRefundsIdList = refundApplyParam.getIds();
        String refuse = refundApplyParam.getRefuse();
        Integer[] orderRefundStatus = {KylinTableStatusConst.ORDER_REFUND_STATUS_APPROVED, KylinTableStatusConst.ORDER_REFUND_STATUS_ERROR};
        List<KylinOrderRefunds> refundList = kylinOrderRefundsMapper.selectList(
                new QueryWrapper<KylinOrderRefunds>()
                        .eq("type", KylinTableStatusConst.ORDER_REFUND_TYPE_APPLY)
                        .in("order_refunds_id", orderRefundsIdList)
                        .in("status", orderRefundStatus)
        );
        if (orderRefundsIdList.size() != refundList.size()) {
            throw new Exception("订单需已审核、退款失败，请检查订单状态");
        }

        boolean res = kylinRefundsStatusServiceImpl.orderTicketRefundRefuse(refundList, refuse);
        if (res) {
            return true;
        } else {
            return false;
        }
    }

    public Boolean refundCompleted(RefundApplyParam refundApplyParam) {
        return false;
    }

    public KylinOrderRefundsVo detail(String orderRefundId) {
        KylinOrderRefunds data = kylinOrderRefundsMapper.selectOne(
                new QueryWrapper<KylinOrderRefunds>()
                        .eq("order_refunds_id", orderRefundId)
        );
        KylinOrderRefundsVo kylinOrderRefundsVo = new KylinOrderRefundsVo();
        BeanUtils.copyProperties(data, kylinOrderRefundsVo);

        return kylinOrderRefundsVo;
    }

    public PageInfo<OrderRefundDao> refundList(RefundSearchParam refundSearchParam) {
        PageInfo<OrderRefundDao> pageInfoTmp = null;
        try {
            PageHelper.startPage(refundSearchParam.getPageNum(), refundSearchParam.getPageSize());
            List<OrderRefundDao> voList = kylinOrderRefundsMapper.misRefundList(BeanUtil.convertBeanToMap(refundSearchParam));
            for (OrderRefundDao item : voList) {
                item.setStatusName(item.getStatus());
            }
            pageInfoTmp = new PageInfo(voList);
        } catch (Exception e) {
            e.printStackTrace();
            return new PageInfo();
        }
        return pageInfoTmp;
    }

    public String refundCallback(RefundCallbackParam refundCallbackParam) {
        KylinOrderRefunds refundInfo = kylinOrderRefundsMapper.selectOne(
                new UpdateWrapper<KylinOrderRefunds>()
                        .eq("order_refund_code", refundCallbackParam.getOrder_refund_code())
        );
        if (refundInfo == null) {
            log.info("Failed:{}.RefundController refundCallback: 退款订单查询失败，编号{}", "KylinOrderRefundsServiceImplRefundCallback", refundCallbackParam.getOrder_refund_code());
            return "fail";
        }
        if (refundInfo.getStatus() == KylinTableStatusConst.ORDER_REFUND_STATUS_CANCEL) {
            log.info("Failed:{}.RefundController refundCallback: 退款订单已取消，编号{}", "KylinOrderRefundsServiceImplRefundCallback", refundCallbackParam.getOrder_refund_code());
            return "fail";
        }
        if (refundInfo.getStatus() == KylinTableStatusConst.ORDER_REFUND_STATUS_REFUNDED) {
            log.info("Failed:{}.RefundController refundCallback: 退款订单已退款，编号{}", "KylinOrderRefundsServiceImplRefundCallback", refundCallbackParam.getOrder_refund_code());
            return "success";
        }

        Integer status = refundCallbackParam.getStatus();
        if (1 == status) { // 退款成功
            boolean res = kylinRefundsStatusServiceImpl.orderTicketRefunded(refundCallbackParam, refundInfo);
            if (res) {
                return "success";
            } else {
                return "fail";
            }
        }
        if (0 == status) { // 退款失败
            KylinOrderRefunds kylinOrderRefunds = new KylinOrderRefunds();
            kylinOrderRefunds.setStatus(KylinTableStatusConst.ORDER_REFUND_STATUS_ERROR);
            kylinOrderRefunds.setRefundCode(refundCallbackParam.getRefund_code());
            kylinOrderRefunds.setRefundType(refundCallbackParam.getRefund_type());
            kylinOrderRefunds.setRefundId(refundCallbackParam.getRefund_id());
            kylinOrderRefunds.setRefundAt(refundCallbackParam.getRefund_at());
            kylinOrderRefunds.setRefundError(refundCallbackParam.getRefund_error());

            kylinOrderRefundsMapper.update(
                    kylinOrderRefunds,
                    new UpdateWrapper<KylinOrderRefunds>().eq("order_refund_code", refundCallbackParam.getOrder_refund_code())
            );
        }
        return "success";
    }

}