package com.rongwei.bscommon.sys.service.impl;
import cn.hutool.core.io.resource.ClassPathResource;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rongwei.bscommon.sys.dao.EquMaintenanceOrderDao;
import com.rongwei.bscommon.sys.service.EquMaintenanceOrderService;
import com.rongwei.bscommon.sys.utils.ExcelUtils;
import com.rongwei.bsentity.domain.EquMaintenanceOrderDo;
import com.rongwei.bsentity.dto.EquMaintenanceOrderSumDTO;
import com.rongwei.bsentity.enums.PlantEnum;
import com.rongwei.rwadmincommon.system.service.SysDictService;
import com.rongwei.rwcommonentity.commonservers.domain.SysFileItemDo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.rongwei.safecommon.utils.SaveConstans.DatePattern.DATE_PATTERN_YMD;
import static com.rongwei.safecommon.utils.SaveConstans.FileName.DEVICE_REPEATEDLY_FAILS_FILE_NAME;
import static com.rongwei.safecommon.utils.SaveConstans.FileSuffix.XLSX;
import static com.rongwei.safecommon.utils.SaveConstans.TemplatePath.DEVICE_REPEATEDLY_FAILS_TEMPLATE_NAME;

@Service
@Slf4j
public class EquMaintenanceOrderServiceImpl extends ServiceImpl<EquMaintenanceOrderDao, EquMaintenanceOrderDo> implements EquMaintenanceOrderService {

    @Autowired
    EquMaintenanceOrderDao equMaintenanceOrderDao;

    @Autowired
    private SysDictService sysDictService;


    /**
     * 根据故障发生时间自动查询每个工厂近3个月内 (以本月在往前倒推三个月至当前时间)所有 除去 无需维修、已关闭  且  维修对象分类 为 档案设备、工装 的 维修任务记录中，
      * 然后根据所属工厂、设备类型、发生部位 分组查询对应分组类型的 数量记录 中 > 1的记录
      * @return
      */
    @Override
    public List<EquMaintenanceOrderSumDTO> selectOrderSummaryData() {
        Date startDate = getBeforeThreeMonthDate();
        return equMaintenanceOrderDao.selectOrderSummaryData(startDate,new Date());
    }

    @Override
    public List<EquMaintenanceOrderDo> selectOrderDataByIds(String ids) {
        return equMaintenanceOrderDao.selectOrderDataByIds(ids);
    }

    @Override
    public List<String> selectRoleList(List<String> roleCode) {
        return equMaintenanceOrderDao.selectRoleList(roleCode);
    }

    /**
     * 获取3月前的时间
     *
     * @return
     */
    private Date getBeforeThreeMonthDate() {
        // 创建一个Calendar实例
        Calendar calendar = Calendar.getInstance();
        // 将Calendar实例设置为当前时间
        calendar.setTimeInMillis(System.currentTimeMillis());
        // 减去3个月的时间
        calendar.add(Calendar.MONTH, -3);
        // 将日期设置为1号
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        // 将时分秒设置为00:00:00
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        log.info("开始时间{}", calendar.getTime());
        return calendar.getTime();
    }




