package com.xunmei.core.retrieval.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xunmei.common.core.constant.ErrorMsgConstants;
import com.xunmei.common.core.constant.SecurityConstants;
import com.xunmei.common.core.utils.DateHelper;
import com.xunmei.common.core.web.page.TableDataInfo;
import com.xunmei.core.access.dto.CoreMonitoringTaskRegistrationDTO;
import com.xunmei.common.core.domain.retrieval.domain.CoreMonitoringRetrievalTask;
import com.xunmei.common.core.domain.retrieval.dto.RetrievalTaskPageDto;
import com.xunmei.core.retrieval.mapper.CoreMonitoringRetrievalTaskMapper;
import com.xunmei.core.retrieval.service.ICoreMonitoringRetrievalTaskService;
import com.xunmei.common.core.domain.retrieval.vo.CoreMonitoringRetrievalTaskVo;
import com.xunmei.system.api.RemoteDictDataService;
import com.xunmei.system.api.RemoteOrgService;
import com.xunmei.system.api.domain.SysDictData;
import com.xunmei.system.api.domain.SysOrg;
import com.xunmei.system.api.function.RemoteCallHandlerExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


/**
 * 监控调阅任务Service业务层处理
 *
 * @author xunmei
 * @date 2023-08-25
 */
@Service
public class CoreMonitoringRetrievalTaskServiceImpl extends ServiceImpl<CoreMonitoringRetrievalTaskMapper, CoreMonitoringRetrievalTask> implements ICoreMonitoringRetrievalTaskService {
    @Resource
    private CoreMonitoringRetrievalTaskMapper coreMonitoringRetrievalTaskMapper;
    @Resource
    private RemoteOrgService orgService;
    @Resource
    private RemoteDictDataService dictDataService;

    @Override
    public TableDataInfo selectPage(RetrievalTaskPageDto request) {

        Page<CoreMonitoringRetrievalTaskVo> page;
        //分页
        if (request.getPageNum()!=null&&request.getPageSize()!=null)
        {
            page = new Page<>(request.getPageNum(), request.getPageSize());
        }else{
            page = new Page<>();
        }
        //下穿
        if (request.getCheckSub()) {
            SysOrg sysOrg = RemoteCallHandlerExecutor.executeRemoteCall(() -> orgService.selectTopOrg(SecurityConstants.INNER), ErrorMsgConstants.QUERY_ORG_DATA_ERROR);
            request.setOrgPath(sysOrg.getPath());
            request.setOrgId(null);
        }
        //获取数据
        page = coreMonitoringRetrievalTaskMapper.selectPageList(page, request);
        //抓换为TableDataInfo适配前端
        return TableDataInfo.build(page);
    }

