package com.ruoyi.dxp.service.impl;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.common.utils.uuid.Seq;
import com.ruoyi.dxp.constant.DxpConstants;
import com.ruoyi.dxp.domain.UserResource;
import com.ruoyi.dxp.dto.AuditDto;
import com.ruoyi.dxp.dto.NoticeSendDto;
import com.ruoyi.dxp.mapper.UserResourceMapper;
import com.ruoyi.dxp.service.INoticeService;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.dxp.mapper.ApplicationMapper;
import com.ruoyi.dxp.domain.Application;
import com.ruoyi.dxp.service.IApplicationService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 应用Service业务层处理
 *
 * @author jy
 * @date 2022-12-06
 */
@Service
public class ApplicationServiceImpl implements IApplicationService {
    @Autowired
    private ApplicationMapper applicationMapper;

    @Autowired
    private UserResourceMapper userResourceMapper;

    @Autowired
    private INoticeService noticeService;

    /**
     * 查询应用
     *
     * @param id 应用主键
     * @return 应用
     */
    @Override
    public Application selectApplicationById(Long id) {
        return applicationMapper.selectApplicationById(id);
    }

    /**
     * 查询应用列表
     *
     * @param application 应用
     * @return 应用
     */
    @Override
    public List<Application> selectApplicationList(Application application) {
        return applicationMapper.selectApplicationList(application);
    }

    /**
     * 新增应用
     *
     * @param application 应用
     * @return 结果
     */
    @Override
    public AjaxResult insertApplication(Application application) {
        // 检测参数
        // appName
        if (StringUtils.isEmpty(application.getAppName())) {
            return AjaxResult.error("应用名称不能为空");
        }

        // appId
        AtomicInteger uploadSeq = new AtomicInteger(1);
        application.setAppId(Seq.getId(uploadSeq, 3));

        // appSecret
        application.setAppSecret(IdUtils.simpleUUID());

        // coverimg
        if (StringUtils.isEmpty(application.getCoverImg())) {
            return AjaxResult.error("请上传应用图片");
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        application.setUserId(loginUser.getUserId());
        application.setCreateBy(loginUser.getUsername());
        application.setCreateTime(DateUtils.getNowDate());
        application.setStatus(DxpConstants.STATUS_WAIT_APPROVED);
        applicationMapper.insertApplication(application);

        // 发送通知
        NoticeSendDto sendDto = new NoticeSendDto();
        sendDto.setNoticeType("applicationAudit");
        noticeService.sendNotice(sendDto);

        return AjaxResult.success(application.getId());
    }

    /**
     * 修改应用
     *
     * @param applicationDto 应用
     * @return 结果
     */
    @Override
    public AjaxResult updateApplication(Application applicationDto) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Application application = applicationMapper.selectApplicationById(applicationDto.getId());
        if (application == null) {
            return AjaxResult.error("待编辑的应用不存在");
        }

        if (!applicationDto.getUserId().equals(application.getUserId()) || !loginUser.getUserId().equals(application.getUserId())) {
            return AjaxResult.error("不能修改非自己的应用");
        }

        application.setAppName(applicationDto.getAppName());
        application.setLinkMan(applicationDto.getLinkMan());
        application.setLinkPhone(applicationDto.getLinkPhone());
        application.setCoverImg(applicationDto.getCoverImg());
        application.setStatus(DxpConstants.STATUS_WAIT_APPROVED);
        application.setRemark(applicationDto.getRemark());
        application.setAuditBy(null);
        application.setAuditTime(null);
        application.setAuditRemark(null);
        application.setUpdateTime(DateUtils.getNowDate());
        application.setUpdateBy(loginUser.getUsername());
        applicationMapper.updateApplication(application);

        // 发送通知
        NoticeSendDto sendDto = new NoticeSendDto();
        sendDto.setNoticeType("applicationAudit");
        noticeService.sendNotice(sendDto);

        return AjaxResult.success(application.getId());
    }

    /**
     * 批量删除应用
     *
     * @param ids 需要删除的应用主键
     * @return 结果
     */
    @Override
    public int deleteApplicationByIds(Long[] ids) {
        return applicationMapper.deleteApplicationByIds(ids);
    }

    /**
     * 删除应用信息
     *
     * @param id 应用主键
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult deleteApplicationById(Long id) {
        Application application = applicationMapper.selectApplicationById(id);
        if (application == null) {
            return AjaxResult.error("待删除应用不存在");
        }

        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (!application.getUserId().equals(loginUser.getUserId())) {
            return AjaxResult.error("不能删除非自己的应用");
        }

        applicationMapper.deleteApplicationById(id);

        // 同时删除应用订购的资源
        UserResource req = new UserResource();
        req.setApplicationId(id);
        List<Long> ids = userResourceMapper.selectUserResourceList(req).stream().map(t -> {
            return t.getId();
        }).collect(Collectors.toList());

        if (ids != null && ids.size() > 0) {
            for (Long appId : ids) {
                userResourceMapper.deleteUserResourceById(appId);
            }
        }

        return AjaxResult.success();
    }

    /**
     * 审核应用
     *
     * @param auditDto 审核对象
     * @return
     */
    @Override
    public AjaxResult audit(AuditDto auditDto) {
        Application application = applicationMapper.selectApplicationById(auditDto.getId());
        if (application == null || !application.getStatus().equals("0")) {
            return AjaxResult.error("待审核应用不存在或非待审核状态");
        }

        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (StringUtils.isEmpty(auditDto.getStatus())) {
            return AjaxResult.error("状态不能为空");
        }

        if (!auditDto.getStatus().equals(DxpConstants.STATUS_VALID) && !auditDto.getStatus().equals(DxpConstants.STATUS_REJECT)) {
            return AjaxResult.error("状态值错误");
        }

        if (StringUtils.isEmpty(auditDto.getAuditRemark())) {
            return AjaxResult.error("审核意见不能为空");
        }
        application.setStatus(auditDto.getStatus());
        application.setAuditBy(loginUser.getUsername());
        application.setAuditTime(DateUtils.getNowDate());
        application.setAuditRemark(auditDto.getAuditRemark());
        application.setUpdateTime(DateUtils.getNowDate());
        application.setUpdateBy(loginUser.getUsername());
        applicationMapper.updateApplication(application);

        // 发送通知
        NoticeSendDto sendDto = new NoticeSendDto();
        sendDto.setNoticeType("auditResult");
        sendDto.setUserId(application.getUserId());
        sendDto.setContennt("您申请的应用【" + application.getAppName() + "】，已审核" + (auditDto.getStatus().equals(DxpConstants.STATUS_VALID) ? "通过" : ("拒绝，拒绝原因：" + auditDto.getAuditRemark())));
        noticeService.sendNotice(sendDto);

        return AjaxResult.success();
    }
}
