package com.pj.ht_trade_settlement;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pj.api.dto.*;
import com.pj.current.config.SystemObject;
import com.pj.enummj.*;
import com.pj.tb_goods.TbGoods;
import com.pj.tb_goods.TbGoodsService;
import com.pj.tb_import_order.TbImportOrder;
import com.pj.tb_import_order.TbImportOrderService;
import com.pj.tb_order.TbOrder;
import com.pj.tb_order.TbOrderMapper;
import com.pj.tb_people.TbPeople;
import com.pj.tb_people.TbPeopleService;
import com.pj.tb_shop.TbShop;
import com.pj.tb_shop.TbShopService;
import com.pj.tb_trade_area.TbTradeArea;
import com.pj.tb_trade_area.TbTradeAreaService;
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 javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Service: ht_trade_settlement -- 航通交易结算表
 *
 * @author yzs
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class HtTradeSettlementService extends ServiceImpl<HtTradeSettlementMapper, HtTradeSettlement> implements IService<HtTradeSettlement> {

    /**
     * 底层 Mapper 对象
     */
    @Autowired
    HtTradeSettlementMapper htTradeSettlementMapper;
    @Autowired
    private TbPeopleService tbPeopleService;
    @Autowired
    private TbOrderMapper tbOrderMapper;

    @Resource
    private TbTradeAreaService tbTradeAreaService;
    @Resource
    private TbGoodsService tbGoodsService;
    @Resource
    private TbShopService tbShopService;
    @Resource
    private TbImportOrderService tbImportOrderService;

    /**
     * 增
     */
    void add(HtTradeSettlement h) {
        save(h);
    }

    /**
     * 删
     */
    @Transactional
    void delete(Long id) {
        removeById(id);
        SoMap soMap = new SoMap();
        soMap.put("sale_main_id", id);
        tbOrderMapper.deleteByMap(soMap);
    }

    /**
     * 改
     */
    void update(HtTradeSettlement h) {
        updateById(h);

    }

    /**
     * 查
     */
    HtTradeSettlement getById(String platSeqNo) {
        return super.getById(platSeqNo);
    }

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


    /**
     * 远程调用: 添加大订单时同时生成边民订单
     */
    public boolean tradeSettlementDto(TradeSettlementDto tradeSettlementDto) {
        LambdaQueryWrapper<HtTradeSettlement> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(HtTradeSettlement::getPlatSeqNo, tradeSettlementDto.getPlatSeqNo());
        List<HtTradeSettlement> htTradeSettlements = htTradeSettlementMapper.selectList(wrapper);
        //删除已存在的大订单与小订单，保留航通送过来的最新记录
        if (htTradeSettlements.size() > 0) {
            List<Long> idList = htTradeSettlements.stream().map(item -> item.getId()).collect(Collectors.toList());
            LambdaQueryWrapper<TbOrder> orderWrapper = new LambdaQueryWrapper<>();
            orderWrapper.in(TbOrder::getSaleMainId, idList);
            int orderDelete = tbOrderMapper.delete(orderWrapper);

            int htTradeSettlementsDelete = htTradeSettlementMapper.delete(wrapper);
            StaticLog.info("\n------删除航通旧进境结算单:platSeqNo={}", tradeSettlementDto.getPlatSeqNo());
        }

        StaticLog.info("接收到航通结算订单:{}", JSONUtil.toJsonStr(tradeSettlementDto));
        HtTradeSettlement htTradeSettlement = new HtTradeSettlement();
        BeanUtils.copyProperties(tradeSettlementDto, htTradeSettlement);
        TbShop tbShop = tbShopService.findByCode(tradeSettlementDto.getShopNo());
        if (tbShop == null) {
            StaticLog.error("结算单异常，找不到店铺信息:{}", tradeSettlementDto.getShopNo());
        } else {
            htTradeSettlement.setEnterpriseId(tbShop.getEnterpriseId());
        }
        htTradeSettlement.setCreateTime(new Date());
        //获取边民订单集合
        List<BordersListDto> bordersListDtoList = tradeSettlementDto.getBordersListDtoList();
        htTradeSettlement.setOrderCount(bordersListDtoList.size());
        int insert = htTradeSettlementMapper.insert(htTradeSettlement);
        //获取订单商品列表集合
        List<BorderBuyGoodsListDto> borderBuyGoodsListDtoList = tradeSettlementDto.getBorderBuyGoodsListDtoList();
        //获取商铺卖货物列表(目前逻辑为：当前商铺卖货集合，只有当前订单商品(一个商品))
        List<SellGoodsListDto> sellGoodsListDtoList = tradeSettlementDto.getSellGoodsListDtoList();

        TbTradeArea tbTradeArea = tbTradeAreaService.updateHandler(tradeSettlementDto.getFieldCode(), tradeSettlementDto.getFieldName(), "");
        Date applyTime = new Date(Long.parseLong(tradeSettlementDto.getDeclTime()));
        htTradeSettlement.setDeclTime(DateUtil.format(applyTime, "yyyy-MM-dd HH:mm:ss")).setFinishStatus(0);
        BigDecimal totalPrice = BigDecimal.ZERO;
        for (BordersListDto item : bordersListDtoList) {//开始创建边民订单
            totalPrice = totalPrice.add(BigDecimal.valueOf(item.getBuyAmount()));
            TbOrder tbOrder = new TbOrder();
            //航通字段
            BeanUtils.copyProperties(item, tbOrder);
            tbOrder.setSaleMainId(htTradeSettlement.getId());
            tbOrder.setCreateTime(new Date()).setPreNo(item.getPreNo())
                    .setTradeNo(SystemObject.getREFcode("YJSCDD", new Date()))
                    .setTradeAreaId(tbTradeArea.getId()).setTradeAreaName(tbTradeArea.getName());
            tbOrder.setTotalWeight(item.getGrossWt()).setTotalPrice(item.getBuyAmount());

            tbOrder.setApply(ApplyStatus.APPLY_STATUS_ONE.getCode()).setApplyTime(applyTime).setVeNo(tradeSettlementDto.getVeNo());
            tbOrder.setDeleteStatus(DeleteStatus.DELETE_STATUS_ON.getCode());
            tbOrder.setResaleStatus(ResaleStatus.RESALE_STATUS_ZERO.getCode());
            tbOrder.setFinishStatus(OrderStatus.ORDER_STATUS_ZERO.getCode());
            //申报单类型，用以后续判断当前订单是否是委托单
            tbOrder.setDeclareType(tradeSettlementDto.getDeclareType());
            tbOrder.setGoodsNames(tradeSettlementDto.getGoodsNames());
            //008进口申报单
            List<TbImportOrder> importOrderList = tbImportOrderService.lambdaQuery().eq(TbImportOrder::getPlatSeqNo, item.getPreIeportNo()).list();
            if (importOrderList.size() > 0) {
                tbOrder.setImportOrderId(importOrderList.get(0).getId());
            }

            //获取商品单价
            if (sellGoodsListDtoList.size() > 0) tbOrder.setDeclPrice(sellGoodsListDtoList.get(0).getDeclPrice());

            //根据边民身份证号获取边民的订单商品列表(目前逻辑为一个边民对应一个商品)
            List<BorderBuyGoodsListDto> collect = borderBuyGoodsListDtoList.stream().filter(borderBuyGoods -> item.getIdno().equals(borderBuyGoods.getIdno())).collect(Collectors.toList());
            if (collect.size() > 0) {
                //根据商品编号查询商品表
                TbGoods tbGoods = tbGoodsService.findByCode(collect.get(0).getCodeTs());
                if (null != tbGoods) {
                    tbOrder.setGoodsId(tbGoods.getId());
                    tbOrder.setGoodsNames(tbGoods.getName());
                    tbOrder.setGoodsUnit(tbGoods.getUnit());

                    tbOrder.setBuyQty(collect.get(0).getBuyQty());
                    tbOrder.setGrossWt(collect.get(0).getGrossWt());
                    tbOrder.setCodeTs(collect.get(0).getCodeTs());
                }
            }
            //根据身份证查询边民
            TbPeople tbPeople = tbPeopleService.findByIdCarNo(item.getIdno());
            if (tbPeople != null) {
                tbOrder.setBuyUserId(tbPeople.getId());
                tbOrder.setBuyUserName(tbPeople.getName());
                tbOrder.setBuyUserType(String.valueOf(tbPeople.getRole()));
                tbOrder.setGroupId(tbPeople.getGroupId());
            }
            //商品店铺信息
            if (tbShop != null) {
                tbOrder.setEnterpriseId(tbShop.getEnterpriseId()).setEnterpriseName(tbShop.getEnterpriseName());
                tbOrder.setShopId(tbShop.getId()).setShopName(tbShop.getShopName());
            }
            int result = tbOrderMapper.insert(tbOrder);
            //发送短信
            if (result == 1) {
                String content = "您好,您的[边民互市订单]已经生成,订单商品是[" + tbOrder.getGoodsNames() + "]。请前往app进行交易确认";
                // SystemObject.smsFactory.handler().sendSMS(tbPeople.getPhone(), content);
            }
        }
        htTradeSettlement.setTotalPrice(totalPrice);
        this.updateById(htTradeSettlement);

        return insert == 1;
    }

    public List<HtTradeSettlement> getOnSaleList(SoMap startPage) {
        return htTradeSettlementMapper.getOnSaleList(startPage);
    }
}
