package com.ruoyi.web.controller.system;

import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.ColumnNews;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.ExamineConfig;
import com.ruoyi.system.service.IColumnNewsService;
import com.ruoyi.system.service.IExamineConfigService;
import io.swagger.models.auth.In;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.ExamineSchedule;
import com.ruoyi.system.service.IExamineScheduleService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 审核进度Controller
 * 
 * @author boman
 * @date 2022-01-24
 */
@RestController
@RequestMapping("/system/schedule")
public class ExamineScheduleController extends BaseController
{
    @Autowired
    private IExamineScheduleService examineScheduleService;
    @Autowired
    private IExamineConfigService examineConfigService;
    @Autowired
    private IColumnNewsService columnNewsService;

    /**
     * 查询审核进度列表
     */
    @PreAuthorize("@ss.hasPermi('system:schedule:list')")
    @GetMapping("/list")
    public TableDataInfo list(ExamineSchedule examineSchedule)
    {
        startPage();
        List<ExamineSchedule> list = examineScheduleService.selectExamineScheduleList(examineSchedule);
        return getDataTable(list);
    }

    /**
     * 导出审核进度列表
     */
    @PreAuthorize("@ss.hasPermi('system:schedule:export')")
    @Log(title = "审核进度", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ExamineSchedule examineSchedule)
    {
        List<ExamineSchedule> list = examineScheduleService.selectExamineScheduleList(examineSchedule);
        ExcelUtil<ExamineSchedule> util = new ExcelUtil<ExamineSchedule>(ExamineSchedule.class);
        util.exportExcel(response, list, "审核进度数据");
    }

    /**
     * 获取审核进度详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:schedule:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(examineScheduleService.selectExamineScheduleById(id));
    }

    /**
     * 新增审核进度
     */
    @PreAuthorize("@ss.hasPermi('system:schedule:add')")
    @Log(title = "审核进度", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ExamineSchedule examineSchedule)
    {
        return toAjax(examineScheduleService.insertExamineSchedule(examineSchedule));
    }

    /**
     * 修改审核进度
     */
    @PreAuthorize("@ss.hasPermi('system:schedule:edit')")
    @Log(title = "审核进度", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ExamineSchedule examineSchedule)
    {
        //去查询这个角色有没有该等级的审批权限
        String examineLevel = examineSchedule.getExamineLevel();
        if (StringUtils.isNotBlank(examineLevel)){
            int level = Integer.parseInt(examineLevel);
            if (level > 2){
                return AjaxResult.error("该文章已经审核完成");
            }
            List<ExamineConfig> examineConfigs = examineConfigService.selectExamineConfigByLevel(examineLevel);
            if (examineConfigs.size() > 0){
                List<SysRole> roles = SecurityUtils.getLoginUser().getUser().getRoles();
                for (ExamineConfig examineConfig : examineConfigs) {
                    for (SysRole role : roles) {
                        String[] split = examineConfig.getRoleId().replace("[", "").replace("]", "").split(",");
                        if (Arrays.asList(split).contains(String.valueOf(role.getRoleId()))){
                            //有审核权限,判断有没有id
                            Long id = examineSchedule.getId();
                            ColumnNews columnNews = new ColumnNews();
                            columnNews.setNewsId(examineSchedule.getNewsId());
                            if (id == null){
                                examineSchedule.setExamineNameOne(SecurityUtils.getUsername());
                                examineSchedule.setExamineTimeOne(DateUtils.getNowDate());
                                columnNews.setStatus(String.valueOf(level));
                                columnNewsService.updateColumnNews(columnNews);
                                return toAjax(examineScheduleService.insertExamineSchedule(examineSchedule));
                            }
                            level = level + 1;
                            if (level==2){
                                examineSchedule.setExamineNameTwo(SecurityUtils.getUsername());
                                examineSchedule.setExamineTimeTwo(DateUtils.getNowDate());
                            }
                            if (level==3){
                                examineSchedule.setExamineNameThr(SecurityUtils.getUsername());
                                examineSchedule.setExamineTimeThr(DateUtils.getNowDate());
                            }
                            examineSchedule.setExamineLevel(String.valueOf(level));
                            columnNews.setStatus(String.valueOf(level));
                            columnNewsService.updateColumnNews(columnNews);
                            return toAjax(examineScheduleService.updateExamineSchedule(examineSchedule));
                        }
                    }
                }
            }else {
                return AjaxResult.error("没有设置该审批等级的角色");
            }
        }
        return AjaxResult.success();
    }

    /**
     * 删除审核进度
     */
    @PreAuthorize("@ss.hasPermi('system:schedule:remove')")
    @Log(title = "审核进度", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(examineScheduleService.deleteExamineScheduleByIds(ids));
    }

    /**
     * 获取审核进度详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:schedule:query')")
    @GetMapping(value = "/newId/{id}")
    public AjaxResult getInfoByNewId(@PathVariable("id") Long id)
    {
        return AjaxResult.success(examineScheduleService.selectExamineScheduleByNewId(id));
    }

    /**
     * 撤销审核进度
     */
    @PreAuthorize("@ss.hasPermi('system:schedule:revoke')")
    @Log(title = "撤销审核进度", businessType = BusinessType.UPDATE)
    @PostMapping("/revoke")
    public AjaxResult revoke(@RequestBody ExamineSchedule examineSchedule)
    {
        //去查询这个角色有没有该等级的审批权限
        String examineLevel = examineSchedule.getExamineLevel();
        if (StringUtils.isNotBlank(examineLevel)){
            int level = Integer.parseInt(examineLevel);
            if (level < 1){
                return AjaxResult.error("该文章不能继续撤销");
            }
            List<ExamineConfig> examineConfigs = examineConfigService.selectExamineConfigByLevel(examineLevel);
            if (examineConfigs.size() > 0){
                List<SysRole> roles = SecurityUtils.getLoginUser().getUser().getRoles();
                for (ExamineConfig examineConfig : examineConfigs) {
                    for (SysRole role : roles) {
                        String[] split = examineConfig.getRoleId().replace("[", "").replace("]", "").split(",");
                        if (Arrays.asList(split).contains(String.valueOf(role.getRoleId()))){
                            examineSchedule.setExamineLevel(String.valueOf(level-1));
                            ColumnNews columnNews = new ColumnNews();
                            columnNews.setNewsId(examineSchedule.getNewsId());
                            columnNews.setStatus(String.valueOf(level-1));
                            columnNewsService.updateColumnNews(columnNews);
                            return toAjax(examineScheduleService.updateExamineSchedule(examineSchedule));
                        }
                    }
                }
            }
        }else {
            return AjaxResult.error("没有设置该审批等级的角色");
        }
        return AjaxResult.success();
    }
}
