package com.ruoyi.warehouseBusiness.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.ruoyi.basicData.domain.TCorps;
import com.ruoyi.basicData.domain.TGoods;
import com.ruoyi.basicData.mapper.TCorpsMapper;
import com.ruoyi.basicData.mapper.TGoodsMapper;
import com.ruoyi.basicData.mapper.TWarehouseMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.TWarehouse;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.reportManagement.domain.TWhgenleg;
import com.ruoyi.reportManagement.mapper.TWhgenlegMapper;
import com.ruoyi.warehouseBusiness.domain.TWarehouseBills;
import com.ruoyi.warehouseBusiness.domain.TWarehousebillsitems;
import com.ruoyi.warehouseBusiness.domain.TWarehousebillsitemsElabel;
import com.ruoyi.warehouseBusiness.mapper.TWarehouseBillsMapper;
import com.ruoyi.warehouseBusiness.mapper.TWarehousebillsitemsElabelMapper;
import com.ruoyi.warehouseBusiness.mapper.TWarehousebillsitemsMapper;
import com.ruoyi.warehouseBusiness.service.IWarehouseBillsCcbService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 建行接口实现
 *
 * @author s
 */
@Service
@AllArgsConstructor
public class WarehouseBillsCcbServiceImpl implements IWarehouseBillsCcbService {

    private final BillnoSerialServiceImpl serialServiceImpl;

    private final TWarehouseBillsMapper billMapper;

    private final TWarehousebillsitemsMapper billItemMapper;

    private final TWarehousebillsitemsElabelMapper eLabelMapper;

    private final TCorpsMapper corpMapper;

    private final TGoodsMapper goodsMapper;

    private final TWarehouseMapper warehouseMapper;

    private final TWhgenlegMapper stockMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult inAndOutStock(String billType, List<TWarehousebillsitems> items) {
        for (TWarehousebillsitems item : items) {
            // 获取客户信息
            TCorps corp = corpMapper.getCorpByName(item.getCargoBelong());
            if (ObjectUtil.isNull(corp)) {
                return AjaxResult.error("客户不存在！");
            }

            TGoods goods = goodsMapper.getGoodsByNo(item.getCargoNo());
            if (ObjectUtil.isNull(goods)) {
                return AjaxResult.error("商品不存在！");
            }

            // 初始化数据
            Date bsDate = new Date();
            String billNo = serialServiceImpl.getBillNo(billType, bsDate);
            String dateChanged = DateUtils.getTimestamp(bsDate).toString() + (int) (Math.random() * 900) + 100;
            Long billId;

            // 组装主表数据
            TWarehouseBills bill = new TWarehouseBills();
            bill.setfDeptid(100L);
            bill.setCreateBy("CCB");
            bill.setfStorekeeper("CCB");
            bill.setfContacts("CCB");
            bill.setfIfdamage("1");
            bill.setfIfweigh("1");
            bill.setfChargetype("1");
            bill.setfStltypeid(1L);
            if ("1".equals(item.getfSealno())) {
                bill.setfTrademodeid(273L);
            } else {
                bill.setfTrademodeid(1L);
            }

            bill.setfGoodsid(goods.getfId());
            bill.setfPlanqty(item.getfPlanqty());
            bill.setfPlangrossweight(item.getfPlangrossweight());
            bill.setfPlannetweight(item.getfPlannetweight());
            bill.setfPlanvolumn(BigDecimal.ZERO);
            bill.setfQty(item.getfQty());
            bill.setfGrossweight(item.getfGrossweight());
            bill.setfNetweight(item.getfNetweight());
            bill.setfVolumn(BigDecimal.ZERO);

            bill.setfBsdeptid(100L);
            bill.setfBillno(billNo);
            bill.setfCorpid(corp.getfId());

            bill.setfShipper(corp.getfCname());
            bill.setfStltypeid(corp.getfStltypeid());

            bill.setfBillingway(2L);
            bill.setfTrademodeid(1L);
            bill.setfMblno(item.getfMblno());
            bill.setfBilltype(billType);

            bill.setCreateTime(bsDate);
            bill.setfDateChanged(dateChanged);
            bill.setfBillstatus(2L);
            bill.setfItemsStatus(2L);
            bill.setfBsdate(bsDate);
            bill.setfBstime(bsDate);

            if ("SJRK".equals(billType)) {
                String bsCorpNo = serialServiceImpl.getCorpNo(corp.getfId(), bsDate);
                bill.setfBscorpno(bsCorpNo);
                bill.setfBusinessType("0");
            } else {
                TWarehouse warehouse = warehouseMapper.getWarehouseByNo(item.getWarehouseNo());
                if (ObjectUtil.isNull(warehouse)) {
                    return AjaxResult.error("仓库不存在！");
                }

                bill.setfWarehouseid(warehouse.getfId());
                bill.setfChargedate(bsDate);
                bill.setfBusinessType("5");
            }

            billMapper.insertTWarehousebills(bill);
            billId = bill.getfId();

            // 从表数据处理
            item.setfGoodsid(goods.getfId());
            item.setfPid(billId);
            item.setfBillno(billNo);
            item.setfShipper(bill.getfShipper());
            item.setfBilltype(billType);
            item.setCreateBy("CCB");
            item.setCreateTime(bsDate);
            item.setfBsdate(bill.getfBsdate());
            item.setfBusinessType(1L);

            if ("SJCK".equals(billType)) {
                TWarehouse warehouse = warehouseMapper.getWarehouseByNo(item.getShelvesNo());
                if (ObjectUtil.isNull(warehouse)) {
                    return AjaxResult.error("库区不存在！");
                }
                item.setfWarehouselocid(warehouse.getfId());
                item.setfWarehouseInformation(warehouse.getfWarehouseInformation());

                TWhgenleg temp = new TWhgenleg();
                temp.setfCorpid(bill.getfCorpid());
                temp.setfMblno(item.getfMblno());
                temp.setfWarehouseLocationid(item.getfWarehouselocid());
                temp.setfTrademodeid(bill.getfTrademodeid());
                temp.setfGoodsid(item.getfGoodsid());
                temp.setfLocation(1L);
                TWhgenleg stock = stockMapper.selectTWhgenleg(temp);
                if (ObjectUtil.isNull(stock)) {
                    return AjaxResult.error("未找到库存！");
                }
                item.setfSrcid(stock.getfId());
                item.setfSrcBsdate(stock.getfBsdate());
                item.setfChargedate(stock.getfChargedate());
            }
            billItemMapper.insertTWarehousebillsitems(item);

            if ("SJCK".equals(billType)) {
                List<String> tags = item.getElectronicTags();
                if (CollectionUtil.isNotEmpty(tags)) {
                    tags.forEach(tag -> {
                        TWarehousebillsitemsElabel eLabel = new TWarehousebillsitemsElabel();
                        eLabel.setfGPid(billId);
                        eLabel.setfPid(item.getfId());
                        eLabel.setfContent(tag);
                        eLabel.setfType(2);
                        eLabel.setCreateBy("CCB");
                        eLabel.setCreateTime(bsDate);
                        eLabelMapper.insert(eLabel);
                    });
                }
            }
        }
        return AjaxResult.success();
    }

