package com.ruoyi.project.task.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.project.check.domain.TCheckCheckpoints;
import com.ruoyi.project.check.mapper.TCheckCheckpointsMapper;
import com.ruoyi.project.check.service.ITCheckCheckpointsService;
import com.ruoyi.project.task.domain.TTaskInspection;
import com.ruoyi.project.task.domain.TTaskInspectionPlan;
import com.ruoyi.project.task.service.ITTaskInspectionPlanService;
import com.ruoyi.project.task.service.ITTaskInspectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 检测任务Controller
 *
 * @author ruoyi
 * @date 2022-11-21
 */
@RestController
@RequestMapping("/task/inspection")
public class TTaskInspectionController extends BaseController {
    @Autowired
    private ITTaskInspectionService tTaskInspectionService;

    @Autowired
    private ITTaskInspectionPlanService taskInspectionPlanService;

    @Autowired
    private TCheckCheckpointsMapper tCheckCheckpointsMapper;

    /**
     * 查询检测任务列表
     */
    @PreAuthorize("@ss.hasPermi('task:inspection:list')")
    @GetMapping("/list")
    public TableDataInfo list(TTaskInspection tTaskInspection) {
        startPage();
        List<TTaskInspection> list = tTaskInspectionService.selectTTaskInspectionList(tTaskInspection);
        list.forEach(item -> {
            if (StringUtils.isNotEmpty(item.getTaskDoneNum()) && StringUtils.isNotEmpty(item.getTaskNum())) {
                item.setPercentage(new BigDecimal(item.getTaskDoneNum()).divide(new BigDecimal(item.getTaskNum()), 4, RoundingMode.HALF_UP).multiply(new BigDecimal(100)).doubleValue());
            } else {
                item.setPercentage(0.0);
            }
            if (item.getEndTime() != null) {
                if (item.getEndTime().before(new Date()) && StringUtils.isNotEmpty(item.getTaskNum()) && !item.getTaskNum().equals(item.getTaskDoneNum())) {
                    item.setTimeOut("是");
                } else {
                    item.setTimeOut("否");
                }
            }
        });
        return getDataTable(list);
    }

    /**
     * 导出检测任务列表
     */
    @PreAuthorize("@ss.hasPermi('task:inspection:export')")
    @Log(title = "检测任务导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TTaskInspection tTaskInspection) {
        List<TTaskInspection> list = tTaskInspectionService.selectTTaskInspectionList(tTaskInspection);
        ExcelUtil<TTaskInspection> util = new ExcelUtil<TTaskInspection>(TTaskInspection.class);
        util.exportExcel(response, list, "检测任务数据");
    }

    /**
     * 获取检测任务详细信息
     */
    @PreAuthorize("@ss.hasPermi('task:inspection:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tTaskInspectionService.selectTTaskInspectionById(id));
    }

    /**
     * 新增检测任务
     */
    @PreAuthorize("@ss.hasPermi('task:inspection:add')")
    @Log(title = "检测任务新增", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TTaskInspection tTaskInspection) {
        if ("1".equals(tTaskInspection.getTaskType())) {
            TTaskInspectionPlan tTaskInspectionPlan = taskInspectionPlanService.selectTTaskInspectionPlanById(tTaskInspection.getPlanId());
            tTaskInspection.setPlantId(tTaskInspectionPlan.getPlantId());
        }
        tTaskInspection.setCreaterCode(getUserId());
        return toAjax(tTaskInspectionService.insertTTaskInspection(tTaskInspection));
    }

    /**
     * 修改检测任务
     */
    @PreAuthorize("@ss.hasPermi('task:inspection:edit')")
    @Log(title = "检测任务修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TTaskInspection tTaskInspection) {
        if ("1".equals(tTaskInspection.getTaskType())) {
            TTaskInspectionPlan tTaskInspectionPlan = taskInspectionPlanService.selectTTaskInspectionPlanById(tTaskInspection.getPlanId());
            tTaskInspection.setPlantId(tTaskInspectionPlan.getPlantId());
        }
        tTaskInspection.setUpdaterCode(getUserId());
        return toAjax(tTaskInspectionService.updateTTaskInspection(tTaskInspection));
    }

    /**
     * 删除检测任务
     */
    @PreAuthorize("@ss.hasPermi('task:inspection:remove')")
    @Log(title = "检测任务删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        QueryWrapper<TCheckCheckpoints> wrapper = new QueryWrapper<>();
        for (Long id : ids) {
            wrapper.clear();
            wrapper.eq("inspection_id", id);
            Integer count = tCheckCheckpointsMapper.selectCount(wrapper);
            if (count == 0) {
                tTaskInspectionService.deleteTTaskInspectionByIds(ids);
            }
        }
        return AjaxResult.success();
    }

    @PreAuthorize("@ss.hasPermi('task:inspection:edit')")
    @Log(title = "检测任务分配", businessType = BusinessType.UPDATE)
    @PutMapping("/{ids}")
    public AjaxResult divide(@PathVariable Long[] ids) {
        QueryWrapper<TCheckCheckpoints> wrapper = new QueryWrapper<>();
        for (Long id : ids) {
            wrapper.clear();
            wrapper.eq("inspection_id", id);
            Integer count = tCheckCheckpointsMapper.selectCount(wrapper);
            if (count == 0) {
                continue;
            }
            TTaskInspection tTaskInspection = new TTaskInspection();
            tTaskInspection.setId(id);
            tTaskInspection.setTaskNum(count.toString());
            tTaskInspection.setTaskUndoneNum(count.toString());
            tTaskInspection.setStatus("1");
            tTaskInspectionService.updateTTaskInspection(tTaskInspection);
        }
        return AjaxResult.success();
    }
}
