package com.ruoyi.web.controller.system;

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.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.postCheck.domain.PostPlanInfo;
import com.ruoyi.postCheck.service.IPostPlanInfoService;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.service.ISysPostService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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


/**
 * 岗位信息操作处理
 *
 * @author ruoyi
 */
@Api(tags = "6.3.1-岗位管理")
@RestController
@RequestMapping("/system/post")
public class SysPostController extends BaseController {
    @Autowired
    private ISysPostService postService;

    @Autowired
    private IPostPlanInfoService postPlanInfoService;


    @ApiOperation("获取岗位列表")
    @PreAuthorize("@ss.hasPermi('system:post:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysPost post) {
//        startPage();
        startPage("asc", "t1.post_sort");
        Long deptId = post.getDeptId();
        if (deptId != null && deptId == 17) {
            post.setDeptId(null);
        }
        List<SysPost> list = postService.selectPostList(post);
        return getDataTable(list);
    }

    @Log(title = "岗位管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:post:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysPost post) {
        List<SysPost> list = postService.selectPostList(post);
        ExcelUtil<SysPost> util = new ExcelUtil<SysPost>(SysPost.class);
        util.exportExcel(response, list, "岗位数据");
    }

    /**
     * 根据岗位编号获取详细信息
     */
    @ApiOperation("岗位详情")
    @PreAuthorize("@ss.hasPermi('system:post:query')")
    @GetMapping(value = "/{postId}")
    public AjaxResult getInfo(
            @ApiParam(name = "postId", value = "岗位ID", required = true)
            @PathVariable Long postId) {
        return success(postService.selectPostById(postId));
    }

    /**
     * 新增岗位
     */
    @ApiOperation("新增岗位")
    @ApiImplicitParams({
//            @ApiImplicitParam(name = "postId", value = "岗位ID", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "deptId", value = "部门ID", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "postCode", value = "岗位编码", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "postName", value = "岗位名称", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "postSort", value = "排序", dataType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "status", value = "岗位状态0正常1停用", dataType = "String", dataTypeClass = String.class),
    })
    @PreAuthorize("@ss.hasPermi('system:post:add')")
    @Log(title = "岗位管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysPost post) {
        if (!postService.checkPostNameUnique(post)) {
            return error("新增岗位'" + post.getPostName() + "'失败，岗位名称已存在");
        }
//        else if (!postService.checkPostCodeUnique(post)) {
//            return error("新增岗位'" + post.getPostName() + "'失败，岗位编码已存在");
//        }
        post.setCreateBy(getUsername());
        return toAjax(postService.insertPost(post));
    }


    @ApiOperation("修改岗位")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "postId", value = "岗位ID", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "deptId", value = "部门ID", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "postCode", value = "岗位编码", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "postName", value = "岗位名称", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "postSort", value = "排序", dataType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "status", value = "岗位状态0正常1停用", dataType = "String", dataTypeClass = String.class),
    })
    @PreAuthorize("@ss.hasPermi('system:post:edit')")
    @Log(title = "岗位管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysPost post) {
        if (!postService.checkPostNameUnique(post)) {
            return error("修改岗位'" + post.getPostName() + "'失败，岗位名称已存在");
        }
//        else if (!postService.checkPostCodeUnique(post)) {
//            return error("修改岗位'" + post.getPostName() + "'失败，岗位编码已存在");
//        }
        post.setUpdateBy(getUsername());
        return toAjax(postService.updatePost(post));
    }


    @ApiOperation("删除岗位")
    @PreAuthorize("@ss.hasPermi('system:post:remove')")
    @Log(title = "岗位管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{postIds}")
    public AjaxResult remove(
            @ApiParam(name = "postIds", value = "岗位ID数组", required = true)
            @PathVariable Long[] postIds) {
        return toAjax(postService.deletePostByIds(postIds));
    }

    /**
     * 获取岗位选择框列表
     */
    @GetMapping("/optionselect")
    public AjaxResult optionselect() {
        List<SysPost> posts = postService.selectPostAll();
        return success(posts);
    }


    @ApiOperation("根据部门查询岗位列表，并设置检查时间和检查人员")
    @GetMapping({"/postCheck/optionselect/{deptId}", "/postCheck/optionselect/{deptId}/{planId}"})
    public AjaxResult postCheckOptionselect(
            @ApiParam(name = "deptId", value = "部门ID", required = true)
            @PathVariable("deptId") Long deptId,

            @ApiParam(name = "planId", value = "计划ID", required = false)
            @PathVariable(value = "planId", required = false) Long planId) {
        List<SysPost> posts = postService.selectPostByDeptId(deptId);
        if (planId != null) {
            //根据计划ID查询岗位的检查时间和检查人

            List<PostPlanInfo> planInfoList = postPlanInfoService.selectCheckTimeAndUser(planId);

            Map<Long, List<PostPlanInfo>> postCheckTimeUserMap = planInfoList.stream().collect(Collectors.groupingBy(PostPlanInfo::getCheckedPostId));

            for (SysPost post : posts) {
                Long postId = post.getPostId();
                if (postCheckTimeUserMap.containsKey(postId)) {
                    List<PostPlanInfo> infoList = postCheckTimeUserMap.get(postId);
                    //当一个岗位有多个计划时，选择第一个有有值的数据回显
                    for (PostPlanInfo postPlanInfo : infoList) {
                        Date checkedTime = postPlanInfo.getCheckedTime();
                        String checkedUserName = postPlanInfo.getCheckedUserName();
                        if (checkedTime != null || StringUtils.isNotBlank(checkedUserName)) {
                            post.setCheckTime(checkedTime);
                            post.setCheckUserName(checkedUserName);
                            break;
                        }
                    }
                }
            }
        }
        return success(posts);
    }

    @ApiOperation("岗位导入（先调用上传文件接口再将上传文件的相对路径放到设置到参数中）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileNameList", value = "数组（但是数组中只能放1个文件-与岗位责任制清单导入保持一致，方便接口联调才这样传参的）：前端上传文件接口返回的相对路径（含文件名称）,例如：/upload/2024/02/23/岗位表_2A003.xlsx", dataType = "String", dataTypeClass = String.class),
    })
    @PostMapping(value = "/batchImport")
    public AjaxResult batchImport(@RequestBody String[] fileNameList) {


//        if (false) {
//            判断 data ，如果有data 提示信息后 再就下载文件，如果没data仅提示信息
//            {
//                "msg": "msg错误信息",
//                    "code": 500,
//                    "data": "/download/这是XXXExcel文件.xlsx"
//            }
//             AjaxResult result = AjaxResult.error("msg错误信息", "/download/这是XXXExcel文件.xlsx");
//            return result;

//        }
        int length = fileNameList.length;
        if (length == 0) {
            return error("失败，未发现上传文件，请检查！");
        } else if (length > 1) {
            return error("失败，本次上传了" + length + "个文件，一次只能上传1个文件，请检查！");
        }

        String fileName = fileNameList[0];

        try {
            return postService.batchImport(fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return error("全部失败，本次操作为批量，发现文件中存在以下问题，请检查！" + e.getMessage());
        }

//        return success(1);
    }
}
