package cn.com.ty.lift.ud.liftCaseAppeal.service.impl;

import java.math.BigDecimal;
import java.util.List;

import cn.com.ty.lift.ud.userInfo.mapper.entity.UserInfoEntity;
import cn.com.ty.lift.ud.userInfo.service.IUserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.com.ty.lift.common.model.PushMessage;
import cn.com.ty.lift.common.model.PushUserInfo;
import cn.com.ty.lift.ud.chat.mapper.entity.LiftCaseEntity;
import cn.com.ty.lift.ud.chat.service.ILiftCaseService;
import cn.com.ty.lift.ud.common.RandomizingID;
import cn.com.ty.lift.ud.coupon.mapper.CouponMapper;
import cn.com.ty.lift.ud.coupon.mapper.entity.Coupon;
import cn.com.ty.lift.ud.liftCaseAppeal.controller.query.LiftCaseAppealQuery;
import cn.com.ty.lift.ud.liftCaseAppeal.mapper.LiftCaseAppealMapper;
import cn.com.ty.lift.ud.liftCaseAppeal.mapper.entity.CancelSeasonDto;
import cn.com.ty.lift.ud.liftCaseAppeal.mapper.entity.LiftCaseAppealEntity;
import cn.com.ty.lift.ud.liftCaseAppeal.service.ILiftCaseAppealService;
import cn.com.ty.lift.ud.payment.mapper.entity.UserBillEntity;
import cn.com.ty.lift.ud.payment.service.IUserBillService;
import cn.com.ty.lift.ud.userAccount.service.IUserAccountService;
import cn.com.xwy.boot.web.dto.RestResponse;

/**
 * 诊单申诉 -ServiceImpl
 *
 * @author Xson
 * @date 2020-04-23
 */
