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

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.result.SysNoticeResult;
import com.qmth.sop.business.entity.SysNotice;
import com.qmth.sop.business.entity.SysUser;
import com.qmth.sop.business.mapper.SysNoticeMapper;
import com.qmth.sop.business.service.SysMessageService;
import com.qmth.sop.business.service.SysNoticeService;
import com.qmth.sop.common.enums.ExceptionResultEnum;
import com.qmth.sop.common.enums.FieldUniqueEnum;
import com.qmth.sop.common.enums.NoticeStatusEnum;
import com.qmth.sop.common.enums.NoticeTypeEnum;
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.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 公告表 服务实现.
 *
 * @author: shudonghui
 * @date: 2023-08-07 13:53:29
 * @version: 1.0
 * @email: shudonghui@qmth.com.cn
 * @Company: www.qmth.com.cn
 */
@Service
public class SysNoticeServiceImpl extends ServiceImpl<SysNoticeMapper, SysNotice> implements SysNoticeService {

    @Resource
    SysMessageService sysMessageService;

    /**
     * 查询列表
     *
     * @param iPage
     * @return
     */
    @Override
    public IPage<SysNoticeResult> query(IPage<Map> iPage, String query, NoticeStatusEnum status, NoticeTypeEnum type, Long startTime, Long endTime) {
        return this.baseMapper.query(iPage, query, Objects.nonNull(status) ? status.name() : null, Objects.nonNull(type) ? type.name() : null, startTime, endTime);
    }


    /**
     * 新增修改公告表
     *
     * @param sysNotice
     */
    @Override
    @Transactional
    public Boolean saveSysNotice(SysNotice sysNotice) {
        try {
            sysNotice.setEnable(true);
            //sysNotice.setStatus(NoticeStatusEnum.UN_PUBLISH);
            SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
            if (Objects.isNull(sysNotice.getId())) {// 新增
                sysNotice.insertInfo(sysUser.getId());
            } else { // 修改
                sysNotice.updateInfo(sysUser.getId());
            }
            if (NoticeStatusEnum.PUBLISH == sysNotice.getStatus()) {
                sysNotice.setEnable(true);
                sysNotice.setStatus(NoticeStatusEnum.PUBLISH);
                sysNotice.setPublishTime(System.currentTimeMillis());
                //需调发布插入表SysMessage
                sysMessageService.publishByNotice(sysNotice);
            }
            this.saveOrUpdate(sysNotice);
        } 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
    @Transactional
    public boolean disable(long[] ids) {
        //ids数组转化为list
        List<Long> idList = Arrays.stream(ids).boxed().collect(Collectors.toList());
        //根据id数组查询公告表
        List<SysNotice> sysNotices = this.listByIds(idList);
        sysNotices.forEach(e->{
            e.setEnable(false);
            if (NoticeStatusEnum.PUBLISH == e.getStatus()) {
                e.setStatus(NoticeStatusEnum.UN_PUBLISH);
                // 需调用撤销发布SysMessage
                sysMessageService.deleteByNoticeId(e.getId());
            }
        });
        return this.updateBatchById(sysNotices);
    }

    @Override
    @Transactional
    public boolean publishOrUnpublish(long id) {
        SysNotice sysNotice = this.getById(id);
        if (NoticeStatusEnum.PUBLISH == sysNotice.getStatus()) {
            sysNotice.setStatus(NoticeStatusEnum.UN_PUBLISH);
            // 需调用撤销发布删除SysMessage
            sysMessageService.deleteByNoticeId(id);
        } else {
            sysNotice.setEnable(true);
            sysNotice.setStatus(NoticeStatusEnum.PUBLISH);
            sysNotice.setPublishTime(System.currentTimeMillis());
            //需调发布插入表SysMessage
            sysMessageService.publishByNotice(sysNotice);
        }
        return this.saveOrUpdate(sysNotice);
    }

}