/*
 * 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.DeviceHandleInfoDto;
import com.tofly.stocks.dto.DeviceHandleInfoQuery;
import com.tofly.stocks.entity.*;
import com.tofly.stocks.service.DeviceHandleDetailService;
import com.tofly.stocks.service.DeviceHandleInfoService;
import com.tofly.stocks.service.StockInfoService;
import com.tofly.stocks.vo.DeviceHandleDetailVo;
import com.tofly.stocks.vo.DeviceHandleInfoVo;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
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 org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import com.tofly.stocks.mapper.DeviceHandleInfoMapper;

/**
 * 设备处置信息表
 *
 * @author admin
 * @date Fri Nov 25 00:00:00 CST 2022
 */
@Service("deviceHandleInfoService")
public class DeviceHandleInfoServiceImpl extends ServiceImpl<DeviceHandleInfoMapper, DeviceHandleInfo> implements DeviceHandleInfoService {

    @Autowired
    private IFileInfoService fileInfoService;

    @Autowired
    private DeviceHandleDetailService deviceHandleDetailService;

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

    @Autowired
    private StockInfoService stockInfoService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveDeviceHandleInfo(DeviceHandleInfoDto deviceHandleInfoDto, List<MultipartFile> files) {

        Boolean flag = false;

        if (CollectionUtils.isEmpty(deviceHandleInfoDto.getDeviceHandleDetails())) {
            throw new RuntimeException("处置明细单数据不能为空");
        }

        String baseNo = "SBCZ";

        Date now = new Date(); // 创建一个Date对象，获取当前时间
        String strDateFormat = "yyyyMM";
        String start_no = baseNo + DateFormatUtils.format(now, strDateFormat);
        //获取当天最大的采样编号
        String Sample_No = this.baseMapper.getDeviceHandleMaxNo(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 deviceHandleNo = start_no + end_no;

        DeviceHandleInfo data = new DeviceHandleInfo();
        BeanUtils.copyProperties(deviceHandleInfoDto, data);
        data.setHandleNo(deviceHandleNo);
        if (data.getHandleUserId() == null || data.getHandleUserId() == 0) {
            data.setHandleUserId(SecurityUtils.getUserId()); //默认入库人为当前登录人
        }
        if (data.getHandleDpt() == null || data.getHandleDpt() == 0) {
            data.setHandleDpt(SecurityUtils.getUserDeptId());
        }
        if(data.getDeviceType()==null || data.getDeviceType()==0){
            data.setDeviceType(62002L);//固定为设备
        }

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

        flag = this.save(data);
        //保存入库明细数据

        for (DeviceHandleDetail deviceHandleDetail : deviceHandleInfoDto.getDeviceHandleDetails()) {
            deviceHandleDetail.setHandleInfoId(data.getId());
            deviceHandleDetailService.save(deviceHandleDetail);
        }
        if (data.getHandleStatus() == 2) {  //已确认的
            AddStockInfo(deviceHandleInfoDto.getDeviceHandleDetails()); //加入库存
        }
        return flag;
    }


    /**
     * 更改库存
     *
     * @param deviceHandleDetails
     */
    private void AddStockInfo(List<DeviceHandleDetailVo> deviceHandleDetails) {

        for (DeviceHandleDetail detail : deviceHandleDetails) {
            StockInfo existStockInfo = stockInfoService.getById(detail.getStockInfoId());
            if (null == existStockInfo) {
                throw new RuntimeException("所选设备没有对应的库存，不能处置");
            }
            if (existStockInfo.getStockNum() < detail.getHandleNum()) {
                throw new RuntimeException("所选设备处置数量:" + detail.getHandleNum() + "，不能大于当前库存总数:" + existStockInfo.getStockNum());

            }
            StockInfo stockInfo = new StockInfo();
            stockInfo.setId(existStockInfo.getId());
            stockInfo.setHandleTotalNum(existStockInfo.getHandleTotalNum() + detail.getHandleNum());
            stockInfo.setStockNum(existStockInfo.getStockNum() - detail.getHandleNum());
            stockInfoService.updateById(stockInfo);
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean editDeviceHandleInfo(DeviceHandleInfoDto deviceHandleInfoDto, List<MultipartFile> files) {
        boolean flag;
        if (CollectionUtils.isEmpty(deviceHandleInfoDto.getDeviceHandleDetails())) {
            throw new RuntimeException("处置明细单数据不能为空");
        }

        DeviceHandleInfo deviceHandleInfo = this.getById(deviceHandleInfoDto.getId());
        if (deviceHandleInfo == null) {
            throw new RuntimeException("修改，参数Id错误");
        }
        if (deviceHandleInfo.getHandleStatus() == 2) {
            throw new RuntimeException("设备处置已确认的数据不能修改");
        }
        if (!deviceHandleInfo.getHandleUserId().equals(SecurityUtils.getUserId())) {
            throw new RuntimeException("只能修改自己创建的数据");
        }

        deviceHandleInfoDto.setHandleNo(deviceHandleInfo.getHandleNo());
        DeviceHandleInfo data = new DeviceHandleInfo();
        BeanUtils.copyProperties(deviceHandleInfoDto, data);

        data.setAnnex(fileInfoService.uploadFiles(files, data.getAnnex()
                , deviceHandleInfo.getAnnex(), path, "TF_STOCKS_DEVICE_HANDLE_INFO"));

        flag = this.updateById(data);

        deviceHandleDetailService.remove(Wrappers.<DeviceHandleDetail>lambdaQuery()
                .eq(DeviceHandleDetail::getHandleInfoId, data.getId()));

        for (DeviceHandleDetail deviceHandleDetail : deviceHandleInfoDto.getDeviceHandleDetails()) {
            deviceHandleDetail.setHandleInfoId(data.getId());
            deviceHandleDetailService.save(deviceHandleDetail);
        }
        if (data.getHandleStatus() == 2) { //已确认的
            AddStockInfo(deviceHandleInfoDto.getDeviceHandleDetails());
        }
        return flag;
    }

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

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

        //删除明细
        deviceHandleDetailService.remove(Wrappers.<DeviceHandleDetail>lambdaQuery()
                .in(DeviceHandleDetail::getHandleInfoId,lstIds));

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

    }

    @Override
    public Page<DeviceHandleInfoVo> getDataPage(Page page, DeviceHandleInfoQuery deviceHandleInfoQuery) {
        QueryWrapper<DeviceHandleInfo> queryWrapper = getDeviceTransInfoQueryWrapper(deviceHandleInfoQuery);

        return super.page(page, queryWrapper);

    }

    private static QueryWrapper<DeviceHandleInfo> getDeviceTransInfoQueryWrapper(DeviceHandleInfoQuery deviceHandleInfoQuery) {
        QueryWrapper<DeviceHandleInfo> queryWrapper = new QueryWrapper<>();
        if (deviceHandleInfoQuery.getHandleTimeStart() != null) {

            queryWrapper.ge("HANDLE_TIME", deviceHandleInfoQuery.getHandleTimeStart());
        }
        if (deviceHandleInfoQuery.getHandleTimeEnd() != null) {

            queryWrapper.le("HANDLE_TIME", deviceHandleInfoQuery.getHandleTimeEnd());
        }

        if (deviceHandleInfoQuery.getWaterworksId() != null && deviceHandleInfoQuery.getWaterworksId() > 0) {

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


        if (deviceHandleInfoQuery.getHandleStatus() != null && deviceHandleInfoQuery.getHandleStatus() > 0) {

            queryWrapper.eq("HANDLE_STATUS", deviceHandleInfoQuery.getHandleStatus());
        }
        if (StringUtil.isNotEmpty(deviceHandleInfoQuery.getHandleNo())){
            queryWrapper.like("HANDLE_NO", deviceHandleInfoQuery.getHandleNo());

        }

        queryWrapper.orderByDesc("CREATE_TIME");
        return queryWrapper;
    }

    @Override
    public List<DeviceHandleDetail> getDeviceHandleDetailByInfoId(Long deviceHandleInfoId) {
        return deviceHandleDetailService.list(Wrappers.<DeviceHandleDetail>lambdaQuery()
                .eq(DeviceHandleDetail::getHandleInfoId, deviceHandleInfoId));
    }

}
