package com.zbf.system.service.impl;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; //添加
import com.zbf.common.utils.DateUtils;
import com.zbf.common.utils.OrderCodeFactory;
import com.zbf.system.domain.TBasePallet;
import com.zbf.system.domain.TBaseStorageAreaLocation;
import com.zbf.system.domain.TMiStock;
import com.zbf.system.domain.TMiStockF;
import com.zbf.system.domain.TMiStockFUpdate;
import com.zbf.system.domain.TOngoodsshelf;
import com.zbf.system.domain.TOngoodsshelfBak;
import com.zbf.system.domain.TRkWareNotice;
import com.zbf.system.domain.TRkWareNoticeBak;
import com.zbf.system.domain.TRkWareNoticeTabBak;
import com.zbf.system.mapper.TBasePalletMapper;
import com.zbf.system.mapper.TBaseStorageAreaLocationMapper;
import com.zbf.system.mapper.TMiStockFMapper;
import com.zbf.system.mapper.TMiStockMapper;
import com.zbf.system.mapper.TOngoodsshelfBakMapper;
import com.zbf.system.mapper.TOngoodsshelfMapper;
import com.zbf.system.mapper.TRkWareNoticeBakMapper;
import com.zbf.system.mapper.TRkWareNoticeMapper;
import com.zbf.system.service.ITCallNoticeService;
import com.zbf.system.service.ITMiStockFService;

/**
 * 库存Service业务层处理
 *
 * @author tony
 * @date 2024-07-27
 */
@Service
public class TMiStockFServiceImpl extends ServiceImpl<TMiStockFMapper, TMiStockF> implements ITMiStockFService //修改
{
    @Autowired
    private TMiStockFMapper tMiStockFMapper;

    @Autowired
    private TBasePalletMapper palletMapper;

    @Autowired
    private ITCallNoticeService tNoticeService;

    @Autowired
    private TRkWareNoticeMapper tRkWareNoticeMapper;

    @Autowired
    private TRkWareNoticeBakMapper tRkWareNoticeBakMapper;

    @Autowired
    private TOngoodsshelfMapper tOngoodsshelfMapper;

    @Autowired
    private TBaseStorageAreaLocationMapper service;

    @Autowired
    private TOngoodsshelfBakMapper tOngoodsshelfBakMapper;

    @Autowired
    private TMiStockMapper tMiStockMapper;

    /**
     * 查询库存
     *
     * @param id 库存主键
     * @return 库存
     */
    @Override
    public TMiStockF selectTMiStockFById(String id)
    {
        return tMiStockFMapper.selectTMiStockFById(id);
    }

    /**
     * 查询库存列表
     *
     * @param tMiStockF 库存
     * @return 库存
     */
    @Override
    public List<TMiStockF> selectTMiStockFList(TMiStockF tMiStockF)
    {
        return tMiStockFMapper.selectTMiStockList(tMiStockF);
    }

    /**
     * 新增库存
     *
     * @param tMiStockF 库存
     * @return 结果
     */
    @Override
    public int insertTMiStockF(TMiStockF tMiStockF)
    {
        tMiStockF.setCreateTime(DateUtils.getNowDate());
        return tMiStockFMapper.insertTMiStock(tMiStockF);
    }

    /**
     * 批量删除库存
     *
     * @param ids 需要删除的库存主键
     * @return 结果
     */
    @Override
    public int deleteTMiStockFByIds(String[] ids)
    {
        return tMiStockFMapper.deleteTMiStockFByIds(ids);
    }

    @Override
    public int updateTMiStockF(TMiStockF tMiStockF) {
        // TODO Auto-generated method stub
        throw new UnsupportedOperationException("Unimplemented method 'updateTMiStockF'");
    }

    @Override
    public int deleteTMiStockFById(String id) {
        // TODO Auto-generated method stub
        throw new UnsupportedOperationException("Unimplemented method 'deleteTMiStockFById'");
    }

