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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
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.TBViolationResult;
import com.qmth.sop.business.entity.SysMessage;
import com.qmth.sop.business.entity.SysUser;
import com.qmth.sop.business.entity.TBViolation;
import com.qmth.sop.business.entity.TBViolationDetail;
import com.qmth.sop.business.mapper.TBViolationMapper;
import com.qmth.sop.business.service.*;
import com.qmth.sop.business.util.SmsSendUtil;
import com.qmth.sop.common.contant.SystemConstant;
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 javax.annotation.Resource;
import java.util.*;

/**
 * sop违规登记表 服务实现.
 *
 * @author: shudonghui
 * @date: 2023-08-09 10:33:08
 * @version: 1.0
 * @email: shudonghui@qmth.com.cn
 * @Company: www.qmth.com.cn
 */
@Service
public class TBViolationServiceImpl extends ServiceImpl<TBViolationMapper, TBViolation> implements TBViolationService {

    @Resource
    SysMessageService sysMessageService;

    @Resource
    SmsSendUtil smsSendUtil;

    @Resource
    SequenceService sequenceService;

    @Resource
    TBViolationDetailService tbViolationDetailService;

    @Resource
    SysUserService sysUserService;

    /**
     * 查询列表
     *
     * @param iPage
     * @param serviceId
     * @param type
     * @param status
     * @param userId
     * @param custom
     * @param sopNo
     * @param createId
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public IPage<TBViolationResult> query(IPage<Map> iPage, Long serviceId, ViolationTypeEnum type, ViolationStatusEnum status, Long userId, String custom, String sopNo, Long createId, Long startTime, Long endTime) {
        SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
        DataPermissionDto dpr = sysUserService.buildUserDataPermission(requestUser.getId());
        return this.baseMapper.query(iPage, serviceId, Objects.nonNull(type) ? type.name() : null, Objects.nonNull(status) ? status.name() : null, userId, custom, sopNo, createId, startTime, endTime, dpr);
    }

    /**
     * 新增修改sop违规登记表
     *
     * @param tBViolation
     */
    @Override
    @Transactional
    public Boolean saveTBViolation(TBViolation tBViolation) {
        try {
            SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
            if (Objects.isNull(tBViolation.getId())) {// 新增
                tBViolation.setCode(DelayWarnSeqTypeEnum.VIOLATION_WARN.getMark() + sequenceService.createCode(DelayWarnSeqTypeEnum.VIOLATION_WARN.getCode()));
                tBViolation.insertInfo(sysUser.getId());
                saveOrUpdate(tBViolation);
                TBViolationResult tbViolationResult = getByCode(tBViolation.getCode());

//                String content = MessageEnum.NOTICE_OF_VIOLATION_REMIND.getTemplate();
//                content = content.replaceAll("\\$\\{userName\\}", tbViolationResult.getUserName());
//                content = content.replaceAll("\\$\\{serviceName\\}", tbViolationResult.getService());
//                content = content.replaceAll("\\$\\{customName\\}", tbViolationResult.getCustom());
//                content = content.replaceAll("\\$\\{createUserName\\}", tbViolationResult.getCreateName());
//                content = content.replaceAll("\\$\\{violationType\\}", tbViolationResult.getType().getTitle());

                String configKey = SystemConstant.SMS_VIOLATION_REMIND_CODE;
                Map<String, Object> templateParam = new HashMap<>();
                templateParam.put("userName", tbViolationResult.getUserName());
                templateParam.put("serviceName", tbViolationResult.getService());
                templateParam.put("customName", tbViolationResult.getCustom());
                templateParam.put("createUserName", tbViolationResult.getCreateName());
                templateParam.put("violationType", tbViolationResult.getType().getTitle());

                SysMessage sysMessage = new SysMessage(tBViolation.getCrmNo(), tBViolation.getCode(),
                        MessageTypeEnum.VIOLATION, tBViolation.getType().name(), tBViolation.getServiceId(), tBViolation.getUserId(), tBViolation.getContent(),sysUser.getId());
                sysMessageService.saveSysMessage(Collections.singletonList(sysMessage));
                //发送短信
                smsSendUtil.sendSms(tbViolationResult.getMobileNumber(), configKey, templateParam);
            } else { // 修改
                tBViolation.updateInfo(sysUser.getId());
                saveOrUpdate(tBViolation);
            }
            return true;
        } 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;

    }

    /**
     * 删除sop违规登记表
     *
     * @param id
     */
    @Override
    @Transactional
    public Boolean delete(Long id) {
        return this.removeById(id);
    }


    @Override
    public TBViolationResult getByCode(String code) {
        TBViolationResult tbViolationResult = this.baseMapper.getByCode(code);
        List<TBViolationDetail> TBViolationDetails = tbViolationDetailService.list(new QueryWrapper<TBViolationDetail>().lambda().eq(TBViolationDetail::getViolationId, tbViolationResult.getId()).orderByDesc(TBViolationDetail::getCreateTime));
        tbViolationResult.setTbViolationDetails(TBViolationDetails);
        return tbViolationResult;
    }

}