package com.pj.tb_orders;

import cn.dev33.satoken.stp.StpUtil;
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.client.async_server.AsyncServerInterface;
import com.pj.api.client.level_one_server.LevelOneServerInterface;
import com.pj.api.dto.GoodsDto;
import com.pj.api.dto.MessageDto;
import com.pj.api.dto.OrdersDto;
import com.pj.common.core.text.Convert;
import com.pj.common.core.utils.StringUtils;
import com.pj.current.config.SystemObject;
import com.pj.current.dto.APPLoginUserInfo;
import com.pj.current.satoken.StpAPPUserUtil;
import com.pj.enummj.DataType;
import com.pj.enummj.DeleteStatus;
import com.pj.enummj.OrderStatus;
import com.pj.tb_demand_quotation.TbDemandQuotation;
import com.pj.tb_demand_quotation.TbDemandQuotationService;
import com.pj.tb_fee_item.TbFeeItem;
import com.pj.tb_fee_item.TbFeeItemService;
import com.pj.tb_fee_item_record.TbFeeItemRecord;
import com.pj.tb_fee_item_record.TbFeeItemRecordService;
import com.pj.tb_goods_demand.TbGoodsDemand;
import com.pj.tb_goods_demand.TbGoodsDemandService;
import com.pj.tb_goods_demand.vo.GoodsDemandVo;
import com.pj.tb_orders_cart.TbOrdersCart;
import com.pj.tb_orders_cart.TbOrdersCartMapper;
import com.pj.tb_purchaser.TbPurchaser;
import com.pj.tb_purchaser.TbPurchaserMapper;
import com.pj.utils.so.SoMap;
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.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Service: tb_orders -- 订单表
 *
 * @author qzy
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class TbOrdersService extends ServiceImpl<TbOrdersMapper, TbOrders> implements IService<TbOrders> {

    /**
     * 底层 Mapper 对象
     */
    @Autowired
    TbOrdersMapper tbOrdersMapper;
    @Autowired
    private TbPurchaserMapper tbPurchaserMapper;
    @Autowired
    private LevelOneServerInterface levelOneServerInterface;
    @Autowired
    private TbGoodsDemandService goodsDemandService;
    @Autowired
    private TbDemandQuotationService demandQuotationService;
    @Autowired
    private AsyncServerInterface asyncServerInterface;
    @Autowired
    TbOrdersCartMapper tbOrdersCartMapper;

    @Autowired
    TbFeeItemService tbFeeItemService;

    @Autowired
    TbFeeItemRecordService tbFeeItemRecordService;

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

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

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

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

    }

    /**
     * 改 收购商购买
     */
    boolean purchaserBuy(SoMap so) {
        // 获取app登录用户
        APPLoginUserInfo appLoginInfo = StpAPPUserUtil.getAPPLoginInfo();

        // 获取收购商ID与名称
        TbPurchaser purchaser = tbPurchaserMapper.selectById(appLoginInfo.getFk());
        if (null == purchaser) throw new RuntimeException("当前收购商账号异常，请重新登录或联系管理员！");

        String idStr = so.getString("ids");
        if (StringUtils.isEmpty(idStr)) throw new RuntimeException("当前购买操作异常，请重新登录或联系管理员！");

        Long[] idArr = Convert.toLongArray(idStr);
        TbOrders orders = new TbOrders();
        orders.setPurchaserId(purchaser.getId());
        orders.setPurchaserName(purchaser.getName());

        //todo 接收国内采购商的货款支付申请，划扣至边民账户并给出回执 并且同步至航通
        orders.setIsPay(1);//支付成功
        orders.setPayTime(new Date());
        OrdersDto ordersDto = new OrdersDto();
        BeanUtils.copyProperties(orders,ordersDto);
        asyncServerInterface.sendLevelTwoOrdersDto(ordersDto, DataType.DATA_TYPE_FOUR.getCode()); // 发送航通

        for (Long id : idArr) {

            orders.setId(id);
            boolean b = updateById(orders);
            if (!b) throw new RuntimeException("购买异常，请重新登录或联系管理员！");

            //todo:给每个购买他商品的边民发一条支付成功消息，通知边民发起缴税申请以及缴费申请
            TbOrders t = getById(id);
            MessageDto dto = new MessageDto();
            dto.setUrl("/pages/market/two/leader/order");
            dto.setUserId(t.getLeaderId());
            dto.setContents("你转售的《" + t.getGoodsName() + "》收购商已付款。请及时发起缴税申请以及缴费申请。");
            adminInterface.messageSave(dto);
        }

        // 清空购物车
        LambdaQueryWrapper<TbOrdersCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(TbOrdersCart::getOrderId, Arrays.asList(idArr));
        int del = tbOrdersCartMapper.delete(wrapper);

        return true;
    }

    /**
     * 新增 边民缴税以及各服务费
     */
    boolean payTax(SoMap so) {
        // 获取app登录用户
        APPLoginUserInfo appLoginInfo = StpAPPUserUtil.getAPPLoginInfo();
        TbOrders orders = getById(so.getLong("id"));

        if (null == orders) throw new RuntimeException("订单信息不存在");
        if (!orders.getLeaderId().equals(appLoginInfo.getFk())) throw new RuntimeException("非法操作非本人数据");
        if (orders.getPayTax() == 1) throw new RuntimeException("你已缴清费用");

        //todo 边民缴税以及各服务费，边民发起缴税申请以及缴费申请 接收支付结果，划扣，并给出回执
        orders.setPayTax(1);
        orders.setPayTaxTime(new Date());
        orders.setOrderFinish(1);//缴费成功订单完成
        if (updateById(orders)) {
            //保存缴费记录
            List<TbFeeItem> feeItems = tbFeeItemService.getFeeItems();
            feeItems.stream().forEach(e -> {
                TbFeeItemRecord record = new TbFeeItemRecord();
                record.setItemId(e.getId());
                record.setCompanyName(e.getCompanyName());
                record.setItemName(e.getName());
                record.setOrderNo(orders.getOrderNo());
                record.setLevelTwoOrderId(orders.getId());
                record.setPayTime(new Date());
                record.setCreateTime(new Date());
                record.setPayStatus("1");
                record.setPayRemark("缴纳:" + e.getName());
                tbFeeItemRecordService.save(record);
            });
            //todo:给收购商发送边民缴费成功消息
            MessageDto dto = new MessageDto();
            dto.setUrl("/pages/market/two/purchaser/order/list");
            dto.setUserId(orders.getPurchaserId());
            dto.setContents("你购买的《" + orders.getGoodsName() + "》边民已缴清税以及各服务费。");
            adminInterface.messageSave(dto);
            return true;
        }
        return false;
    }

    List<TbOrders> getDetailById(SoMap so) {
        String idStr = so.getString("ids");
        if (StringUtils.isEmpty(idStr)) throw new RuntimeException("当前订单操作异常，请重新登录或联系管理员！");

        List<TbOrders> list = new ArrayList<>();

        String[] idArr = idStr.split(",");
        for (String id : idArr) {
            TbOrders orders = getById(id);
            list.add(orders);
        }
        return list;
    }

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

    /**
     * pc端查看订单列表,并可根据状态进行查询
     */
    List<TbOrders> getPCList(SoMap soMap, Integer ordersStatus) {
        //检查登录
        StpUtil.checkLogin();
        // PC端只能admin进行登录,默认查询所有
        soMap.put("orderFinish", ordersStatus); // 订单的完成状态
        soMap.put("sortType", 22);  // 根据时间降序
        return tbOrdersMapper.getList(soMap);
    }

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

    /**
     * 查集合 - 查二级市场订单(未被购买的订单)
     */
    List<TbOrders> getLevelTwoList(SoMap so) {
        return tbOrdersMapper.getLevelTwoList(so);
    }

    /**
     * 二级市场订单 组长/边民角色入口
     * 管理购买的商品订单（包括已支付、运输中、售后）
     */
    List<TbOrders> getLeaderOrderList(SoMap so) {
        // 边民组长id
        so.put("leaderId", StpAPPUserUtil.getAPPLoginInfo().getFk());
        so.put("sortType", 22);
        so.put("deleteStatus", DeleteStatus.DELETE_STATUS_ON.getCode());
        List<TbOrders> orderList = tbOrdersMapper.getList(so);

        return orderList;
    }

    /**
     * 二级市场订单 收购商角色入口
     * 管理购买的商品订单（包括已支付、运输中、售后）
     */
    List<TbOrders> getPurchaserOrderList(SoMap so) {
        // 收购商id
        so.put("purchaserId", StpAPPUserUtil.getAPPLoginInfo().getFk());
        so.put("sortType", 22);
        so.put("deleteStatus", DeleteStatus.DELETE_STATUS_ON.getCode());
        List<TbOrders> orderList = tbOrdersMapper.getList(so);

        return orderList;
    }

    /**
     * 管理二级市场的开票申请信息、并审核
     *
     * @param tbOrdersID 二级市场订单ID主键
     * @param isBill     审核是否开票状态 1=通过 0=未通过
     */
    public void bill(Long tbOrdersID, Integer isBill) {
        //todo: 管理二级市场的开票申请信息、并审核
    }

    /**
     * 增 一级市场已完成订单进行转售时，新增二级市场订单
     */
    boolean addOrderByResale(TbOrdersDto ordersDto) {
        //获取app登录用户
        APPLoginUserInfo appLoginInfo = StpAPPUserUtil.getAPPLoginInfo();
        if (appLoginInfo == null || appLoginInfo.getLoginId() == null)
            throw new RuntimeException("当前登陆用户信息已失效!");

        if (null == ordersDto.getLevelOneOrderId()) throw new RuntimeException("当前一级市场订单号为空，请联系管理员！");

        TbOrders orders = new TbOrders();
        BeanUtils.copyProperties(ordersDto, orders);
        //订单编号:EJSCDD=二级市场订单
        orders.setOrderNo(SystemObject.getREFcode("EJSCDD", new Date()));
        //订单完成状态 (0=未完成,1=已完成)
        orders.setOrderFinish(OrderStatus.ORDER_STATUS_ZERO.getCode());
        //删除状态(0=禁用,1=启用)
        orders.setDeleteStatus(DeleteStatus.DELETE_STATUS_ON.getCode());

        //转售订单的边民id
        orders.setLeaderId(appLoginInfo.getFk());
        //创建人
        orders.setCreateBy(appLoginInfo.getLoginId());
        orders.setCreateName(appLoginInfo.getLoginName());
        orders.setCreateTime(new Date());

        this.add(orders);

        //修改一级市场边民订单转售状态为已转售
        boolean b = levelOneServerInterface.updateResaleStatus(ordersDto.getLevelOneOrderId());
        if (!b) throw new RuntimeException("修改一级市场边民订单转售状态为已转售失败！");

        return true;
    }

    /**
     * 增  二级市场订单
     */
    boolean addByDetail(GoodsDemandVo goodsDemandVo) {
        TbOrders orders = new TbOrders();

        //查询商品基本信息
        GoodsDto goodsDto = levelOneServerInterface.getByGoodsId(goodsDemandVo.getLevelOneGoodsId());
        orders.setGoodsFrom(goodsDto.getSource());

        //订单编号:EJSCDD=二级市场订单
        orders.setOrderNo(SystemObject.getREFcode("EJSCDD", new Date()));
        orders.setGoodsId(goodsDemandVo.getLevelOneGoodsId());
        orders.setGoodsName(goodsDemandVo.getGoodsName());
        orders.setConsigneeName(goodsDemandVo.getName());
        orders.setConsigneePhone(goodsDemandVo.getPhone());
        orders.setUnloadingAddress(goodsDemandVo.getAddressName());
        orders.setLeaderId(goodsDemandVo.getLeaderId());
        // 需求表主键Id
        orders.setFkGoodsDemandId(goodsDemandVo.getGoodsDemandId());
        //订单完成状态 (0=未完成,1=已完成)
        orders.setOrderFinish(OrderStatus.ORDER_STATUS_ZERO.getCode());
        //收货状态 (0=未收货,1=已收货)
        orders.setOrderFinish(OrderStatus.ORDER_STATUS_ZERO.getCode());
        //删除状态(0=禁用,1=启用)
        orders.setDeleteStatus(DeleteStatus.DELETE_STATUS_ON.getCode());
        //创建人
        orders.setCreateBy(StpAPPUserUtil.getAPPLoginInfo().getLoginId());
        orders.setCreateName(StpAPPUserUtil.getAPPLoginInfo().getLoginName());
        orders.setCreateTime(new Date());

        orders.setPurchaserId(StpAPPUserUtil.getAPPLoginInfo().getFk());
        orders.setTradeAreaId(goodsDemandVo.getTradeAreaId());
        orders.setTradeAreaName(goodsDemandVo.getTradeAreaName());

        this.add(orders);

        // 回写到收购商发布需求表，把收购商确认状态改为已确认
        LambdaUpdateWrapper<TbGoodsDemand> wrapper1 = new LambdaUpdateWrapper();
        //收购商是否确认:0=未确认,1=已确认
        wrapper1.set(TbGoodsDemand::getIsConfirm, 1);
        wrapper1.eq(TbGoodsDemand::getId, goodsDemandVo.getGoodsDemandId());
        boolean update1 = goodsDemandService.update(wrapper1);

        // 回写到组长报价表，把报价结果状态改为已确认
        LambdaUpdateWrapper<TbDemandQuotation> wrapper2 = new LambdaUpdateWrapper();
        //收购商是否确认:0=未确认,1=已确认
        wrapper2.set(TbDemandQuotation::getQuotationResult, 1);
        wrapper2.eq(TbDemandQuotation::getDemandId, goodsDemandVo.getGoodsDemandId());
        wrapper2.eq(TbDemandQuotation::getQuotationResult, 0);
        boolean update2 = demandQuotationService.update(wrapper2);

        //todo:给组长发一条已确认接单消息
        MessageDto dto = new MessageDto();
        dto.setUrl("/pages/market/two/leader/order");
        dto.setUserId(goodsDemandVo.getLeaderId());
        dto.setContents("你接单的《" + goodsDemandVo.getGoodsName() + "》商户已确认,请及时发货。");
        adminInterface.messageSave(dto);

        return true;
    }
}