@Service
@Transactional
public class LiftCaseAppealServiceImpl extends ServiceImpl<LiftCaseAppealMapper, LiftCaseAppealEntity>
    implements ILiftCaseAppealService {

    @Autowired
    private LiftCaseAppealMapper liftCaseAppealMapper;

    @Autowired
    private IUserBillService iUserBillService;

    @Autowired
    private ILiftCaseService iLiftCaseService;

    @Autowired
    private IUserInfoService iUserInfoService;

    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    private @Autowired IUserAccountService iUserAccountService;

    private @Autowired CouponMapper couponMapper;

    @Override
    public RestResponse selectByExample(LiftCaseAppealQuery query) {
        IPage page = query.page();
        List<LiftCaseAppealEntity> list = liftCaseAppealMapper.selectByQuery(query.condition(), query);
        page.setRecords(list);
        int total = liftCaseAppealMapper.countByQuery(query.condition());
        page.setTotal(total);
        return RestResponse.success(page, "Select successfully");
    }

    /**
     * 驳回
     * 
     * @param cancelDto
     */
    @Override
    public void cancelById(CancelSeasonDto cancelDto) {
        // 查询被驳回的问题
        LiftCaseAppealEntity infoById = liftCaseAppealMapper.selectById(cancelDto.getId());
        if (infoById != null) {
            // 修改状态为 驳回，并加上驳回理由
            infoById.setStatuz(2);
            infoById.setCancelSeason(cancelDto.getCancelSeason());
            liftCaseAppealMapper.updateById(infoById);
            PushUserInfo pushUserInfo = iUserAccountService.getPushUserInfoByUserId(infoById.getAppealerId().toString());
            PushMessage pushMessage = PushMessage.auditNotice(pushUserInfo.getUserName(), "诊单申诉", "已驳回");
            pushMessage.sendTokenOnPlatform(jmsMessagingTemplate, pushUserInfo);
            // 修改订单状态为待评价
            LiftCaseEntity byId = iLiftCaseService.getById(infoById.getDataId());
            if (null != byId) {
                if (byId.getDataTable() == 1) {
                    iLiftCaseService.updateStatusById(byId.getId(), 3);
                } else {
                    iLiftCaseService.updateStatusById(byId.getId(), 4);
                }
            }
        }

    }

    /**
     * 结束申诉
     * 
     * @param id
     */
    @Override
    public void endAppeal(Long id) {
        liftCaseAppealMapper.endAppeal(id);
        LiftCaseAppealEntity selectById = liftCaseAppealMapper.selectById(id);
        if (null != selectById) {
            // 修改订单状态为待评价
            LiftCaseEntity byId = iLiftCaseService.getById(selectById.getDataId());
            if (null != byId) {
                if (byId.getDataTable() == 1) {
                    iLiftCaseService.updateStatusById(byId.getId(), 3);
                } else {
                    iLiftCaseService.updateStatusById(byId.getId(), 4);
                }
            }
        }

    }

    /**
     * 退款
     * 
     * @param id
     *            申诉ID
     * @param userId
     *            用户ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResponse refund(Long id, Long userId) {
        LiftCaseAppealEntity selectById = liftCaseAppealMapper.selectById(id);
        LiftCaseEntity byId = null;
        if (null != selectById) {
            byId = iLiftCaseService.getById(selectById.getDataId());
            if (null != byId) {
                if (byId.getDataTable() == 1) {
                    iLiftCaseService.updateStatusById(byId.getId(), 6);
                } else {
                    iLiftCaseService.updateStatusById(byId.getId(), 6);
                }
            }
        } else {
            return RestResponse.fail("无法获取诊单支付信息");
        }

        // BigDecimal balance = new BigDecimal("0");
        // 修改状态为已退款
        liftCaseAppealMapper.refund(id);
        // 查询支付信息
        BigDecimal serviceCost = byId.getServiceCost();
        if (byId.getCouponId() != null) {
            Coupon byCouponId = couponMapper.getByCouponId(byId.getCouponId());
            if (byCouponId != null) {
                serviceCost = serviceCost.subtract(byCouponId.getDiscount());
            }
        }
        if (byId.getRedEnvelopeId() != null) {
            Coupon byCouponId = couponMapper.getByCouponId(byId.getRedEnvelopeId());
            if (byCouponId != null) {
                serviceCost = serviceCost.subtract(byCouponId.getPrice());
            }
        }

        if (serviceCost.compareTo(new BigDecimal("0")) == 1) {
            iUserInfoService.rechargePayBalance(userId, serviceCost);

            // 用户账户流水记录，余额相应增加
            // BigDecimal latestBalanceList = iUserBillService.getLatestBalance(userId);
            UserInfoEntity byUserId = iUserInfoService.getByUserId(userId);
            UserBillEntity userBillEntity = new UserBillEntity();
            userBillEntity.setBalance(byUserId.getBalance());
            userBillEntity.setUserId(userId);
            userBillEntity.setTargetUserId(byId.getChargerId());
            userBillEntity.setType(2);
            userBillEntity.setAmount(serviceCost);
            userBillEntity.setBusinessType(10);
            userBillEntity.setDescr("申诉退款");
            // 生成流水号
            String billId = RandomizingID.getBillId();
            userBillEntity.setFlowNum(billId);
            iUserBillService.save(userBillEntity);
        }
        // todo 发送消息给该用户
        PushUserInfo pushUserInfo = iUserAccountService.getPushUserInfoByUserId(selectById.getAppealerId().toString());
        PushMessage pushMessage = PushMessage.auditNotice(pushUserInfo.getUserName(), "诊单申诉", "已退款");
        pushMessage.sendTokenOnPlatform(jmsMessagingTemplate, pushUserInfo);
        return RestResponse.success(null, "退款成功");
    }

    /**
     * 重写新增的方法 可能存在先取消申诉，然后重新发起的情况，一个诊单只能申诉一次 查询当前会话是否申诉过，如果状态为已结束，就是取消申诉导致的，直接修改状态为未结束 如果不存在，直接新增
     * 
     * @param entity
     * @return
     */
    @Override
    public RestResponse create(LiftCaseAppealEntity entity) {
        if (null != entity.getDataId()) {
            LiftCaseAppealEntity byDataId = liftCaseAppealMapper.getByDataId(entity.getDataId());
            if (null == byDataId) {
                // 修改订单状态为申诉
                LiftCaseEntity byId = iLiftCaseService.getById(entity.getDataId());
                if (null != byId) {
                    if (byId.getDataTable() == 1) {
                        iLiftCaseService.updateStatusById(byId.getId(), 7);
                    } else {
                        iLiftCaseService.updateStatusById(byId.getId(), 7);
                    }
                }
                // 当前诊单没有申诉过，直接新增
                entity.setStatuz(1);
                int insert = liftCaseAppealMapper.insert(entity);
                if (insert == 1) {
                    // 消息
                    PushUserInfo pushUserInfo =
                        iUserAccountService.getPushUserInfoByUserId(byId.getChargerId().toString());
                    PushMessage pushMessage = PushMessage.orderChargeStatus("被申诉");
                    pushMessage.sendTokenOnPlatform(jmsMessagingTemplate, pushUserInfo);

                    return RestResponse.success(null, "新增成功");
                } else {
                    return RestResponse.fail("新增失败");
                }
            }
            if (null != byDataId) {
                if (byDataId.getStatuz() == 3) {
                    // 当前诊单申诉过，并且状态为已完成,直接修改状态为未结束
                    entity.setStatuz(1);
                    int byId = liftCaseAppealMapper.updateByDataId(entity.getDataId());
                    if (byId == 1) {
                        return RestResponse.success(null, "新增成功");
                    } else {
                        return RestResponse.fail("新增失败");
                    }
                } else {
                    // 当前诊单不能申诉
                    return RestResponse.fail("当前诊单不能申诉");
                }

            }

        }
        return RestResponse.fail("诊单ID无数据");
    }

    @Override
    public LiftCaseAppealEntity getByDataId(Long id) {
        return liftCaseAppealMapper.getByDataId(id);
    }
}