    @Override
    public int disabledTMiStockFByIds(String[] ids) {
        // TODO Auto-generated method stub
        throw new UnsupportedOperationException("Unimplemented method 'disabledTMiStockFByIds'");
    }

    @Override
    public int enableTMiStockFByIds(String[] ids) {
        // TODO Auto-generated method stub
        throw new UnsupportedOperationException("Unimplemented method 'enableTMiStockFByIds'");
    }

    @Override
    public int updateStatus(TMiStockF tMiStockF) {
        // TODO Auto-generated method stub
        throw new UnsupportedOperationException("Unimplemented method 'updateStatus'");
    }

    @Override
    public Map<String, String> goodsMakeCtl(TMiStockFUpdate tMiStockFUpdate) {

        Map<String, String> resultMap = new HashMap<>();

        if (ObjectUtils.isEmpty(tMiStockFUpdate.getToCtlNo())) {
            resultMap.put("error", "托盘号不能为空");
            return resultMap;
        }

        //校验托盘容器是否正确
        LambdaQueryWrapper<TBasePallet> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TBasePallet::getPalletId, tMiStockFUpdate.getToCtlNo());
        List<TBasePallet> plcs = palletMapper.selectList(wrapper);
        if (plcs.isEmpty()){
            resultMap.put("error", "托盘不存在");
            return resultMap;
        }

        if (ObjectUtils.isEmpty(tMiStockFUpdate.getToLoc())) {
            resultMap.put("error", "目标库位不能为空");
            return resultMap;
        }

        LambdaQueryWrapper<TBaseStorageAreaLocation> wrapperLoc = new LambdaQueryWrapper<>();
        wrapperLoc.eq(TBaseStorageAreaLocation::getLocationId,tMiStockFUpdate.getToLoc());
        List<TBaseStorageAreaLocation> areaLocations = service.selectList(wrapperLoc);
        if (areaLocations.isEmpty()){
            throw new RuntimeException("库位号错误");
        }

        Map<String, TRkWareNoticeBak> noticeMap = new HashMap<>();
        Map<String, TRkWareNoticeTabBak> trkWareNoticeTabMap = new HashMap<String, TRkWareNoticeTabBak>();

        for(TMiStockF tMiStockF : tMiStockFUpdate.gettMiStockFList()) {

            if (!noticeMap.containsKey(tMiStockF.getNoticeId())) {

                TRkWareNoticeBak tRkWareNoticeBak = tRkWareNoticeBakMapper.selectTRkWareNoticeBakByNoticeId(tMiStockF.getNoticeId());

                if (tRkWareNoticeBak == null) {

                    // 查询入库通知单明细
                    TRkWareNotice tRkWareNotice = tRkWareNoticeMapper.selectTRkWareNoticeByNoticeId(tMiStockF.getNoticeId());

                    if (tRkWareNotice == null) {
                        resultMap.put("error", "入库通知单不存在");
                        throw  new RuntimeException("入库通知单不存在");
                    }

                    BeanUtils.copyProperties(tRkWareNotice, tRkWareNoticeBak);
                }

                noticeMap.put(tMiStockF.getNoticeId(), tRkWareNoticeBak);
            }

            TRkWareNoticeBak tRkWareNoticeBak = noticeMap.get(tMiStockF.getNoticeId());

            String searchKey = tMiStockF.getNoticeId()+tMiStockF.getSalesOrderNumber()+tMiStockF.getGoodsId();

            // 通知单明细map
            for (int i = 0; i < tRkWareNoticeBak.getTRkWareNoticeTabBakList().size(); i++) {
                TRkWareNoticeTabBak noticeTab = tRkWareNoticeBak.getTRkWareNoticeTabBakList().get(i);

                if (!trkWareNoticeTabMap.containsKey(searchKey)) {
                    trkWareNoticeTabMap.put(searchKey, noticeTab);
                }
            }

            TRkWareNoticeTabBak tRkWareNoticeTabBak = trkWareNoticeTabMap.get(searchKey);

            if (tRkWareNoticeTabBak == null) {
                resultMap.put("error", "入库通知单明细不存在");
                throw  new RuntimeException("入库通知单明细不存在");
            }

            tMiStockF.setLocationId(tMiStockFUpdate.getToLoc());
            tMiStockF.setCtl(tMiStockFUpdate.getToCtlNo());
            tMiStockF.setCreateBy(tMiStockFUpdate.getUpdateBy());
            tMiStockF.setCreateTime(new Date());
            tMiStockF.setUpdateBy(tMiStockFUpdate.getUpdateBy());
            tMiStockF.setUpdateTime(new Date());

            makeTOngoodsshelf(tRkWareNoticeBak, tRkWareNoticeTabBak,tMiStockFUpdate);

            // 生成真实库存
            TMiStock tMiStock = new TMiStock();
            BeanUtils.copyProperties(tMiStockF, tMiStock);
//            tMiStock.setId(OrderCodeFactory.getOrderCode("TMI", ""));
            tMiStockMapper.insertTMiStock(tMiStock);

            // 删除暂存库存
            tMiStockFMapper.deleteTMiStockFById(tMiStockF.getId());
        }

