package com.jumeirah.common.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jumeirah.common.entity.McPlain;
import com.jumeirah.common.entity.Stroke;
import com.jumeirah.common.enums.StrokeStatusEnum;
import com.jumeirah.common.mapper.StrokeMapper;
import com.jumeirah.common.mq.Queue;
import com.jumeirah.common.param.McStrokePageParam;
import com.jumeirah.common.param.McStrokePaymentPageParam;
import com.jumeirah.common.param.StrokeCompleteParam;
import com.jumeirah.common.param.StrokePageParam;
import com.jumeirah.common.param.StrokeQuotedPriceParam;
import com.jumeirah.common.service.StrokeService;
import com.jumeirah.common.vo.McStrokePaymentQueryVo;
import com.jumeirah.common.vo.McStrokeQueryVo;
import com.jumeirah.common.vo.StrokeDetailVo;
import com.jumeirah.common.vo.StrokeQueryVo;
import io.geekidea.springbootplus.framework.common.api.ApiCode;
import io.geekidea.springbootplus.framework.common.api.ApiResult;
import io.geekidea.springbootplus.framework.common.service.impl.BaseServiceImpl;
import io.geekidea.springbootplus.framework.core.pagination.PageInfo;
import io.geekidea.springbootplus.framework.core.pagination.Paging;
import io.geekidea.springbootplus.framework.shiro.jwt.JwtToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;

/**
 * 行程表 服务实现类
 *
 * @author wei
 * @since 2020-09-29
 */
@Slf4j
@Service
public class StrokeServiceImpl extends BaseServiceImpl<StrokeMapper, Stroke> implements StrokeService {

    @Autowired
    private Queue queue;

