package com.pj.tb_goods_demand;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
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.dto.MessageDto;
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.enummj.IsOrders;
import com.pj.enummj.OrderStatus;
import com.pj.enummj.ReleaseStatus;
import com.pj.tb_demand_quotation.TbDemandQuotation;
import com.pj.tb_demand_quotation.TbDemandQuotationMapper;
import com.pj.tb_demand_quotation.TbDemandQuotationService;
import com.pj.tb_goods_demand.vo.GoodsDemandVo;
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.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Service: tb_goods_demand -- 二级收购商需求发布表
 *
 * @author yzs
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class TbGoodsDemandService extends ServiceImpl<TbGoodsDemandMapper, TbGoodsDemand> implements IService<TbGoodsDemand> {

    /**
     * 底层 Mapper 对象
     */
    @Autowired
    TbGoodsDemandMapper tbGoodsDemandMapper;
    @Autowired
    private TbDemandQuotationService demandQuotationService;

    @Autowired
    private MethodGoodsDemandService methodGoodsDemandService;

    @Autowired
    TbDemandQuotationMapper tbDemandQuotationMapper;

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

    /**
     * 二级市场收购商发布需求
     */
    void add(TbGoodsDemand t) {
        //获取并判断当前登陆人
        APPLoginUserInfo appLoginInfo = StpAPPUserUtil.getAPPLoginInfo();
        if (appLoginInfo == null || appLoginInfo.getLoginId() == null)
            throw new ServiceException("当前登录账号信息已失效!");
        //设置基本状态
        t.setIsOrders(0); // 0= 未被下单
        t.setIsConfirm(0);// 收购商未确认
        t.setPurchaserId(appLoginInfo.getFk());
        t.setCreateBy(appLoginInfo.getLoginId());
        t.setCreateName(appLoginInfo.getLoginName());
        t.setDeleteStatus(DeleteStatus.DELETE_STATUS_ON.getCode());
        t.setCreateTime(new Date());
        save(t);
    }

    /**
     * 删
     */
    void delete(Long id) {
        //防止在被报价的情况下删除需求
        TbGoodsDemand tbGoodsDemand = tbGoodsDemandMapper.selectById(id);
        if(tbGoodsDemand == null)
            throw new ServiceException("需求状态异常!");
        //执行
        if(tbGoodsDemand.getIsOrders().equals(IsOrders.IS_ORDERS_ONE.getCode()))
            throw new ServiceException("您的需求[ " + tbGoodsDemand.getGoodsName() + " ]已被报价,请先处理报价再来进行删除。 ");
        removeById(id);
    }

    /**
     * 改
     */
    void update(TbGoodsDemand t) {
        //获取并判断当前登陆人
        APPLoginUserInfo appLoginInfo = StpAPPUserUtil.getAPPLoginInfo();
        if (appLoginInfo == null || appLoginInfo.getLoginId() == null)
            throw new ServiceException("当前登录账号信息已失效!");
        //执行修改
        t.setIsOrders(0); // 0= 未被下单
        t.setIsConfirm(0);// 收购商未确认
        t.setUpdateBy(appLoginInfo.getLoginId());
        t.setUpdateName(appLoginInfo.getLoginName());
        t.setUpdateTime(new Date());
        updateById(t);

    }

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

    /**
     * pc端:专供给一级市场查看的需求列表
     */
    List<TbGoodsDemand> getList(SoMap so) {
        return tbGoodsDemandMapper.getList(so);
    }

    /**
     * app端:专供给二级市场查看的需求列表
     */
    List<TbGoodsDemand> getAppList(SoMap so) {
        //获取并判断当前登陆人
        APPLoginUserInfo appLoginInfo = StpAPPUserUtil.getAPPLoginInfo();
        if (appLoginInfo == null || appLoginInfo.getLoginId() == null)
            throw new ServiceException("当前登录账号信息已失效!");
        //获取当前收购商发布的需求
        so.put("purchaserId", appLoginInfo.getFk());
        so.put("sortType", 10); //根据创建日期降序
        so.put("deleteStatus", DeleteStatus.DELETE_STATUS_ON.getCode()); // 状态可用
        return tbGoodsDemandMapper.getList(so);
    }

    /**
     * 二级收购商查看需求发布需求详情
     *
     * @return
     */
    public GoodsDemandVo goodsDemandList(SoMap so) {
        so.put("deleteStatus", DeleteStatus.DELETE_STATUS_ON.getCode());
        List<TbGoodsDemand> goodsDemandMapperList = tbGoodsDemandMapper.getList(so);

        //匹配已被报价的列表
        if (goodsDemandMapperList.size() > 0) {
            List<GoodsDemandVo> goodsDemandVos = methodGoodsDemandService.setGoodsDemandVo(goodsDemandMapperList, so);
            if (goodsDemandVos.size() > 0) return goodsDemandVos.get(0);
        }
        return null;
    }

    /**
     * 二级市场收购商处理需求订单
     *
     * @param disposeStatus     处理状态[0=待处理,1=通过,2=拒绝]
     * @param goodsDemandId     需求表主键
     * @param demandQuotationId 报价表主键
     */
    public boolean disposeOrders(Integer disposeStatus, Long goodsDemandId, Long demandQuotationId, String purchaserRemark) {
        //获取并判断当前登陆人
        APPLoginUserInfo appLoginInfo = StpAPPUserUtil.getAPPLoginInfo();
        if (appLoginInfo == null || appLoginInfo.getLoginId() == null)
            throw new ServiceException("当前登录账号信息已失效!");

        //同意则开始创建订单,不同意则修改报价表和需求表状态
        if (disposeStatus == 1) {
            return methodGoodsDemandService.agreeQuotation(appLoginInfo, goodsDemandId, demandQuotationId, purchaserRemark);
        } else if (disposeStatus == 2) {
            return methodGoodsDemandService.refuseQuotation(appLoginInfo, goodsDemandId, demandQuotationId, purchaserRemark);
        }
        throw new RuntimeException("服务器繁忙~");
    }

    boolean refuse(TbGoodsDemand t) {
        t.setIsOrders(OrderStatus.ORDER_STATUS_ZERO.getCode());//未被接单
        t.setIsRelease(ReleaseStatus.RELEASE_STATUS_PUBLISH.getCode());//已发布
        t.setIsConfirm(0);//收购商未确认
        update(t);

        LambdaUpdateWrapper<TbDemandQuotation> wrapper = new LambdaUpdateWrapper<>();
        //报价结果[0=待确认,1=确认,2=拒绝]
        wrapper.set(TbDemandQuotation::getQuotationResult, 2);
        wrapper.eq(TbDemandQuotation::getDemandId, t.getId());
        boolean update = demandQuotationService.update(wrapper);

        LambdaQueryWrapper<TbDemandQuotation> wra = new LambdaQueryWrapper<>();
        wra.eq(TbDemandQuotation::getDemandId, t.getId());
        wra.orderByDesc(TbDemandQuotation::getCreateTime);
        List<TbDemandQuotation> quotationList=tbDemandQuotationMapper.selectList(wra);

        //todo:给组长发一条拒绝的接单消息
        MessageDto dto = new MessageDto();
        dto.setUserId(quotationList.get(0).getLeaderId());
        dto.setContents("抱歉! 你接单的《" + t.getGoodsName()+ "》已被商户拒绝,请重新接单或换一家商品。");
        adminInterface.messageSave(dto);

        return update;
    }
}
