package com.zbf.system.service.impl;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zbf.common.core.page.PageDomain;
import com.zbf.common.core.page.TableSupport;
import com.zbf.common.utils.PageUtils;
import com.zbf.common.utils.SecurityUtils;
import com.zbf.system.domain.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbf.common.annotation.DataScope;
import com.zbf.common.annotation.DataSource;
import com.zbf.common.enums.DataSourceType;
import com.zbf.common.utils.OrderCodeFactory;
import com.zbf.common.utils.StringUtils;
import com.zbf.system.mapper.TMiStockMapper;
import com.zbf.system.service.ITBaseStorageService;
import com.zbf.system.service.ITMiStockService;

import cn.hutool.core.util.ObjectUtil;

/**
 * 库存Service业务层处理
 *
 * @author tony
 * @date 2024-06-12
 */
@Service
public class TMiStockServiceImpl extends ServiceImpl<TMiStockMapper, TMiStock> implements ITMiStockService {

    @Autowired
    private TMiStockMapper tMiStockMapper;
    @Autowired
    private ITBaseStorageService baseStorageService;

    /**
     * 根据库存ID列表冻结库存
     *
     * @param stockIds 库存ID列表
     * @return 如果更新成功返回true，否则返回false
     */
    public boolean freezeStockByIds(List<String> stockIds, String value) {
        String userNick = SecurityUtils.getUserNick();
        LambdaUpdateWrapper<TMiStock> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(TMiStock::getId, stockIds)  // 指定条件：库存ID在提供的列表中
                .set(TMiStock::getIsFreeze, "1").set(TMiStock::getConsignment, value).set(TMiStock::getFrostMan, userNick);// 设置冻结字段为true

        // 执行更新操作，返回更新的记录数
        int updatedCount = tMiStockMapper.update(null, updateWrapper);
        return updatedCount > 0;
    }

    private List<TBaseStorage> getStorageList(Long deptId) {
        TBaseStorage baseStorage = new TBaseStorage();
        baseStorage.setDeptId(deptId);
        return baseStorageService.selectTBaseStorageList(baseStorage);

    }

    /**
     * 解冻
     *
     * @param ids
     * @return
     */
    @Override
    public boolean thawStockByIds(List<String> ids) {
        LambdaUpdateWrapper<TMiStock> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(TMiStock::getId, ids)  // 指定条件：库存ID在提供的列表中
                .set(TMiStock::getIsFreeze, "0").
                set(TMiStock::getConsignment, "").set(TMiStock::getFrostMan, "");

        // 执行更新操作，返回更新的记录数
        int updatedCount = tMiStockMapper.update(null, updateWrapper);
        return updatedCount > 0;
    }

    /**
     * 批次号修改
     *
     * @param ids
     * @param value
     * @return
     */
    @Override
    public boolean updates(List<String> ids, String value) {
        LambdaUpdateWrapper<TMiStock> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(TMiStock::getId, ids)
                .set(TMiStock::getBatchNo, value);
        // 执行更新操作，返回更新的记录数
        int updatedCount = tMiStockMapper.update(null, updateWrapper);
        return updatedCount > 0;
    }


    /**
     * 生产日期修改
     *
     * @param ids
     * @param value
     * @return
     */
    @Override
    public boolean updateDate(List<String> ids, Date value) {
        LambdaUpdateWrapper<TMiStock> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(TMiStock::getId, ids)
                .set(TMiStock::getProductionDate, value);
        // 执行更新操作，返回更新的记录数
        int updatedCount = tMiStockMapper.update(null, updateWrapper);
        return updatedCount > 0;
    }

    @Override
    public boolean updateShelvesNum(TMiStock tMiStock) {

        int i = tMiStockMapper.updateShelvesNum(tMiStock);
        return i > 0;
    }

    @Override
    @DataScope(deptAlias = "d")
    public List<TMiStock> selectTMiStockList(TMiStock tMiStock) {
        return tMiStockMapper.selectTMiStockList(tMiStock);
    }

    @DataScope(deptAlias = "d")
    public List<TMiStock> selectTMiStockLists(TMiStock tMiStock) {
        // List<TBaseStorage> storageList = getStorageList(tMiStock.getDeptId());
        // if(storageList.size() > 0){
        //     tMiStock.setStorageList(storageList.stream().map(TBaseStorage::getStorageId).collect(Collectors.toList()));
        // }
        return tMiStockMapper.selectTMiStockList(tMiStock);
    }

