/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.stocks.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.common.core.util.StringUtil;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.common.service.IFileInfoService;
import com.tofly.stocks.dto.OutstockInfoDto;
import com.tofly.stocks.dto.OutstockInfoQuery;
import com.tofly.stocks.entity.*;
import com.tofly.stocks.service.OutstockDetailService;
import com.tofly.stocks.service.OutstockInfoService;
import com.tofly.stocks.service.StockInfoService;
import com.tofly.stocks.vo.InstockDetailVo;
import com.tofly.stocks.vo.OutstockDetailVo;
import com.tofly.stocks.vo.OutstockInfoVo;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.tofly.stocks.mapper.OutstockInfoMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 库存出库信息表
 *
 * @author admin
 * @date Fri Nov 25 00:00:00 CST 2022
 */
@Service("outstockInfoService")
public class OutstockInfoServiceImpl extends ServiceImpl<OutstockInfoMapper, OutstockInfo> implements OutstockInfoService {

    @Autowired
    private IFileInfoService fileInfoService;

    @Autowired
    private OutstockDetailService outstockDetailService;

    @Value("${flow.ftp.stocks.outstock}")
    private String path;


    @Autowired
    private StockInfoService stockInfoService;


    private String getRkType(Integer type){
        String str="";
        switch (type){
            case 1:
                str="WZCK";
                break;
            case 2:
                str="SBCK";
                break;
            case 3:
                str="YPCK";
                break;
            default:
                break;
        }
        if(StringUtil.isEmpty(str)){
            throw new RuntimeException("出库类型错误");
        }
        return str;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOutstockInfo(OutstockInfoDto outstockInfoDto, List<MultipartFile> files) {
        boolean flag;
        if (CollectionUtils.isEmpty(outstockInfoDto.getOutstockDetails())) {
            throw new RuntimeException("入库明细单数据不能为空");
        }
        String baseNo=getRkType(outstockInfoDto.getOutstockCategory());

        Date now = new Date(); // 创建一个Date对象，获取当前时间
        String strDateFormat = "yyyyMM";
        String start_no = baseNo + DateFormatUtils.format(now, strDateFormat);
        //获取当天最大的采样编号
        String Sample_No = this.baseMapper.getOutstockMaxNo(start_no);

        int firstNum = 1;
        if (Sample_No.length() == 14) {
            firstNum = Integer.parseInt(Sample_No.substring(11)) + 1;
        }

        String end_no = String.format("%04d", firstNum); //补全数字，不足用0补位

        String outstockNo = start_no + end_no;

        OutstockInfo data = new OutstockInfo();
        BeanUtils.copyProperties(outstockInfoDto, data);
        data.setOutstockNo(outstockNo); //赋值单号

        data.setOutstockUserId(SecurityUtils.getUserId()); //默认入库人为当前登录人
        data.setOutstockDpt(SecurityUtils.getUserDeptId());

        //附件
        data.setAnnex(fileInfoService.uploadFiles(files,data.getAnnex()
                ,data.getAnnex(),path,"TF_STOCKS_OUTSTOCK_INFO"));

        flag = this.save(data);
        //保存入库明细数据
        for (OutstockDetail outstockDetail : outstockInfoDto.getOutstockDetails()
        ) {
            outstockDetail.setOutstockInfoId(data.getId());
            outstockDetail.setId(null);
            outstockDetailService.save(outstockDetail);
        }
        if(data.getOutstockStatus()==2){ //已确认的
            AddStockInfo(outstockInfoDto.getOutstockDetails()); //加入库存
        }
        return flag;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean editOutstockInfo(OutstockInfoDto outstockInfoDto, List<MultipartFile> files) {
        boolean flag;
        OutstockInfo outstockInfo = this.getById(outstockInfoDto.getId());
        if (outstockInfo == null) {
            throw new RuntimeException("修改，参数Id错误");
        }
        if (outstockInfo.getOutstockStatus()==2) {
            throw new RuntimeException("已确认出库的数据不能修改");
        }
        if (!outstockInfoDto.getOutstockUserId().equals(SecurityUtils.getUserId())) {
            throw new RuntimeException("只能修改自己创建的数据");
        }
        outstockInfoDto.setOutstockNo(outstockInfo.getOutstockNo());
        OutstockInfo data = new OutstockInfo();
        BeanUtils.copyProperties(outstockInfoDto, data);

        data.setAnnex(fileInfoService.uploadFiles(files,data.getAnnex()
                ,outstockInfo.getAnnex(),path,"TF_STOCKS_OUTSTOCK_INFO"));

        flag = this.updateById(data);

        outstockDetailService.remove(Wrappers.<OutstockDetail>lambdaQuery()
                .eq(OutstockDetail::getOutstockInfoId,data.getId()));


        for (OutstockDetail outstockDetail : outstockInfoDto.getOutstockDetails()
        ) {
            outstockDetail.setOutstockInfoId(data.getId());
            outstockDetailService.save(outstockDetail);
        }
        if(data.getOutstockStatus()==2){ //已确认的
            AddStockInfo(outstockInfoDto.getOutstockDetails()); //加入库存
        }
        return flag;
    }




    /**
     * 出库
     * @param outstockDetails
     */
    private  void  AddStockInfo(List<OutstockDetailVo> outstockDetails){
        for (OutstockDetail detail: outstockDetails) {
        	StockInfo existStockInfo = stockInfoService.getById(detail.getStockInfoId());
        	if(null == existStockInfo) {
        		 throw new RuntimeException("所选设备【"+detail.getDeviceName()+"】没有对应的库存，不能出库");
        	}
            if(existStockInfo.getStockNum()<detail.getOutstockNum()){
                 throw new RuntimeException("所选设备【"+detail.getDeviceName()+"】出库数量:"+detail.getOutstockNum()+"，不能大于当前库存总数:"+existStockInfo.getStockNum());

            }
            StockInfo stockInfo=new StockInfo();
            stockInfo.setId(existStockInfo.getId());
            stockInfo.setOutstockTotalNum(existStockInfo.getOutstockTotalNum()+detail.getOutstockNum());
            stockInfo.setStockNum(existStockInfo.getStockNum()-detail.getOutstockNum());
            stockInfoService.updateById(stockInfo);
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteByIds(String ids) {
        List<String> lstIds = Arrays.asList(ids.split(","));
        Integer count= this.count(Wrappers.<OutstockInfo>lambdaQuery()
                .in(OutstockInfo::getId,lstIds)
                        .and(a->a.eq(OutstockInfo::getOutstockStatus,2)
                                .or().ne(OutstockInfo::getOutstockUserId,SecurityUtils.getUserId()))

        );
        if(count>0){
            throw new RuntimeException("只能删除自己创建的并且没有确认的数据");
        }

        //删除明细
        outstockDetailService.remove(Wrappers.<OutstockDetail>lambdaQuery()
                .in(OutstockDetail::getOutstockInfoId,lstIds));

        //删除主表
        return this.removeByIds(lstIds);

    }

    @Override
    public Page<OutstockInfoVo> getDataPage(Page page, OutstockInfoQuery outstockInfoQuery) {
        QueryWrapper<OutstockInfo> queryWrapper = getOutstockInfoQueryWrapper(outstockInfoQuery);
        return super.page(page,queryWrapper);
    }

    /**
     * 查询条件拼接
     * @param outstockInfoQuery
     * @return
     */
    private  QueryWrapper<OutstockInfo> getOutstockInfoQueryWrapper(OutstockInfoQuery outstockInfoQuery) {
        QueryWrapper<OutstockInfo> queryWrapper=new QueryWrapper<>();

        if(outstockInfoQuery.getOutstockCategory()!=null && outstockInfoQuery.getOutstockCategory()>0){

            queryWrapper.eq("OUTSTOCK_CATEGORY", outstockInfoQuery.getOutstockCategory());
        }

        if(outstockInfoQuery.getOutstockTimeStart()!=null){

            queryWrapper.ge("OUTSTOCK_TIME", outstockInfoQuery.getOutstockTimeStart());
        }
        if(outstockInfoQuery.getOutstockTimeEnd()!=null){

            queryWrapper.le("OUTSTOCK_TIME", outstockInfoQuery.getOutstockTimeEnd());
        }

        if(StringUtil.isNotEmpty(outstockInfoQuery.getOutstockNo())){

            queryWrapper.like("OUTSTOCK_NO", outstockInfoQuery.getOutstockNo());
        }

        if(outstockInfoQuery.getStoreId()!=null && outstockInfoQuery.getStoreId()>0){

            queryWrapper.eq("STORE_ID", outstockInfoQuery.getStoreId());
        }
        if(outstockInfoQuery.getWaterworksId()!=null && outstockInfoQuery.getWaterworksId()>0){

            queryWrapper.eq("WATERWORKS_ID", outstockInfoQuery.getWaterworksId());
        }

        if(outstockInfoQuery.getOutstockTypeId()!=null && outstockInfoQuery.getOutstockTypeId()>0){

            queryWrapper.eq("OUTSTOCK_TYPE_ID", outstockInfoQuery.getOutstockTypeId());
        }
        if(outstockInfoQuery.getBuninessType()!=null && outstockInfoQuery.getBuninessType()>0){

            queryWrapper.eq("BUNINESS_TYPE", outstockInfoQuery.getBuninessType());
        }

        if(outstockInfoQuery.getOutstockStatus()!=null && outstockInfoQuery.getOutstockStatus()>0){

            queryWrapper.eq("OUTSTOCK_STATUS", outstockInfoQuery.getOutstockStatus());
        }
        queryWrapper.orderByDesc("CREATE_TIME");

        return queryWrapper;
    }


}
