package com.sundot.airport.web.controller.check;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.sundot.airport.common.core.domain.DataPermissionResult;
import com.sundot.airport.common.core.domain.entity.SysDept;
import com.sundot.airport.common.core.domain.entity.SysRole;
import com.sundot.airport.common.enums.CheckLevelEnum;
import com.sundot.airport.common.enums.CheckTaskStatusEnum;
import com.sundot.airport.common.enums.RoleTypeEnum;
import com.sundot.airport.common.enums.SourceTypeEnum;
import com.sundot.airport.common.utils.SecurityUtils;
import com.sundot.airport.system.service.ISysDeptService;
import com.sundot.airport.web.core.utils.DataPermissionUtils;
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.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.sundot.airport.common.annotation.Log;
import com.sundot.airport.common.core.controller.BaseController;
import com.sundot.airport.common.core.domain.AjaxResult;
import com.sundot.airport.common.enums.BusinessType;
import com.sundot.airport.check.domain.CheckTask;
import com.sundot.airport.check.service.ICheckTaskService;
import com.sundot.airport.common.utils.poi.ExcelUtil;
import com.sundot.airport.common.core.page.TableDataInfo;

/**
 * 检查任务Controller
 *
 * @author ruoyi
 * @date 2025-09-07
 */
@RestController
@RequestMapping("/check/checkTask")
public class CheckTaskController extends BaseController {
    @Autowired
    private ICheckTaskService checkTaskService;
    @Autowired
    private ISysDeptService sysDeptService;

    /**
     * 查询检查任务列表
     */
    @PreAuthorize("@ss.hasPermi('check:checkTask:list')")
    @GetMapping("/list")
    public TableDataInfo list(CheckTask checkTask, @RequestHeader(value = "X-Request-Source", defaultValue = "mobile") String source) {
        DataPermissionResult dataPermission = DataPermissionUtils.getDataPermission(getUserId(), getDeptId(), getLoginUser());
        startPage();
        List<CheckTask> list;
        if (StrUtil.equals(SourceTypeEnum.mobile.getCode(), source)) {
            switch (dataPermission.getPermissionType()) {
                case ALL:
                    checkTask.setCheckLevel(null);
                    break;
                case STATION:
                    checkTask.setCheckLevel(CheckLevelEnum.STATION_LEVEL.getCode());
                    break;
                case BRIGADE:
                    List<SysRole> roles = SecurityUtils.getLoginUser().getUser().getRoles();
                    List<String> roleKeyList = roles.stream().map(SysRole::getRoleKey).collect(Collectors.toList());
                    if (roleKeyList.contains(RoleTypeEnum.xingzheng.getCode())) {
                        checkTask.setCheckLevel(CheckLevelEnum.BRIGADE_LEVEL.getCode());
                        checkTask.setSelfCheckDeptId(SecurityUtils.getLoginUser().getUser().getDept().getDeptId());
                    } else {
                        return getDataTable(Collections.emptyList());
                    }
                    break;
                case DEPARTMENT:
                    checkTask.setCheckLevel(CheckLevelEnum.DEPARTMENT_LEVEL.getCode());
                    checkTask.setSelfCheckDeptId(SecurityUtils.getLoginUser().getUser().getDept().getParentId());
                    break;
                case TEAM:
                    checkTask.setCheckLevel(CheckLevelEnum.TEAM_LEVEL.getCode());
                    SysDept teamDept = SecurityUtils.getLoginUser().getUser().getDept();
                    SysDept departmentDept = sysDeptService.selectDeptById(teamDept.getParentId());
                    checkTask.setSelfCheckDeptId(departmentDept.getParentId());
                    break;
                default:
                    return getDataTable(Collections.emptyList());
            }
            list = checkTaskService.selectCheckTaskList(checkTask);
        } else if (StrUtil.equals(SourceTypeEnum.web.getCode(), source)) {
            switch (dataPermission.getPermissionType()) {
                case ALL:
                case STATION:
                    list = checkTaskService.selectCheckTaskList(checkTask);
                    break;
                case BRIGADE:
                    checkTask.setSelfCheckDeptId(SecurityUtils.getLoginUser().getUser().getDept().getDeptId());
                    list = checkTaskService.selectCheckTaskListBrigadeWeb(checkTask);
                    break;
                case DEPARTMENT:
                    checkTask.setSelfCheckDeptId(SecurityUtils.getLoginUser().getUser().getDept().getParentId());
                    list = checkTaskService.selectCheckTaskListWeb(checkTask);
                    break;
                default:
                    return getDataTable(Collections.emptyList());
            }
        } else {
            return getDataTable(Collections.emptyList());
        }
        return getDataTable(list);
    }