    @Override
    public List<Map<String, Object>> getStockList(String takeVoucher, String corpName) {
        // 获取客户信息
        TCorps corp = corpMapper.getCorpByName(corpName);
        if (ObjectUtil.isNull(corp)) {
            return Collections.emptyList();
        }
        return stockMapper.selectStockList(takeVoucher, corp.getfId());
    }

    @Override
    public AjaxResult lockStock(String belongTo, List<String> billNoList, boolean isWrNumber) {
        billNoList.forEach(billNo -> {
            TWhgenleg stock = new TWhgenleg();
            stock.setfOriginalbillno(billNo);
            stock.setLockStatus(1);
            stock.setBelongTo(belongTo);
            stock.setLockTime(new Date());
            if (isWrNumber) {
                stock.setWrNumber(billNo);
            }
            stockMapper.changeBelongTo(stock);
        });
        return AjaxResult.success();
    }

    @Override
    public AjaxResult unlockStock(List<String> billNoList, boolean isWrNumber) {
        billNoList.forEach(billNo -> {
            TWhgenleg stock = new TWhgenleg();
            stock.setfOriginalbillno(billNo);
            stock.setLockStatus(0);
            stock.setUnlockTime(new Date());
            if (isWrNumber) {
                stock.setWrNumber("");
            }
            stockMapper.changeBelongTo(stock);
        });
        return AjaxResult.success();
    }

    @Override
    public List<Map<String, Object>> getSyncOrg(Integer page, Integer size, String time) {
        PageHelper.startPage(page, size);
        return corpMapper.getSyncCorpList(time);
    }

    @Override
    public List<String> getLabel(String billNo) {
        return eLabelMapper.getLabel(billNo);
    }


    /**
     * 获取库存
     *
     * @param blNumber 提单号
     * @param corpName 客户名
     * @return 库存列表
     */
    @Override
    public List<Map<String, Object>> selectBlNumber(String blNumber, String corpName) {
        // 获取客户信息
        TCorps corp = corpMapper.getCorpByName(corpName);
        //判断该客户是否存在
        if (ObjectUtil.isNull(corp)) {
            return Collections.emptyList();
        }
        return stockMapper.selectBlNumber(blNumber, corp.getfId());
    }
}