    @Override
    public List<TMiStock> select(TMiStock tMiStock) {
        List<TMiStock> tMiStocks = tMiStockMapper.selectTMiStockList(tMiStock);
        return tMiStocks;
    }

    @Override
    public List rfid(RfidQueryRequest request) {
        List<TMiStock> list = list(new LambdaQueryWrapper<TMiStock>()
                .eq(TMiStock::getRfidTid, request.getRfidTid())
                .or()
                .eq(TMiStock::getRfidEpc, request.getRfidEpc()));
        return list;
    }

    @Override
    public int updateRfidQuantity(RfidQuantityUpdateRequest request) {
        if ("jb".equals(request.getType())) {
            // 解绑RFID：清空RFID相关字段
            return tMiStockMapper.update(null,
                    new LambdaUpdateWrapper<TMiStock>()
                            .eq(TMiStock::getId, request.getId())
                            .set(TMiStock::getRfidEpc, "")
                            .set(TMiStock::getRfidTid, "")
                            .set(TMiStock::getUpdateTime, new Date())
                            .set(TMiStock::getUpdateBy, SecurityUtils.getUsername())
            );
        } else {
            // 更新RFID数量：更新RFID信息和库存数量
            return tMiStockMapper.update(null,
                    new LambdaUpdateWrapper<TMiStock>()
                            .eq(TMiStock::getId, request.getId())
                            .set(TMiStock::getRfidEpc, request.getRfidEpc())
                            .set(TMiStock::getRfidTid, request.getRfidTid())
                            .set(TMiStock::getShelvesNum, request.getOccupyNum())
                            .set(TMiStock::getUpdateTime, new Date())
                            .set(TMiStock::getUpdateBy, SecurityUtils.getUsername())
            );
        }
    }


    @Override
    public BigDecimal getTotal(TMiStock tMiStock) {
   /*     LambdaQueryWrapper<TMiStock> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TMiStock::getStorageId,tMiStock.getStorageId())
                .eq(TMiStock::getGoodsId,tMiStock.getGoodsId());
        if(StringUtils.isNotBlank(tMiStock.getStorageAreaId())){
            queryWrapper.eq(TMiStock::getStorageAreaId,tMiStock.getStorageAreaId());
        }

        // 执行查询并计算总金额
        BigDecimal total = tMiStockMapper.selectList(queryWrapper)
                .stream().map(TMiStock::getShelvesNum).
                reduce(BigDecimal.ZERO, BigDecimal::add);*/
        BigDecimal total = selectTMiStockList(tMiStock)
                .stream().map(TMiStock::getShelvesNum).
                reduce(BigDecimal.ZERO, BigDecimal::add);


        return total;
    }

    @Override
    public List<TMiStock> inventoryStatisticsGoods(TMiStock tMiStock) {
        List<TBaseStorage> storageList = getStorageList(tMiStock.getDeptId());
        if (storageList.size() > 0) {
            tMiStock.setStorageList(storageList.stream().map(TBaseStorage::getStorageId).collect(Collectors.toList()));
        }
        return tMiStockMapper.inventoryStatisticsGoods(tMiStock);
    }

    /**
     * 盘点库存查询
     *
     * @param tMiStock
     * @return
     */
    @Override
    public List<TMiStock> selectPanGoodsList(TMiStock tMiStock) {
        List<TBaseStorage> storageList = getStorageList(tMiStock.getDeptId());
        if (storageList.size() > 0) {
            tMiStock.setStorageList(storageList.stream().map(TBaseStorage::getStorageId).collect(Collectors.toList()));
        }
        return tMiStockMapper.selectPanGoodsList(tMiStock);
    }

    /**
     * 获取当日变化的库位
     *
     * @return
     */
    public List<String> selectPanTimeLocation() {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String queryDate = df.format(new Date());
        return tMiStockMapper.selectPanTimeLocation(queryDate);
    }