    /**
     * 导出检查任务列表
     */
    @PreAuthorize("@ss.hasPermi('check:checkTask:export')")
    @Log(title = "检查任务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CheckTask checkTask) {
        DataPermissionResult dataPermission = DataPermissionUtils.getDataPermission(getUserId(), getDeptId(), getLoginUser());
        List<CheckTask> list;
        switch (dataPermission.getPermissionType()) {
            case ALL:
            case STATION:
                list = checkTaskService.selectCheckTaskList(checkTask);
                break;
            case BRIGADE:
                checkTask.setSelfCheckDeptId(SecurityUtils.getLoginUser().getUser().getDept().getDeptId());
                list = checkTaskService.selectCheckTaskListBrigadeWeb(checkTask);
                break;
            case DEPARTMENT:
                checkTask.setSelfCheckDeptId(SecurityUtils.getLoginUser().getUser().getDept().getParentId());
                list = checkTaskService.selectCheckTaskListWeb(checkTask);
                break;
            default:
                list = Collections.emptyList();
                break;
        }
        ExcelUtil<CheckTask> util = new ExcelUtil<CheckTask>(CheckTask.class);
        util.exportExcel(response, list, "检查任务数据");
    }

    /**
     * 获取检查任务详细信息
     */
    @PreAuthorize("@ss.hasPermi('check:checkTask:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(checkTaskService.selectCheckTaskById(id));
    }

    /**
     * 新增检查任务
     */
    @PreAuthorize("@ss.hasPermi('check:checkTask:add')")
    @Log(title = "检查任务", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CheckTask checkTask) {
        checkTask.setCreateId(getUserId());
        checkTask.setCreateBy(getUsername());
        return toAjax(checkTaskService.insertCheckTask(checkTask));
    }

    /**
     * 修改检查任务
     */
    @PreAuthorize("@ss.hasPermi('check:checkTask:edit')")
    @Log(title = "检查任务", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CheckTask checkTask) {
        checkTask.setUpdateId(getUserId());
        checkTask.setUpdateBy(getUsername());
        return toAjax(checkTaskService.updateCheckTask(checkTask));
    }

    /**
     * 删除检查任务
     */
    @PreAuthorize("@ss.hasPermi('check:checkTask:remove')")
    @Log(title = "检查任务", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(checkTaskService.deleteCheckTaskByIds(ids));
    }

    /**
     * 查询检查任务未读数量
     */
    @PreAuthorize("@ss.hasPermi('check:checkTask:list')")
    @GetMapping("/unReadNum")
    public AjaxResult unReadNum() {
        DataPermissionResult dataPermission = DataPermissionUtils.getDataPermission(getUserId(), getDeptId(), getLoginUser());
        CheckTask checkTask = new CheckTask();
        checkTask.setStatus(CheckTaskStatusEnum.IN_PROGRESS.getCode());
        switch (dataPermission.getPermissionType()) {
            case ALL:
                checkTask.setCheckLevel(null);
                break;
            case STATION:
                checkTask.setCheckLevel(CheckLevelEnum.STATION_LEVEL.getCode());
                break;
            case BRIGADE:
                checkTask.setCheckLevel(CheckLevelEnum.BRIGADE_LEVEL.getCode());
                checkTask.setSelfCheckDeptId(SecurityUtils.getLoginUser().getUser().getDept().getDeptId());
                break;
            case DEPARTMENT:
                checkTask.setCheckLevel(CheckLevelEnum.DEPARTMENT_LEVEL.getCode());
                checkTask.setSelfCheckDeptId(SecurityUtils.getLoginUser().getUser().getDept().getParentId());
                break;
            case TEAM:
                checkTask.setCheckLevel(CheckLevelEnum.TEAM_LEVEL.getCode());
                SysDept teamDept = SecurityUtils.getLoginUser().getUser().getDept();
                SysDept departmentDept = sysDeptService.selectDeptById(teamDept.getParentId());
                checkTask.setSelfCheckDeptId(departmentDept.getParentId());
                break;
            default:
                return success(0);
        }
        List<CheckTask> list = checkTaskService.selectCheckTaskList(checkTask);
        if (CollUtil.isEmpty(list)) {
            return success(0);
        }
        return success(list.stream().filter(item -> !item.isRead()).count());
    }
}