        resultMap.put("success", "物料组盘入库成功");
        resultMap.put("error", "");
        return resultMap;
    }

    /**
     * 编辑入库任务
     *
     * @param notice
     * @param noticeTab
     * @return
     */
    private void makeTOngoodsshelf(TRkWareNoticeBak notice, TRkWareNoticeTabBak noticeTab,
            TMiStockFUpdate params) {
        TOngoodsshelf tOngoodsshelf = new TOngoodsshelf();

        // 需求数量 TODO
        // tOngoodsshelf.setStoNum();

        tOngoodsshelf.setId(OrderCodeFactory.getOrderCode("S", ""));

        // 中标供应商
        tOngoodsshelf.setProviderId(notice.getProviderId());
        // 单位
        tOngoodsshelf.setUnit(noticeTab.getUnit());
        // 子需求编号
        tOngoodsshelf.setSalesOrderNumber(noticeTab.getSalesOrderNumber());
        // 物料名称
        tOngoodsshelf.setGoodsName(noticeTab.getGoodsName());
        // 规格型号
        tOngoodsshelf.setSpecification(noticeTab.getSpecification());
        // 物料描述
        tOngoodsshelf.setRecoil(noticeTab.getRecoil());
        // 招标员
        tOngoodsshelf.setCustomerId(notice.getTenderer());
        // 需求组织
        tOngoodsshelf.setOperatorId(notice.getOperatorId());
        // 申请部门
        tOngoodsshelf.setSupplier(noticeTab.getSupplier());
        // 创建时间
        tOngoodsshelf.setOperateDate(noticeTab.getOperateDate());
        // 上报时间
        tOngoodsshelf.setReportTime(noticeTab.getReportTime());
        // 申请单号 设置为来源单号 发货单号 TODO
        tOngoodsshelf.setLotId(notice.getPurchaseId());
        // 申请人
        tOngoodsshelf.setApplicant(notice.getApplicant());
        // 主管部门 TODO
        // tOngoodsshelf.setRespDept(null);
        // 计划日期
        tOngoodsshelf.setPlanDate(noticeTab.getPlanDate());
        // 计划期间
        tOngoodsshelf.setPlanTime(noticeTab.getPlanTime());
        // 需求周期
        tOngoodsshelf.setNeedCycle(noticeTab.getNeedCycle());
        // 需求类型
        tOngoodsshelf.setNeedType(noticeTab.getNeedType());
        // 物料编码
        tOngoodsshelf.setGoodsId(noticeTab.getGoodsId());
        // 物料分类
        tOngoodsshelf.setGoodsTypeId(noticeTab.getGoodsTypeId());
        // 品牌
        tOngoodsshelf.setBrand(noticeTab.getBrand());
        // 计划单价（含税）
        tOngoodsshelf.setPrice(noticeTab.getPrice());
        // 计划金额
        tOngoodsshelf.setTotalMoney(noticeTab.getTotalMoney());
        // 需求时间
        tOngoodsshelf.setExpiryDate(noticeTab.getExpiryDate());
        // 建议供应商名称 TODO
        tOngoodsshelf.setProviderName(notice.getProviderName());
        // 收货人
        tOngoodsshelf.setReceiver(notice.getReceiver());
        // 需求部门
        tOngoodsshelf.setNeedDept(noticeTab.getNeedDept());
        // 采购组织
        tOngoodsshelf.setPurchaseDept(notice.getPurchaseDept());
        // 收货组织
        tOngoodsshelf.setProduclotId(notice.getProduclotId());
        // 收货人部门
        tOngoodsshelf.setReceiverDept(notice.getReceiverDept());
        // 送货区域
        tOngoodsshelf.setReceivingArea(notice.getReceivingArea());
        // 技术需求附件
        tOngoodsshelf.setPackageId(noticeTab.getPackageId());
        // 物资计划明细备注
        tOngoodsshelf.setRemark(noticeTab.getRemark());
        // 用途
        tOngoodsshelf.setUseType(noticeTab.getUseType());
        // 中标供应商联系方式
        tOngoodsshelf.setTelephone(notice.getTelephone());
        // wms订单号
        tOngoodsshelf.setAcceId(notice.getNoticeId());
        // 入库数量 TODO
        tOngoodsshelf.setAccNum(noticeTab.getArraMount());

        // 状态 3:确认完成
        tOngoodsshelf.setInStatus("3");
        // 打印状态
        tOngoodsshelf.setPrintSts("0");
        // 打印次数
        tOngoodsshelf.setPrintCs(BigDecimal.ZERO);
        // 生产日期
        tOngoodsshelf.setProductionDate(noticeTab.getProductionDate());
        // 入库类型
        tOngoodsshelf.setStorageMode(notice.getStorageMode());
        // 仓库编号
        tOngoodsshelf.setStorageId(noticeTab.getStorageId());
        tOngoodsshelf.setStorageShortName(noticeTab.getStorageShortName());
        // 库位
        tOngoodsshelf.setLocationId(params.getToLoc());
        // 暂存收货库位
        tOngoodsshelf.setVirtuallyLocation(params.getFromLoc());
        // 入库方式 TODO
        // tOngoodsshelf.setPurchaseType(noticeTab.getpu.getPurchaseType()));
        // 入库时间

        tOngoodsshelf.setOndate(DateUtils.getTime());
        // 是否人工码盘
        tOngoodsshelf.setManualTrayState("1");
        // 增加采购入库单号 TODO 交货单号
        tOngoodsshelf.setWmsOrderId(notice.getDeliveryId());
        // 增加外部批次号
        tOngoodsshelf.setBatchNo(noticeTab.getBatchNo());
        // 条码
        tOngoodsshelf.setBarcode(noticeTab.getBarcode());

        // 通知单明细编号
        tOngoodsshelf.setNoticeTabId(noticeTab.getId());

        // 托盘
        tOngoodsshelf.setCtl(params.getToCtlNo());

        tOngoodsshelf.setDeptId(params.getDeptId());
        tOngoodsshelf.setCreateBy(params.getUpdateBy());
        tOngoodsshelf.setCreateTime(new Date());

        // 入库级别
        tOngoodsshelf.setLevelType(noticeTab.getLevelType());
        tOngoodsshelf.setNeedTel(noticeTab.getNeedTel());
        tOngoodsshelf.setNeedPerson(noticeTab.getNeedPerson());

        // 生成入库任务bak数据
        TOngoodsshelfBak tOngoodsshelfBak = new TOngoodsshelfBak();
        BeanUtils.copyProperties(tOngoodsshelf, tOngoodsshelfBak);
//        tOngoodsshelfBak.setId(OrderCodeFactory.getOrderCode("TSB", ""));
        tOngoodsshelfBakMapper.insertTOngoodsshelfBak(tOngoodsshelfBak);
    }
}