    @Override
    public int changeLocation(TMiStockUpdate tMiStockUpdate) {
        try {

            for (String s : tMiStockUpdate.getLocal()) {
                TMiStock tMiStock = tMiStockMapper.selectOne(new LambdaQueryWrapper<TMiStock>().eq(TMiStock::getId, s));
                TMiStockUpdate update = new TMiStockUpdate();
                update.setFromLoc(tMiStock.getLocationId());
                update.setToLoc(tMiStockUpdate.getToLoc());
                update.setId(s);
                tMiStockMapper.changeLocation(update);

                /*update.setFromLoc(s);
                tMiStockUpdate.setUpdateTime(new Date());
                tMiStockMapper.changeLocation(update);*/
            }
        } catch (Exception e) {
            return -1;
        }
        return 0;
    }

    @Override
    public List<TMiStock> selectTMiStockListByCtl(TMiStock tMiStock) {
        return tMiStockMapper.selectTMiStockList(tMiStock);
    }

    @Override
    public int changeCtlNo(TMiStockUpdate tMiStockUpdate) {
        try {
            tMiStockUpdate.setUpdateTime(new Date());
            tMiStockMapper.changeCtlNo(tMiStockUpdate);
        } catch (Exception e) {
            return -1;
        }
        return 0;
    }

    /**
     * 容器拆分修改数量
     *
     * @param tMiStockUpdate
     * @return
     */
    @Override
    public int splitCtlNo(TMiStockUpdate tMiStockUpdate) {
        if (ObjectUtil.isEmpty(tMiStockUpdate.getFromCtlNo()) || ObjectUtil.isEmpty(tMiStockUpdate.getToCtlNo())) {
            return -1;
        }

        for (TMiStock tMiStock : tMiStockUpdate.gettMiStockList()) {
            LambdaUpdateWrapper<TMiStock> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(TMiStock::getId, tMiStock.getId());
            TMiStock old = tMiStockMapper.selectOne(wrapper);

            BigDecimal oldShelvesNum = old.getShelvesNum();
            BigDecimal newShelvesNum = tMiStock.getShelvesNum();

            if (oldShelvesNum.compareTo(newShelvesNum) == 0) {
                // 数量相同，只更新托盘号
                tMiStock.setCtl(tMiStockUpdate.getToCtlNo());
                tMiStock.setUpdateBy(tMiStockUpdate.getUpdateBy());
                tMiStock.setUpdateTime(new Date());
                tMiStockMapper.updateTMiStockSplitCtl(tMiStock);
            } else {
                // 数量不同，进行库存拆分
                BigDecimal difference = oldShelvesNum.subtract(newShelvesNum);
                old.setShelvesNum(difference);
                tMiStockMapper.updateTMiStockNum(old);

                tMiStock.setShelvesNum(newShelvesNum);
                tMiStock.setCtl(tMiStockUpdate.getToCtlNo());
                tMiStock.setUpdateBy(tMiStockUpdate.getUpdateBy());
                tMiStock.setUpdateTime(new Date());
                tMiStock.setId(OrderCodeFactory.getOrderCode("TMI", ""));
                tMiStock.setCreateTime(new Date());
                tMiStock.setCreateBy(tMiStockUpdate.getUpdateBy());
                tMiStockMapper.insertTMiStock(tMiStock);
            }
        }

        return 0;
    }


    @Override
    public List<TMiStock> selectCountStockList(TMiStock tMiStock) {
//        QueryWrapper<TMiStock> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("status","0");
//        queryWrapper.select("goods_id","goods_name","sum(shelves_num) as shelvesNums").groupBy("goods_id","goods_name");
//        List<TMiStock> tMiStocks = tMiStockMapper.selectList(queryWrapper);
        if (StringUtils.isBlank(tMiStock.getStorageId())) {
            List<TBaseStorage> storageList = getStorageList(tMiStock.getDeptId());
            if (storageList.size() > 0) {
                tMiStock.setStorageList(storageList.stream().map(TBaseStorage::getStorageId).collect(Collectors.toList()));
            }
        }
        return tMiStockMapper.inventoryStatisticsGoods(tMiStock);
    }

    @DataSource(value = DataSourceType.MASTER)
    @Override
    public List<TMiStock> overInsured(TMiStock tMiStock) {
        QueryWrapper<TMiStock> wrapper = new QueryWrapper<>(tMiStock);
        wrapper.isNotNull("mark");
        return list(wrapper);
    }
}
