package com.rongwei.bscommon.sys.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rongwei.bscommon.sys.dao.CommonDao;
import com.rongwei.bscommon.sys.dao.EquLubricationTaskManagementMapperDao;
import com.rongwei.bscommon.sys.service.EquLubricationTaskDetailService;
import com.rongwei.bscommon.sys.service.EquLubricationTaskManagementService;
import com.rongwei.bscommon.sys.utils.ExceptionUtils;
import com.rongwei.bscommon.sys.utils.TimeUtils;
import com.rongwei.bsentity.domain.EquLubricationTaskDetailVo;
import com.rongwei.bsentity.domain.EquLubricationTaskManagementDo;
import com.rongwei.rwadmincommon.system.domain.SysDictDo;
import com.rongwei.rwadmincommon.system.service.SysDictService;
import com.rongwei.rwcommon.base.BaseDo;
import com.rongwei.rwcommon.utils.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 设备子系统——润滑任务管理 服务实现类
 * </p>
 *
 * @author fpy
 * @since 2024-01-12
 */
@Service
public class EquLubricationTaskManagementServiceImpl extends ServiceImpl<EquLubricationTaskManagementMapperDao, EquLubricationTaskManagementDo> implements EquLubricationTaskManagementService {
    private final Logger log = LoggerFactory.getLogger(this.getClass().getName());

    @Autowired
    private EquLubricationTaskDetailService equLubricationTaskDetailService;

    @Autowired
    private CommonDao commonDao;

    @Autowired
    private SysDictService sysDictService;

    @Autowired
    private EquLubricationTaskManagementMapperDao lubricationTaskManagementMapperDao;

    @Override
    public void wordExportLubricationTask(Map<String, Object> parameter, HttpServletResponse response) {
        log.info("开始导出润滑任务明细");
        String tenantId = parameter.get("userTopOrg").toString();
        List<EquLubricationTaskDetailVo> taskDetailVoList = equLubricationTaskDetailService.queryAllTaskDetailList(tenantId);
        List<SysDictDo> isEnableType = sysDictService.getDictsByType("lubricationIsEnable");
        List<SysDictDo> frequencyByType = sysDictService.getDictsByType("lubricationFrequency");
        List<SysDictDo> ynByType = sysDictService.getDictsByType("srm_yn");
        try {
            response.setContentType("application/octet-stream");
            // 读取模板文件
            TemplateExportParams params = new TemplateExportParams("template/润滑任务明细模板.xls",0);
            Map<String, Object> dataMap = new HashMap<>(16);
            List<Map<String,Object>> dataList = new ArrayList<>();
            for (EquLubricationTaskDetailVo equLubricationTaskDetailVo : taskDetailVoList) {
                String frequency = "";
                if (StringUtils.isNotBlank(equLubricationTaskDetailVo.getFrequency())) {
                    frequency = frequencyByType.stream().filter(dictDo -> equLubricationTaskDetailVo.getFrequency().contains(dictDo.getValue()))
                            .map(SysDictDo::getName).collect(Collectors.joining(","));
                    equLubricationTaskDetailVo.setFrequency(frequency);
                }
                String yn = "";
                if (StringUtils.isNotBlank(equLubricationTaskDetailVo.getIslubricationcompleted())) {
                    yn = ynByType.stream().filter(dictDo -> equLubricationTaskDetailVo.getIslubricationcompleted().contains(dictDo.getValue()))
                            .map(SysDictDo::getName).collect(Collectors.joining(","));
                    equLubricationTaskDetailVo.setIslubricationcompleted(yn);
                }
                String isEnable = "";
                if (StringUtils.isNotBlank(equLubricationTaskDetailVo.getEnablestatus())) {
                    isEnable = isEnableType.stream().filter(dictDo -> equLubricationTaskDetailVo.getEnablestatus().contains(dictDo.getValue()))
                            .map(SysDictDo::getName).collect(Collectors.joining(","));
                    equLubricationTaskDetailVo.setEnablestatus(isEnable);
                }
                if (equLubricationTaskDetailVo.getCompletedate()!= null){
                    String formatDate = TimeUtils.dateToString(equLubricationTaskDetailVo.getCompletedate(),"yyyy-MM-dd");
                    equLubricationTaskDetailVo.setCompletedateshow(formatDate);
                }
                dataList.add(JSONObject.parseObject(JSONObject.toJSONString(equLubricationTaskDetailVo), Map.class));
            }
            dataMap.put("list",dataList);
            Workbook workbook = ExcelExportUtil.exportExcel(params,dataMap);
            workbook.write(response.getOutputStream());
            workbook.close();
        }catch (Exception e){
            ExceptionUtils.printExceptionDetail(e,"润滑任务明细导出异常");
        }
    }

    @Override
    public List<EquLubricationTaskManagementDo> getListByTimeQuantum(int year, int month, boolean stride) {
        LambdaQueryWrapper<EquLubricationTaskManagementDo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(EquLubricationTaskManagementDo::getTaskstatus, Arrays.asList(10,20,70))
                // .lt(BaseDo::getCreatedate, year)
                // .gt(BaseDo::getCreatedate, month)
                .eq(BaseDo::getDeleted,0);

        //跨月
        queryWrapper.and(stride,query ->query
                .eq(EquLubricationTaskManagementDo::getYear,year)
                .lt(EquLubricationTaskManagementDo::getMonth,month)
                .or()
                .eq(EquLubricationTaskManagementDo::getYear,year-1)
                .ge(EquLubricationTaskManagementDo::getMonth,month));
        //月末
        queryWrapper.and(!stride,query -> query
                .eq(EquLubricationTaskManagementDo::getYear,year)
                .eq(EquLubricationTaskManagementDo::getMonth,month));
        return lubricationTaskManagementMapperDao.selectList(queryWrapper);
    }
}