    @Override
    public void export(RetrievalTaskPageDto request, HttpServletResponse response) throws IOException {
        //不分页
        request.setPageSize(null);
        request.setPageNum(null);
        SysOrg sysOrg = RemoteCallHandlerExecutor.executeRemoteCall(() -> orgService.selectTopOrg(SecurityConstants.INNER), ErrorMsgConstants.QUERY_ORG_DATA_ERROR);
        List<SysDictData>  listDict = RemoteCallHandlerExecutor.executeRemoteCall(() -> dictDataService.dictType("retrieval_task_status", SecurityConstants.INNER), ErrorMsgConstants.QUERY_DICT_DATA_ERROR);
        final TableDataInfo tableDataInfo = this.selectPage(request);
        if (ObjectUtil.isEmpty(tableDataInfo.getRows())) {
            throw new RuntimeException("导出数据为空!");
        }
        List<CoreMonitoringRetrievalTaskVo> list = this.selectPage(request).getRows();
        list.forEach(r->{
            r.setStatusText(listDict.stream().filter(d->d.getDictValue().equals(r.getStatus())).findFirst().orElse(new SysDictData()).getDictLabel());
        });
        list.forEach(r->r.setNo(list.indexOf(r)+1));
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.addHeaderAlias("序号", "no");
        writer.addHeaderAlias("任务名称", "taskName");
        writer.addHeaderAlias("开始时间", "planStartTime");
        writer.addHeaderAlias("结束时间", "planEndTime");
        writer.addHeaderAlias("状态", "statusText");
        writer.addHeaderAlias("调阅机构", "orgName");
        writer.addHeaderAlias("调阅角色", "roleName");
        writer.addHeaderAlias("调阅开始时间", "startTime");
        writer.addHeaderAlias("调阅结束时间", "endTime");
        writer.addHeaderAlias("调阅人", "retrievalUserName");
        writer.addHeaderAlias("异常数", "exceptionCount");
        //只保留别名的数据
        writer.setOnlyAlias(true);
        // 默认配置
        writer.write(list, true);
        // 设置content—type
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset:utf-8");
        // 设置标题
        String fileName = URLEncoder.encode("【" + sysOrg.getName() + "】-监控调阅任务记录" + DateHelper.getDateString(new Date()), "UTF-8");
        //Content-disposition是MIME协议的扩展，MIME协议指示MIME用户代理如何显示附加的文件。
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".et");
        ServletOutputStream outputStream = response.getOutputStream();
        //将Writer刷新到OutPut
        writer.flush(outputStream, true);
        outputStream.close();
        writer.close();
    }

    @Override
    public List<CoreMonitoringRetrievalTask> selectListApp(CoreMonitoringTaskRegistrationDTO coreMonitoringTaskRegistrationDTO) {
        return baseMapper.selectListApp(coreMonitoringTaskRegistrationDTO);
    }


    /**
     * 查询监控调阅任务
     *
     * @param id 监控调阅任务主键
     * @return 监控调阅任务
     */
    @Override
    public CoreMonitoringRetrievalTask selectCoreMonitoringRetrievalTaskById(Long id) {
        return coreMonitoringRetrievalTaskMapper.selectById(id);
    }

    /**
     * 查询监控调阅任务列表
     *
     * @param CoreMonitoringRetrievalTask 监控调阅任务
     * @return 监控调阅任务
     */
    @Override
    public List<CoreMonitoringRetrievalTask> selectCoreMonitoringRetrievalTaskList(CoreMonitoringRetrievalTask CoreMonitoringRetrievalTask) {
        return coreMonitoringRetrievalTaskMapper.selectList(new QueryWrapper<>(CoreMonitoringRetrievalTask));
    }

    /**
     * 新增监控调阅任务
     *
     * @param CoreMonitoringRetrievalTask 监控调阅任务
     * @return 结果
     */
    @Override
    public int insertCoreMonitoringRetrievalTask(CoreMonitoringRetrievalTask CoreMonitoringRetrievalTask) {
            return coreMonitoringRetrievalTaskMapper.insert(CoreMonitoringRetrievalTask);
    }

    /**
     * 修改监控调阅任务
     *
     * @param CoreMonitoringRetrievalTask 监控调阅任务
     * @return 结果
     */
    @Override
    public int updateCoreMonitoringRetrievalTask(CoreMonitoringRetrievalTask CoreMonitoringRetrievalTask) {
        return coreMonitoringRetrievalTaskMapper.updateById(CoreMonitoringRetrievalTask);
    }

    /**
     * 批量删除监控调阅任务
     *
     * @param ids 需要删除的监控调阅任务主键
     * @return 结果
     */
    @Override
    public int deleteCoreMonitoringRetrievalTaskByIds(Long[] ids) {
        return coreMonitoringRetrievalTaskMapper.deleteBatchIds(Arrays.asList((ids)));
    }

    /**
     * 删除监控调阅任务信息
     *
     * @param id 监控调阅任务主键
     * @return 结果
     */
    @Override
    public int deleteCoreMonitoringRetrievalTaskById(Long id) {
        return coreMonitoringRetrievalTaskMapper.deleteById(id);
    }
}
