package com.docus.server.service.impl;

import com.docus.core.util.DateUtil;
import com.docus.core.util.ListUtils;
import com.docus.core.util.json.JSON;
import com.docus.core.util.property.Setters;
import com.docus.infrastructure.redis.service.IdService;
import com.docus.infrastructure.web.request.SearchDTO;
import com.docus.infrastructure.web.response.PageResult;
import com.docus.server.convert.SchCollectRecordRetryLogConvert;
import com.docus.server.dto.scheduling.management.schcollector.task.ReportDownTwoDTO;
import com.docus.server.dto.scheduling.management.schcollectrecordretrylog.AddSchCollectRecordRetryLogDTO;
import com.docus.server.dto.scheduling.management.schcollectrecordretrylog.DeleteSchCollectRecordRetryLogDTO;
import com.docus.server.dto.scheduling.management.schcollectrecordretrylog.EditSchCollectRecordRetryLogDTO;
import com.docus.server.dto.scheduling.management.schterminator.NettyTerminatorDTO;
import com.docus.server.entity.scheduling.management.SchCollectRecordRetryLog;
import com.docus.server.entity.scheduling.management.SchSystemParams;
import com.docus.server.enums.SubStateEnum;
import com.docus.server.infrastructure.dao.ISchCollectRecordRetryLogDao;
import com.docus.server.infrastructure.dao.ISchSystemParamsDao;
import com.docus.server.service.ISchCollectRecordRetryLogService;
import com.docus.server.vo.scheduling.management.schcollectrecordretrylog.SchCollectRecordRetryLogVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 采集记录表重试表 服务实现类
 *
 * @author AutoGenerator
 * @since 2023-07-15
 */
@Service
public class SchCollectRecordRetryLogServiceImpl implements ISchCollectRecordRetryLogService {
    @Resource
    private ISchCollectRecordRetryLogDao iSchCollectRecordRetryLogDao;
    @Resource
    private ISchSystemParamsDao iSchSystemParamsDao;
    @Resource
    private IdService idService;

    /**
     * 按主键查询
     *
     * @param id 主键Id
     * @return 实体
     */
    @Override
    public SchCollectRecordRetryLogVO findById(String id) {
        return SchCollectRecordRetryLogConvert.INSTANCE.convertVO(iSchCollectRecordRetryLogDao.findById(id));
    }

    /**
     * 关键字搜索
     *
     * @param searchDTO 搜索参数
     * @return 分页列表
     */
    @Override
    public PageResult<SchCollectRecordRetryLogVO> search(SearchDTO searchDTO) {
        PageResult<SchCollectRecordRetryLogVO> result = SchCollectRecordRetryLogConvert.INSTANCE.convertVO(iSchCollectRecordRetryLogDao.search(searchDTO));

        if (CollectionUtils.isEmpty(result.getList())) {
            return new PageResult<>();
        }

        List<SchSystemParams> schSystemParams = iSchSystemParamsDao.findBy("paramValue", ListUtils.distinctSelect(result.getList(), SchCollectRecordRetryLogVO::getCollectorId));
        Map<String, SchSystemParams> taskConfigRetryLogMap = ListUtils.toMap(schSystemParams, SchSystemParams::getParamValue);

        Setters.<SchCollectRecordRetryLogVO>instance().list(result.getList()).cycleSetProperties(p -> {
            String collectorId = String.valueOf(p.getCollectorId());
            if (taskConfigRetryLogMap.containsKey(collectorId)) {
                p.setCollectorName(taskConfigRetryLogMap.get(collectorId).getParamName());
            }
        });

        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public SchCollectRecordRetryLog saveOrUpdateRecordRetryLog(NettyTerminatorDTO terminal, ReportDownTwoDTO messageContent) {
        //新增采集记录表
        AddSchCollectRecordRetryLogDTO retryLogDTO = new AddSchCollectRecordRetryLogDTO();
        retryLogDTO.setId(idService.getDateSeq());
        retryLogDTO.setCollectRecordId(Long.valueOf(String.valueOf(messageContent.getParams().get("collectRecordId"))));
        retryLogDTO.setCollectorId(Long.valueOf(messageContent.getTasks().get(0).getCollectorId()));
        retryLogDTO.setTerminatorId(terminal.getId());
        retryLogDTO.setTaskId(messageContent.getTasks().get(0).getTaskId());
        SchSystemParams params = iSchSystemParamsDao.findOneBy("paramValue", messageContent.getTasks().get(0).getCollectorId());
        retryLogDTO.setTaskName(String.format("%s%s%s", messageContent.getPatient().getName(), params.getParamName(), "采集"));
        retryLogDTO.setTaskMemo(String.format("%s%s%s", messageContent.getPatient().getName(), params.getParamName(), "采集"));
        retryLogDTO.setStartTime(DateUtil.now());
        retryLogDTO.setTaskDetailInfo(String.format("病案号：%s，姓名：%s，采集类型：%s", messageContent.getPatientId(), messageContent.getPatient().getName(), params.getParamName()));
        retryLogDTO.setSubTaskExecState(SubStateEnum.RECEIVE);
        retryLogDTO.setTaskOriginJson(JSON.toJSON(messageContent));

        return this.add(retryLogDTO);
    }

    /**
     * 新增
     *
     * @param addSchCollectRecordRetryLogDTO 编辑参数
     * @return 成功或失败
     */
    @Override
    public SchCollectRecordRetryLog add(AddSchCollectRecordRetryLogDTO addSchCollectRecordRetryLogDTO) {
        SchCollectRecordRetryLog schCollectRecordRetryLog = SchCollectRecordRetryLogConvert.INSTANCE.convertDO(addSchCollectRecordRetryLogDTO);
        iSchCollectRecordRetryLogDao.add(schCollectRecordRetryLog);
        return schCollectRecordRetryLog;
    }

    /**
     * 编辑
     *
     * @param editSchCollectRecordRetryLogDTO 编辑参数
     * @return 成功或失败
     */
    @Override
    public boolean edit(EditSchCollectRecordRetryLogDTO editSchCollectRecordRetryLogDTO) {
        SchCollectRecordRetryLog schCollectRecordRetryLog = SchCollectRecordRetryLogConvert.INSTANCE.convertDO(editSchCollectRecordRetryLogDTO);
        return iSchCollectRecordRetryLogDao.edit(schCollectRecordRetryLog);
    }

    /**
     * 批量删除
     *
     * @param deleteSchCollectRecordRetryLogDTO 删除参数
     * @return 成功或失败
     */
    @Override
    public int delete(DeleteSchCollectRecordRetryLogDTO deleteSchCollectRecordRetryLogDTO) {
        return iSchCollectRecordRetryLogDao.delete(deleteSchCollectRecordRetryLogDTO.getIds());
    }
}

