package com.qmth.sop.business.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.boot.api.exception.ApiException;
import com.qmth.sop.business.bean.dto.DataPermissionDto;
import com.qmth.sop.business.bean.result.TBDelayWarnResult;
import com.qmth.sop.business.bean.result.WorkWarnResult;
import com.qmth.sop.business.entity.SysUser;
import com.qmth.sop.business.entity.TBDelayWarn;
import com.qmth.sop.business.entity.TBDelayWarnDetail;
import com.qmth.sop.business.mapper.TBDelayWarnMapper;
import com.qmth.sop.business.service.SysUserService;
import com.qmth.sop.business.service.TBDelayWarnDetailService;
import com.qmth.sop.business.service.TBDelayWarnService;
import com.qmth.sop.common.enums.*;
import com.qmth.sop.common.util.ResultUtil;
import com.qmth.sop.common.util.ServletUtil;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

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

/**
 * 延期预警跟进表 服务实现.
 *
 * @author: shudonghui
 * @date: 2023-08-08 16:02:21
 * @version: 1.0
 * @email: shudonghui@qmth.com.cn
 * @Company: www.qmth.com.cn
 */
@Service
public class TBDelayWarnServiceImpl extends ServiceImpl<TBDelayWarnMapper, TBDelayWarn> implements TBDelayWarnService {

    @Resource
    TBDelayWarnDetailService tBDelayWarnDetailService;

    @Resource
    SysUserService sysUserService;

    /**
     * 查询列表
     *
     * @param iPage
     * @param type
     * @param status
     * @param serviceId
     * @param custom
     * @param fieldObj
     * @param sopNo
     * @param startTime
     * @param endTime
     * @param id
     * @return
     */
    @Override
    public IPage<TBDelayWarnResult> query(IPage<Map> iPage, DelayWarnTypeEnum type, DelayWarnStatusEnum status, Long serviceId, String custom, String fieldObj, String sopNo, Long startTime, Long endTime, Long id) {
        SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
        DataPermissionDto dpr = sysUserService.buildUserDataPermission(requestUser.getId());
        List<String> fieldObjList = new ArrayList<>();
        if (Objects.nonNull(fieldObj) && ProcessLimitedEnum.PROJECT_KEY_INFO_DATE.getTitle().contains(fieldObj.trim())) {
            fieldObjList.add(ProcessLimitedEnum.PROJECT_KEY_INFO_DATE.getKey());
        }
        if (Objects.nonNull(fieldObj) && ProcessLimitedEnum.APPROVE_RADIO.getTitle().contains(fieldObj.trim())) {
            fieldObjList.add(ProcessLimitedEnum.APPROVE_RADIO.getKey());
        }
        if (Objects.nonNull(fieldObj) && ProcessLimitedEnum.SCAN_START_TIME.getTitle().contains(fieldObj.trim())) {
            fieldObjList.add(ProcessLimitedEnum.SCAN_START_TIME.getKey());
        }
        if (Objects.nonNull(fieldObj) && ProcessLimitedEnum.SCAN_END_TIME.getTitle().contains(fieldObj.trim())) {
            fieldObjList.add(ProcessLimitedEnum.SCAN_END_TIME.getKey());
        }
        if (Objects.nonNull(fieldObj) && ProcessLimitedEnum.MARK_START_TIME.getTitle().contains(fieldObj.trim())) {
            fieldObjList.add(ProcessLimitedEnum.MARK_START_TIME.getKey());
        }
        if (Objects.nonNull(fieldObj) && ProcessLimitedEnum.MARK_END_TIME.getTitle().contains(fieldObj.trim())) {
            fieldObjList.add(ProcessLimitedEnum.MARK_END_TIME.getKey());
        }
        if (Objects.nonNull(fieldObj) && ProcessLimitedEnum.SERVICE_FINISH_PLAN_DATE.getTitle().contains(fieldObj.trim())) {
            fieldObjList.add(ProcessLimitedEnum.SERVICE_FINISH_PLAN_DATE.getKey());
        }
        if (Objects.nonNull(fieldObj) && ProcessLimitedEnum.ENV_DEPLOYMENT_TIME.getTitle().contains(fieldObj.trim())) {
            fieldObjList.add(ProcessLimitedEnum.ENV_DEPLOYMENT_TIME.getKey());
        }
        if (Objects.nonNull(fieldObj) && CollectionUtils.isEmpty(fieldObjList)) {
            fieldObjList.add(fieldObj);
        }
        return this.baseMapper.query(iPage, Objects.nonNull(type) ? type.name() : null, Objects.nonNull(status) ? status.name() : null, serviceId, custom, fieldObjList, sopNo, startTime, endTime, id, dpr);
    }

    /**
     * 新增修改延期预警跟进表
     *
     * @param tBDelayWarn
     */
    @Override
    @Transactional
    public Boolean saveTBDelayWarn(TBDelayWarn tBDelayWarn) {
        try {
            SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
            if (Objects.isNull(tBDelayWarn.getId())) {// 新增
                tBDelayWarn.insertInfo(sysUser.getId());
            } else { // 修改
                tBDelayWarn.updateInfo(sysUser.getId());
            }
            return saveOrUpdate(tBDelayWarn);
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                String errorColumn = e.getCause().toString();
                String columnStr = errorColumn.substring(errorColumn.lastIndexOf("key") + 3, errorColumn.length()).replaceAll("'", "");
                throw ExceptionResultEnum.SQL_ERROR.exception("[" + FieldUniqueEnum.convertToTitle(columnStr) + "]数据不允许重复插入");
            } else if (e instanceof ApiException) {
                ResultUtil.error((ApiException) e, ((ApiException) e).getCode(), e.getMessage());
            } else {
                ResultUtil.error(e.getMessage());
            }
        }
        return null;

    }

    /**
     * 删除延期预警跟进表
     *
     * @param id
     */
    @Override
    @Transactional
    public Boolean delete(Long id) {
        return this.removeById(id);
    }

    @Override
    public TBDelayWarnResult get(long id) {
        IPage<TBDelayWarnResult> resultIPage = query(new Page<>(1, 1), null, null, null, null, null, null, null, null, id);
        TBDelayWarnResult tbDelayWarnResult = resultIPage.getRecords().get(0);
        List<TBDelayWarnDetail> tbDelayWarnDetails = tBDelayWarnDetailService.list(id);
        tbDelayWarnResult.setTbDelayWarnDetails(tbDelayWarnDetails);
        return tbDelayWarnResult;

    }

    /**
     * 获取预警待办
     *
     * @param iPage
     * @param userId
     * @param type
     * @param serviceId
     * @param customName
     * @return
     */
    @Override
    public IPage<WorkWarnResult> getWarnTaskList(IPage<Map> iPage, Long userId, WarnTypeEnum type, Long serviceId, String customName) {
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        userId = Objects.nonNull(sysUser) ? sysUser.getId() : userId;
        return this.baseMapper.getWarnTaskList(iPage, userId, Objects.nonNull(type) ? type.name() : null, serviceId, customName);
    }

    /**
     * 获取预警待办计数
     *
     * @param userId
     * @param type
     * @param serviceId
     * @param customName
     * @return
     */
    @Override
    public int getWarnTaskListCount(Long userId, WarnTypeEnum type, Long serviceId, String customName) {
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        userId = Objects.nonNull(sysUser) ? sysUser.getId() : userId;
        return this.baseMapper.getWarnTaskListCount(userId, Objects.nonNull(type) ? type.name() : null, serviceId, customName);
    }
}