package com.pj.tb_goods_demand;

import com.pj.api.client.level_one_server.LevelOneServerInterface;
import com.pj.api.dto.GoodsDto;
import com.pj.api.dto.OrderDto;
import com.pj.common.core.exception.ServiceException;
import com.pj.current.dto.APPLoginUserInfo;
import com.pj.enummj.DeleteStatus;
import com.pj.tb_demand_quotation.TbDemandQuotation;
import com.pj.tb_demand_quotation.TbDemandQuotationMapper;
import com.pj.tb_goods_demand.vo.GoodsDemandVo;
import com.pj.tb_orders.TbOrders;
import com.pj.tb_orders.TbOrdersMapper;
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.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author Mechrevo
 * @Date 2023 08 03 16 49
 **/
@Service
@Transactional(rollbackFor = Exception.class)
public class MethodGoodsDemandService {

    @Autowired
    private TbDemandQuotationMapper tbDemandQuotationMapper;
    @Autowired
    private LevelOneServerInterface levelOneServerInterface;
    @Autowired
    private TbGoodsDemandMapper tbGoodsDemandMapper;
    @Autowired
    private TbOrdersMapper tbOrdersMapper;

    /**
     * 数据封装
     * 将List<TbGoodsDemand>  封装成   List<GoodsDemandVo>
     * @param list
     * @return
     */
    public List<GoodsDemandVo> setGoodsDemandVo(List<TbGoodsDemand> list, SoMap so){
        //创建返回值集合
        List<GoodsDemandVo> resultList = new ArrayList<>();

        //遍历集合
        list.forEach(item -> {

            //获取需求表ID
            Long id = item.getId();
            so.delete("id");
            //查询报价表
            so.put("demandId",id);
            //报价结果[0=待确认,1=确认,2=拒绝]
            so.put("quotationResult",1);
            so.put("deleteStatus",DeleteStatus.DELETE_STATUS_ON.getCode());
            List<TbDemandQuotation> tbDemandQuotations = tbDemandQuotationMapper.getList(so);

            //开始封装数据
            GoodsDemandVo goodsDemandVo = new GoodsDemandVo();

            //查询商品基本信息
            //GoodsDto goodsDto = levelOneServerInterface.getByGoodsId(item.getLevelOneGoodsId());
            // TODO: 2023/8/8 获取商品图片暂时不需要
            //goodsDemandVo.setGoodsImg(goodsDto.getAvatar());

            // 获取发布需求的详细信息
            goodsDemandVo.setGoodsDemandId(id);
            goodsDemandVo.setGoodsQuantity(item.getGoodsQuantity());
            goodsDemandVo.setGoodsDemandTime(item.getCreateTime());
            goodsDemandVo.setGoodsName(item.getGoodsName());
            goodsDemandVo.setIsOrders(item.getIsOrders());
            goodsDemandVo.setLevelOneGoodsId(item.getLevelOneGoodsId());
            goodsDemandVo.setAddressName(item.getAddressName());
            goodsDemandVo.setPhone(item.getPhone());
            goodsDemandVo.setGoodsNo(item.getGoodsNo());
            goodsDemandVo.setGoodsUnit(item.getGoodsUnit());
            goodsDemandVo.setName(item.getName());
            goodsDemandVo.setIsConfirm(item.getIsConfirm());
            goodsDemandVo.setTradeAreaId(item.getTradeAreaId());
            goodsDemandVo.setTradeAreaName(item.getTradeAreaName());
            goodsDemandVo.setIsRelease(item.getIsRelease());
            goodsDemandVo.setArrivalTime(item.getArrivalTime());
            // 获取已确认的报价信息
            if(tbDemandQuotations.size() > 0) {
                TbDemandQuotation tbDemandQuotation = tbDemandQuotations.get(0);
                goodsDemandVo.setDemandQuotationId(tbDemandQuotation.getId());
                goodsDemandVo.setCreateTime(tbDemandQuotation.getCreateTime());
                goodsDemandVo.setQuotation(tbDemandQuotation.getQuotation());
                goodsDemandVo.setRemark(tbDemandQuotation.getRemark());
                goodsDemandVo.setGroupName(tbDemandQuotation.getGroupName());
                goodsDemandVo.setLeaderId(tbDemandQuotation.getLeaderId());
                goodsDemandVo.setCreateName(tbDemandQuotation.getCreateName());
            }

            //执行添加
            resultList.add(goodsDemandVo);

        });

        return resultList;
    }