    /**
     * 生成 备部位重复故障问题 excel 记录
     *
     * @param
     * @param noticeId
     * @return
     */
    @Override
    public String generateDeviceRepeatedlyFailsExcel(List<EquMaintenanceOrderSumDTO> list, String noticeId) {

        SysFileItemDo fileItemDo=null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_PATTERN_YMD);
        try {
            //1.获取模板
            ClassPathResource classPathResource = new ClassPathResource(DEVICE_REPEATEDLY_FAILS_TEMPLATE_NAME);
            InputStream inputStream = classPathResource.getStream();
            HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
            HSSFSheet sheet0 = workbook.getSheetAt(0);
            HSSFSheet sheet1 = workbook.getSheetAt(1);
            HSSFSheet sheet2 = workbook.getSheetAt(2);
            HSSFSheet sheet3 = workbook.getSheetAt(3);
            //2.填充数据
            //2.1 给第一页数据填充数据
            for (int i = 0; i < list.size() ; i++) {
                // 创建行
                HSSFRow row = sheet0.createRow(i + 1);
                row.createCell(0).setCellValue(list.get(i).getPlant()); // 所属工厂
                row.createCell(1).setCellValue(list.get(i).getDevicetype());  //设备类型
                row.createCell(2).setCellValue(list.get(i).getProblemlocation());  //发生部位
                row.createCell(3).setCellValue(list.get(i).getCount()); //数量
            }

            //获取后面3页工厂的数据,通过ids 获取所有数据
            String ids = list.stream()
                    .map(obj -> String.valueOf(obj.getIds()))
                    .collect(Collectors.joining(","));
            List<EquMaintenanceOrderDo> dos = selectOrderDataByIds(ids);
            //根据工厂进行分组
            Map<String, List<EquMaintenanceOrderDo>> listMap = dos.stream()
                    .collect(Collectors.groupingBy(EquMaintenanceOrderDo::getTenantid));
            //2.2板材
            fillPlantData(listMap.get(PlantEnum.CXBC.getId()), sheet1);
            //2.3精铝
            fillPlantData(listMap.get(PlantEnum.CXJL.getId()), sheet2);
            //2.4箔材
            fillPlantData(listMap.get(PlantEnum.CXLB.getId()), sheet3);
            //3数据填充生成文件
          //  String id = ExcelUtils.feginCommonUpload(workbook, DEVICE_REPEATEDLY_FAILS_FILE_NAME);
            return ExcelUtils.feginCommonUpload(workbook,noticeId,DEVICE_REPEATEDLY_FAILS_FILE_NAME + simpleDateFormat.format(new Date()) + XLSX );

        } catch (Exception e) {
            log.error("生成设备部位重复故障excel 失败：{}",e.getMessage());

        }
        return "";
    }

    /**
     * 填充后3页工厂数据
     *
     * @param list
     * @param sheet
     */
    private void fillPlantData(List<EquMaintenanceOrderDo> list, HSSFSheet sheet) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < list.size() ; i++) {
            // 创建行
            HSSFRow row = sheet.createRow(i + 1);
            row.createCell(0).setCellValue(list.get(i).getJobnumber()); //工单编号
            row.createCell(1).setCellValue(list.get(i).getPlant());  //所属工厂
            row.createCell(2).setCellValue(list.get(i).getWorkshop()); //使用车间
            row.createCell(3).setCellValue(list.get(i).getEquipmentname()); //设备名称
            row.createCell(4).setCellValue(list.get(i).getEquipmentnumber()); //设备编号
            row.createCell(5).setCellValue(list.get(i).getIncidenttime() == null ? "" : dateFormat.format(list.get(i).getIncidenttime())); //故障发生时间
            row.createCell(6).setCellValue(list.get(i).getProblemlocation()); //问题发生部位
            row.createCell(7).setCellValue(list.get(i).getFaultcondition()); //设备故障情况
            row.createCell(8).setCellValue(list.get(i).getIshalt() == null ? "" : sysDictService.getDictNameByValue("YORN", list.get(i).getIshalt())); //是否停机
            row.createCell(9).setCellValue(list.get(i).getHalttime() == null ? "" : dateFormat.format(list.get(i).getHalttime())); //停机时间
            row.createCell(10).setCellValue(list.get(i).getCreateusername()); //报修申请人
            row.createCell(11).setCellValue(list.get(i).getServiceperson()); //维修人
            row.createCell(12).setCellValue(list.get(i).getCausefailure()); //故障发生原因
            row.createCell(13).setCellValue(list.get(i).getResult()); //维修结果
            row.createCell(14).setCellValue(list.get(i).getRepairstatus() == null ? "" : sysDictService.getDictNameByValue("maintenance_state", list.get(i).getRepairstatus()));  //维修状态
        }
    }

}
