package com.pj.tb_demand_quotation;

import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pj.api.client.admin.AdminInterface;
import com.pj.api.client.level_one_server.LevelOneServerInterface;
import com.pj.api.dto.MessageDto;
import com.pj.api.dto.OrderDto;
import com.pj.api.dto.PeopleDto;
import com.pj.common.core.exception.ServiceException;
import com.pj.current.dto.APPLoginUserInfo;
import com.pj.current.satoken.StpAPPUserUtil;
import com.pj.enummj.DeleteStatus;
import com.pj.retry.SmsRetryService;
import com.pj.tb_demand_quotation.param.DemandQuotationParam;
import com.pj.tb_goods_demand.TbGoodsDemand;
import com.pj.tb_goods_demand.TbGoodsDemandMapper;
import com.pj.tb_purchaser.TbPurchaser;
import com.pj.tb_purchaser.TbPurchaserMapper;
import com.pj.utils.so.SoMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Service: tb_demand_quotation -- 一级市场组长需求抢购表
 *
 * @author yzs
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class TbDemandQuotationService extends ServiceImpl<TbDemandQuotationMapper, TbDemandQuotation> implements IService<TbDemandQuotation> {

    /**
     * 底层 Mapper 对象
     */
    @Autowired
    TbDemandQuotationMapper tbDemandQuotationMapper;
    /**
     * 远程调用
     */
    @Autowired
    private LevelOneServerInterface levelOneServerInterface;

    /**
     * 远程调用
     */
    @Autowired
    private AdminInterface adminInterface;

    /**
     * 失败重试机制
     */
    @Autowired
    private SmsRetryService smsRetryService;
    /**
     * 二级收购商需求
     */
    @Autowired
    private TbGoodsDemandMapper tbGoodsDemandMapper;
    /**
     * 二级市场收购商
     */
    @Autowired
    private TbPurchaserMapper tbPurchaserMapper;

    /**
     * 增
     */
    void add(TbDemandQuotation t) {
        save(t);
    }

    /**
     * 删
     */
    void delete(Long id) {
        removeById(id);
    }

    /**
     * 改
     */
    void update(TbDemandQuotation t) {
        updateById(t);

    }

    /**
     * 查
     */
    TbDemandQuotation getById(Long id) {
        return super.getById(id);
    }

    /**
     * 查集合 - 根据条件（参数为空时代表忽略指定条件）
     */
    List<TbDemandQuotation> getList(SoMap so) {
        return tbDemandQuotationMapper.getList(so);
    }


    /**
     * 互市组组长接单
     *
     * @param demandQuotationParam
     */
    public boolean quotation(DemandQuotationParam demandQuotationParam) throws Exception {

        //获取并判断当前登陆人
        APPLoginUserInfo appLoginInfo = StpAPPUserUtil.getAPPLoginInfo();
        if (appLoginInfo == null || appLoginInfo.getLoginId() == null)
            throw new ServiceException("当前登录账号信息已失效!");
        //将需求改成已被报价状态
        demandQuotationParam.setIsOrders(1);
        //接单前判断组长是否当天在一级市场接单
        List<OrderDto> dtoList = levelOneServerInterface.selectOrderList(appLoginInfo.getLoginId());
        if(dtoList.size() != 1)throw new ServiceException("您今天还未在一级市场接单哟~");
        //获取边民组信息
        PeopleDto rpcById = levelOneServerInterface.getRpcById(appLoginInfo.getFk());
        if (rpcById == null) throw new ServiceException("边民组信息有误!");
        //判断组长身份
        if (rpcById.getRole() != 2) throw new ServiceException("您当前身份不是组长,无法抢单报价!");
        //执行接单报价
        TbDemandQuotation tbDemandQuotation = new TbDemandQuotation();
        tbDemandQuotation.setQuotationResult(0); //默认待商家确认
        tbDemandQuotation.setPurchaserId(demandQuotationParam.getPurchaserId()); // 商家ID
        tbDemandQuotation.setDemandId(demandQuotationParam.getGoodsDemandId()); //需求表ID
        tbDemandQuotation.setQuotation(demandQuotationParam.getPrice()); // 报价
        tbDemandQuotation.setCreateBy(appLoginInfo.getLoginId()); //创建人登陆表主键
        tbDemandQuotation.setRemark(appLoginInfo.getLoginName() + ": " + demandQuotationParam.getRemark()); //报价备注
        tbDemandQuotation.setLeaderId(appLoginInfo.getFk());  //边民表主键
        tbDemandQuotation.setGroupName(rpcById.getGroupName()); // 互市组组名
        tbDemandQuotation.setCreateTime(new Date()); //创建时间
        tbDemandQuotation.setGroupId(rpcById.getGroupId());
        tbDemandQuotation.setDeleteStatus(DeleteStatus.DELETE_STATUS_ON.getCode()); // 删除状态默认可用
        tbDemandQuotation.setCreateName(appLoginInfo.getLoginName());
        int insert = tbDemandQuotationMapper.insert(tbDemandQuotation);
        if (insert == 1) {
            //修改二级市场收购商的需求状态
            TbGoodsDemand tbGoodsDemand = tbGoodsDemandMapper.selectById(demandQuotationParam.getGoodsDemandId());
            if (tbGoodsDemand == null || tbGoodsDemand.getIsOrders() == 1 || tbGoodsDemand.getDeleteStatus() == 0)
                throw new RuntimeException("二级市场收购商需求订单状态异常!");
            //执行修改二级市场收购商需求状态
            tbGoodsDemand.setIsOrders(demandQuotationParam.getIsOrders());
            int updateById = tbGoodsDemandMapper.updateById(tbGoodsDemand);
            if (updateById != 1) throw new RuntimeException("无法进行报价!");
            //短信提示二级市场收购商,需求已报价,进入app进行确认接单
            TbPurchaser tbPurchaser = tbPurchaserMapper.selectById(tbGoodsDemand.getPurchaserId());
            if (tbPurchaser == null) throw new RuntimeException("二级商户信息异常!~");
            //todo:给收购商发一条接单消息
            MessageDto dto = new MessageDto();
            dto.setUrl("/pages/market/two/purchaser/buy/list");
            dto.setUserId(tbGoodsDemand.getPurchaserId());
            dto.setContents("你的发布的《" + tbGoodsDemand.getGoodsName() + "》已有人接单,请及时确认。");
            adminInterface.messageSave(dto);
            //todo:发送短信
//			smsRetryService.sendSmsMsg(tbPurchaser.getContact());
            return true;
        }
        throw new RuntimeException("抢单报价失败!");
    }


}