    /**
     * 执行同意处理
     * @param appLoginUserInfo 当前登录账号信息
     * @param goodsDemandId  需求表ID
     * @param demandQuotationId 报价表ID
     * @param purchaserRemark 二级收购商备注
     */
    public boolean agreeQuotation(APPLoginUserInfo appLoginUserInfo,Long goodsDemandId,Long demandQuotationId,String purchaserRemark){

        //关联一级市场订单表 根据创建时间 和 appUserID 进行查询
        List<OrderDto> orderDtos = levelOneServerInterface.selectOrderList( appLoginUserInfo.getLoginId());
        if(orderDtos.size() != 1)throw new ServiceException("一级市场暂未接单!");
        // 校验参数
        TbDemandQuotation tbDemandQuotation = tbDemandQuotationMapper.selectById(demandQuotationId); // 报价
        if(tbDemandQuotation == null)return false;
        TbGoodsDemand tbGoodsDemand = tbGoodsDemandMapper.selectById(goodsDemandId); //需求
        if(tbGoodsDemand == null)return false;
        //执行过程
        tbDemandQuotation.setQuotationResult(1); // 设置二级收购商处理结果 1表示同意
        tbDemandQuotation.setResultTime(new Date());  // 设置二级收购商处理时间
        tbDemandQuotation.setRemark("\n" + appLoginUserInfo.getLoginName() + ": " + purchaserRemark); // 商家备注
        int updateById = tbDemandQuotationMapper.updateById(tbDemandQuotation);
        //处理商家同意后的逻辑
        if(updateById == 1){

            //开始创建订单
            TbOrders tbOrders = new TbOrders();
            //一级市场关联二级市场
            tbOrders.setLevelOneOrderId(orderDtos.get(0).getId());
            //设置订单基本属性
            tbOrders.setGoodsId(tbGoodsDemand.getLevelOneGoodsId()); //一级市场海关允许销售商品表ID
            tbOrders.setGoodsName(tbGoodsDemand.getGoodsName());
            GoodsDto byGoodsId = levelOneServerInterface.getByGoodsId(tbGoodsDemand.getLevelOneGoodsId());
            if(byGoodsId != null)tbOrders.setGoodsFrom(byGoodsId.getSource());//产地
            tbOrders.setShipperPhone(tbDemandQuotation.getLinkPhone()); //联系电话
            tbOrders.setShipperName(tbDemandQuotation.getCreateName()); //卖家名称
            tbOrders.setTradeAreaId(tbDemandQuotation.getTradeAreaId()); //交易地区ID
            tbOrders.setTradeAreaName(tbDemandQuotation.getTradeAreaName());  //交易地区名称
            tbOrders.setCreateBy(appLoginUserInfo.getLoginId()); // 订单创建人 -- appUser表主键
            tbOrders.setPurchaserId(tbGoodsDemand.getPurchaserId());  //买家ID  商户表
            tbOrders.setPurchaserName(tbGoodsDemand.getPurchaserName()); // 买家名称 商户表
            tbOrders.setCreateName(tbDemandQuotation.getCreateName());
            tbOrders.setCreateTime(new Date()); // 创建时间
            tbOrders.setDeleteStatus(DeleteStatus.DELETE_STATUS_ON.getCode()); // 删除状态 默认可用
            int insert = tbOrdersMapper.insert(tbOrders);
            return insert == 1;

        }
        return false;
    }

    /**
     * 执行拒绝处理
     * @param appLoginUserInfo 当前登录账号信息
     * @param goodsDemandId  需求表ID
     * @param demandQuotationId 报价表ID
     * @param purchaserRemark 二级收购商备注
     * @return
     */
    public boolean refuseQuotation(APPLoginUserInfo appLoginUserInfo,Long goodsDemandId, Long demandQuotationId, String purchaserRemark){
        // 校验参数
        TbDemandQuotation tbDemandQuotation = tbDemandQuotationMapper.selectById(demandQuotationId);
        if(tbDemandQuotation == null)return false;
        TbGoodsDemand tbGoodsDemand = tbGoodsDemandMapper.selectById(goodsDemandId);
        if(tbGoodsDemand == null)return false;
        // 修改需求状态
        tbGoodsDemand.setIsOrders(0); // 将需求设置为未被下单
        int updateById = tbGoodsDemandMapper.updateById(tbGoodsDemand);
        //修改报价状态
        if(updateById == 1){
            tbDemandQuotation.setQuotationResult(2); // 2 表示拒绝
            tbDemandQuotation.setRemark("\n" + appLoginUserInfo.getLoginName() + ": " + purchaserRemark);
            // 设置二级市场收购商的响应时间
            tbDemandQuotation.setResultTime(new Date());
            int updateById1 = tbDemandQuotationMapper.updateById(tbDemandQuotation);
            return updateById1 == 1;
        }

        return false;

    }
}