    @Autowired
    private StrokeMapper strokeMapper;
    @Autowired
    private McPlainServiceImpl mcPlainService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveStroke(Stroke stroke) throws Exception {
        final boolean save = super.save(stroke);
        if (save) {//推送订单到客服系统
            queue.pushOrder(JSON.toJSONString(baseMapper.getStrokeInfo(stroke.getMcId(), stroke.getId())));
        }
        return save;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateStroke(Stroke stroke) throws Exception {
        return super.updateById(stroke);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteStroke(Long id) throws Exception {
        JwtToken jwtToken = (JwtToken) SecurityUtils.getSubject().getPrincipal();
        Stroke byId = super.getById(id);

        // 如果已删除 直接返回true
        if (byId == null) {
            return true;
        }

        // 判断该记录是否属于此用户
        if (!byId.getUserId().equals(jwtToken.getUserId())) {
            return false;
        }

        return super.removeById(id);
    }

    @Override
    public boolean cancelStroke(Long id) throws Exception {
        JwtToken jwtToken = (JwtToken) SecurityUtils.getSubject().getPrincipal();
        Stroke byId = super.getById(id);
        // 判断该记录是否属于此用户
        if (!byId.getUserId().equals(jwtToken.getUserId())) {
            return false;
        }
        Stroke stroke = new Stroke();
        stroke.setId(id);
        stroke.setStatus(StrokeStatusEnum.CANCEL.getCode());
        return super.updateById(stroke);
    }

    @Override
    public StrokeDetailVo getStrokeById(Long id) throws Exception {
        return strokeMapper.getStrokeById(id);
    }

    @Override
    public Paging<StrokeQueryVo> getStrokePageList(StrokePageParam strokePageParam, String language) throws Exception {
//        Page<StrokeQueryVo> page = new PageInfo<>(strokePageParam, OrderItem.asc(getLambdaColumn(Stroke::getCreateTime)));
        Page<StrokeQueryVo> page = new PageInfo<>(strokePageParam);
        JwtToken jwtToken = (JwtToken) SecurityUtils.getSubject().getPrincipal();
        // 查询已完成 需要额外查询已取消状态
        if (strokePageParam.getStatus().equals(StrokeStatusEnum.COMPLETED.getCode())) {
            IPage<StrokeQueryVo> iPage = strokeMapper.getStrokePageListWithFinish(page, strokePageParam, jwtToken.getUserId(), language);
            return new Paging<StrokeQueryVo>(iPage);
        }
        IPage<StrokeQueryVo> iPage = strokeMapper.getStrokePageList(page, strokePageParam, jwtToken.getUserId(), language);
        return new Paging<StrokeQueryVo>(iPage);
    }

    @Override
    public Paging<McStrokeQueryVo> getMcStrokePageList(McStrokePageParam mcStrokePageParam, String language) {
        Page<StrokeQueryVo> page = new PageInfo<>(mcStrokePageParam);
        JwtToken jwtToken = (JwtToken) SecurityUtils.getSubject().getPrincipal();
        IPage<McStrokeQueryVo> mcStrokePageList = strokeMapper.getMcStrokePageList(page, mcStrokePageParam, jwtToken.getMcId(), language);
        return new Paging<McStrokeQueryVo>(mcStrokePageList);
    }

    @Override
    public Paging<McStrokePaymentQueryVo> getPaymentPageList(McStrokePaymentPageParam mcStrokePaymentPageParam) {
        Page<StrokeQueryVo> page = new PageInfo<>(mcStrokePaymentPageParam);
        JwtToken jwtToken = (JwtToken) SecurityUtils.getSubject().getPrincipal();
        IPage<McStrokePaymentQueryVo> mcStrokePageList = strokeMapper.getPaymentPageList(page, mcStrokePaymentPageParam, jwtToken.getMcId());
        return new Paging<McStrokePaymentQueryVo>(mcStrokePageList);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult<Boolean> quotedPrice(StrokeQuotedPriceParam strokeQuotedPriceParam) throws Exception {
        //先判断商家机型是否空闲
        JwtToken jwtToken = (JwtToken) SecurityUtils.getSubject().getPrincipal();
        McPlain mcPlain = mcPlainService.getOne(new QueryWrapper<McPlain>().lambda()
                .eq(McPlain::getPtId, strokeQuotedPriceParam.getPlainTypeId())
                .eq(McPlain::getMcId, jwtToken.getMcId())
                .gt(McPlain::getIdleNum, 0)
                .eq(McPlain::getStatus, 0)
        );
        if (mcPlain == null) {
            return ApiResult.result(ApiCode.MC_PLANE_NOT_AVAILABLE, false);
        }
        Stroke stroke = new Stroke();
        BeanUtils.copyProperties(strokeQuotedPriceParam, stroke);
        stroke.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        boolean flag = this.updateStroke(stroke);
        if (flag) {
            //报价完成后，商家飞机表空闲数量-1
            McPlain newMcPlain = new McPlain();
            newMcPlain.setId(mcPlain.getId())
                    .setIdleNum((mcPlain.getIdleNum() - 1) >= 0 ? (mcPlain.getIdleNum() - 1) : 0);
            flag = mcPlainService.updateMcPlain(newMcPlain);
        }
        return ApiResult.result(flag);
    }

    @Override
    public ApiResult<Boolean> completeStroke(StrokeCompleteParam strokeCompleteParam) throws Exception {
        Stroke stroke = new Stroke();
        stroke.setId(strokeCompleteParam.getId())
                .setUpdateTime(new Timestamp(System.currentTimeMillis()))
                .setStatus(StrokeStatusEnum.COMPLETED.getCode());
        boolean flag = this.updateStroke(stroke);
        Stroke newStroke = this.getById(strokeCompleteParam.getId());
        //先判断商家机型是否存在
        JwtToken jwtToken = (JwtToken) SecurityUtils.getSubject().getPrincipal();
        McPlain mcPlain = mcPlainService.getOne(new QueryWrapper<McPlain>().lambda()
                .eq(McPlain::getPtId, newStroke.getPlainTypeId())
                .eq(McPlain::getMcId, jwtToken.getMcId())
        );
        if (mcPlain != null) {
            //行程完成后需要给商家飞机空闲数量+1
            McPlain newMcPlain = new McPlain();
            newMcPlain.setId(mcPlain.getId())
                    .setIdleNum((mcPlain.getIdleNum() + 1) > newMcPlain.getAmount() ? newMcPlain.getAmount()
                            : (mcPlain.getIdleNum() + 1));
            flag = mcPlainService.updateMcPlain(newMcPlain);
        }
        return ApiResult.result(flag);
    }
}
