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

import cn.hutool.core.collection.CollUtil;
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.haiqiu.tools.excel.utils.ExcelUtils;
import com.tofly.common.core.util.StringUtil;
import com.tofly.pojo.Syschildcode;
import com.tofly.stocks.dto.DeviceInfoQuery;
import com.tofly.stocks.dto.DeviceInfoStoreQuery;
import com.tofly.stocks.entity.*;
import com.tofly.stocks.service.DeviceInfoService;
import com.tofly.stocks.service.MaterialTypeService;
import com.tofly.stocks.service.StockInfoService;
import com.tofly.stocks.vo.*;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tofly.stocks.mapper.DeviceInfoMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 物资设备信息表（包含物料、设备、药品）
 *
 * @author admin
 * @date Fri Nov 25 00:00:00 CST 2022
 */
@Service("deviceInfoService")
public class DeviceInfoServiceImpl extends ServiceImpl<DeviceInfoMapper, DeviceInfo> implements DeviceInfoService {

    @Autowired
    private StockInfoService stockInfoService;

    @Autowired
    private MaterialTypeService materialTypeService;

    /**
     * 检查名称是否存在，用于修改和新增
     * @param deviceInfo
     * @return
     */
    public boolean isExist(DeviceInfo deviceInfo) {

        QueryWrapper<DeviceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("DEVICE_NAME", deviceInfo.getDeviceName());
        queryWrapper.eq("DEVICE_TYPE", deviceInfo.getDeviceType());

        if (deviceInfo.getId()!=null &&deviceInfo.getId()>0) {
            queryWrapper.ne("ID", deviceInfo.getId());
        }
        Integer count = baseMapper.selectCount(queryWrapper);

        if (count > 0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean saveDeviceInfo(DeviceInfo deviceInfo) {
         if(isExist(deviceInfo)){
             throw new RuntimeException("名称已存在，不能新增");
         }
         String baseNo="SBBM";
         if (deviceInfo.getDeviceType() == 62001) {
            baseNo="WLBM";
        } else if (deviceInfo.getDeviceType() == 62003) {
            baseNo="YPBM";
        }
        ;
        Date now = new Date(); // 创建一个Date对象，获取当前时间
        String strDateFormat = "yyyyMMdd";
        String start_no = baseNo + DateFormatUtils.format(now, strDateFormat);
        //获取当天最大的采样编号
        DeviceInfo deviceInfoMax=this.baseMapper.selectList(Wrappers.<DeviceInfo>lambdaQuery()
          .like(DeviceInfo::getDeviceNo,start_no).orderByDesc(DeviceInfo::getDeviceNo))
          .stream().findFirst().orElse(new DeviceInfo());

        String Sample_No="";
        if(deviceInfoMax!=null && StringUtil.isNotEmpty(deviceInfoMax.getDeviceNo())){
            Sample_No=deviceInfoMax.getDeviceNo();
        }

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

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

        String deviceNo = start_no + end_no;
        deviceInfo.setDeviceNo(deviceNo);
        return this.save(deviceInfo);
    }

    @Override
    public boolean editDeviceInfo(DeviceInfo deviceInfo) {
        if(isExist(deviceInfo)){
            throw new RuntimeException("名称已存在，不能修改");
        }
        return this.updateById(deviceInfo);
    }

    @Override
    public Page<DeviceInfoStoreVo> getDeviceStorelistPage(Page page, DeviceInfoStoreQuery deviceInfoStoreQuery) {
        return this.baseMapper.getDeviceStorelistPage(page,deviceInfoStoreQuery);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteByIds(String ids) {
        List<String> lstIds = Arrays.asList(ids.split(","));

       QueryWrapper<StockInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.in("DEVICE_ID",lstIds);
        Integer count=stockInfoService.count(queryWrapper);
        if(count>0){
            throw new RuntimeException("选择的设备已有库存记录，不能删除");
        }

        return this.removeByIds(lstIds);
    }

    @Override
    public void DeviceExport(DeviceInfo deviceInfo) {

        List<DeviceInfoExportVo> list = this.baseMapper.selectList(Wrappers.query(deviceInfo)).
                stream().map(deviceInfo_e -> {
                    DeviceInfoExportVo deviceInfoExportVo = new DeviceInfoExportVo();
            BeanUtils.copyProperties(deviceInfo_e, deviceInfoExportVo);
            return deviceInfoExportVo;
        }).collect(Collectors.toList());

        ExcelUtils.getListToExcel(DeviceInfoExportVo.class, list, "类型导出");

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean ImportData(MultipartFile file) {

        if(file==null||file.isEmpty()){
          throw new RuntimeException("导入文件不能为空");
        }

        List<DeviceInfoExportVo> dtos = null;
        try {
            dtos=getExeData(file,"");
        }catch (Exception e){
            throw new RuntimeException("文件异常");
        }
        if(CollUtil.isEmpty(dtos)){
            throw new RuntimeException("数据不存在");
        }
        //从字典里面获取对应的类别id
       List<Syschildcode> listDis=baseMapper.getDicByPcId(62000L);//物资类型id,固定
        if(listDis==null || listDis.stream().count()==0){
            throw new RuntimeException("物资类型字典不存在，请添加");
        }
        for (DeviceInfoExportVo deviceInfoExportVo:dtos
             ) {

            Syschildcode syschildcode= listDis.stream().filter(a->a.getCname().equals(deviceInfoExportVo.getDeviceTypeName())
                    &&a.getCdisable().equals("1")).findAny().orElse(null);
            if(syschildcode==null){
                throw new RuntimeException("类别：["+deviceInfoExportVo.getDeviceTypeName()+"]不存在，请添加字典");

            }
            Long deviceType=syschildcode.getId();


          //根据类别id和类型名称获取类型id
           Long materialTypeId=materialTypeService.getOne(
                    Wrappers.<MaterialType>lambdaQuery()
                            .eq(MaterialType::getMaterialCategoryId,deviceType)
                            .eq(MaterialType::getMaterialTypeName,deviceInfoExportVo.getMaterialTypeName())
            ).getId();
            if(materialTypeId==null || materialTypeId==0){
                throw new RuntimeException("类别:["+deviceInfoExportVo.getDeviceTypeName()+"]下类型：["+deviceInfoExportVo.getMaterialTypeName()+"]不存在，请先添加对应的类型");
            }
            DeviceInfo deviceInfo=new DeviceInfo();
            BeanUtils.copyProperties(deviceInfoExportVo,deviceInfo);
            deviceInfo.setDeviceType(deviceType);
            deviceInfo.setMaterialTypeId(materialTypeId);
            //名称存在了，直接跳过
            if(!isExist(deviceInfo)){
                this.save(deviceInfo);
            }

        }

        return true;
    }

    @Override
    public Page<DeviceRepairVo> getDeviceRepairListPage(Page page, Long deviceId) {
        Page<DeviceRepairVo> list=new Page<>();
        SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
        Date d=new Date();
        System.out.println("今天的日期："+df.format(d));
        List<DeviceRepairVo> list_m=new ArrayList<>();
         for (int i=1;i<11;i++){
             DeviceRepairVo vo=new DeviceRepairVo();
             Random random=new Random();
            vo.setRepairCount(random.nextInt(20));
            vo.setRepairTypeName("维修类型");
            vo.setDispatchUser("张三"+i);
            vo.setDispatchState("已维修");
            vo.setDispatchTime(new Date());
            vo.setRepairStartTime(new Date(d.getTime()-i*24*60 * 60 * 1000));
            vo.setRepairEndTime(new Date(vo.getRepairStartTime().getTime()+10 * 60 * 60 * 1000));

             list_m.add(vo);
         }
        list.setRecords(list_m);

        list.setTotal(list_m.stream().count());
        return list;
    }

    @Override
    public Page<DeviceMaintainVo> getDeviceMaintainListPage(Page page, Long deviceId) {
        Page<DeviceMaintainVo> list=new Page<>();
        List<DeviceMaintainVo> list_m=new ArrayList<>();
        Date d=new Date();
        for (int i=1;i<11;i++){

        DeviceMaintainVo vo=new DeviceMaintainVo();
        vo.setMaintainTypeName("保养类型"+i);

            vo.setDispatchUser("张三"+i);
            vo.setDispatchState("已维修");
            vo.setDispatchTime(new Date());
            vo.setMaintainStartTime(new Date(d.getTime()-i*24*60 * 60 * 1000));
            vo.setMaintainEndTime(new Date(vo.getMaintainStartTime().getTime()+10 * 60 * 60 * 1000));

            list_m.add(vo);
    }
        list.setRecords(list_m);
        list.setTotal(list_m.stream().count());

        return list;
    }

    @Override
    public Page<DevicePatrolVo> getDevicePatrolListPage(Page page, Long deviceId) {
            Date d=new Date();
        Page<DevicePatrolVo> list=new Page<>();
        List<DevicePatrolVo> list_m=new ArrayList<>();
        for (int i=1;i<11;i++){

            DevicePatrolVo vo=new DevicePatrolVo();
            vo.setPatrolCategory("巡检类别"+i);
            vo.setPatrolType("巡检类型"+i);
            vo.setPatrolUser("张三"+i);
            vo.setPatrolStartTime(new Date(d.getTime()-i*24*60 * 60 * 1000));
            vo.setPatrolEndTime(new Date(vo.getPatrolStartTime().getTime()+10 * 60 * 60 * 1000));

            vo.setPatrolState("巡检状态"+i);
            list_m.add(vo);
        }
        list.setRecords(list_m);
        list.setTotal(list_m.stream().count());
        return list;

    }

    @Override
    public DeviceReportVo getDeviceReport(Long deviceId) {
        DeviceReportVo deviceReportVo=new DeviceReportVo();
        Page page=new Page();
        page.setSize(1);
        page.setCurrent(1);

        deviceReportVo.setRepairCount(this.getDeviceRepairListPage(page,deviceId).getTotal());
        deviceReportVo.setMaintainCount(this.getDeviceMaintainListPage(page,deviceId).getTotal());
        deviceReportVo.setPatrolCount(this.getDevicePatrolListPage(page,deviceId).getTotal());

        return deviceReportVo;
    }

    @Override
    public Page<DeviceInfo> getDataPage(Page page, DeviceInfoQuery query) {
      return this.baseMapper.getDataPage(page,query);
    }

    /**
     * 文件转换为对象数据
     * @param fileList 上传的文件
     * @param sheetName sheet名称
     * @return List<DispatchInfoDto>
     * @throws Exception
     */
    private List<DeviceInfoExportVo> getExeData(MultipartFile fileList, String sheetName) throws Exception {
        InputStream inputStream = fileList.getInputStream();
        com.tofly.common.core.util.io.ExcelUtil opsExcel = new com.tofly.common.core.util.io.ExcelUtil(DeviceInfoExportVo.class);
        List<DeviceInfoExportVo> ips = opsExcel.importExcel(sheetName, inputStream);
        return ips;
    }
}
