package com.ruoyi.postCheck.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.constant.PostCheckedEnum;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.zip.ZipFileUtils;
import com.ruoyi.postCheck.domain.PostChecked;
import com.ruoyi.postCheck.domain.PostCheckedItems;
import com.ruoyi.postCheck.service.IPostCheckedService;
import com.ruoyi.postCheck.util.excel.create.PostCheckedCreateExcel;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 岗检表管理Controller
 *
 * @author csg
 * @date 2024-01-05
 */
@Api(tags = "2.4.1-岗检表管理接口")
@RestController
@RequestMapping("/postCheck/postChecked")
public class PostCheckedController extends BaseController {
    @Autowired
    private IPostCheckedService postCheckedService;

    @Autowired
    private RuoYiConfig ruoYiConfig;


    /**
     * 查询岗检表管理列表
     */
    @ApiOperation("查询岗检表管理列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键ID", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "checkWorkgroupId", value = "检查工作组ID", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "checkGroupId", value = "检查小组ID", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "checkedDeptId", value = "被检查部门ID", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "checkedPostId", value = "被检查岗位ID", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "printUserId", value = "打印人ID", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "printTime", value = "打印时间", dataType = "Date", dataTypeClass = Date.class),
            @ApiImplicitParam(name = "checkedImg", value = "上传：检查后的检查表照片或PDF，磁盘相对路径", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "checkedUserName", value = "上传：检查人中文姓名（上传页面设置的值）", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "checkedTime", value = "上传：检查时间（上传页面设置的值）", dataType = "Date", dataTypeClass = Date.class),
            @ApiImplicitParam(name = "uploadUserId", value = "上传：检查表上传人ID", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "uploadTime", value = "上传：检查表上传时间", dataType = "Date", dataTypeClass = Date.class),
            @ApiImplicitParam(name = "delFlag", value = "删除标志（0代表存在 2代表删除）", dataType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "createUserId", value = "创建者用户ID", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "pageNum", value = "页码从1开始", dataType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "pageSize", value = "分页大小", dataType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "orderBy", value = "排序字段", dataType = "String", dataTypeClass = String.class)
    })
//    @PreAuthorize("@ss.hasPermi('postCheck:postChecked:list')")
    @GetMapping("/list")
    public TableDataInfo list(PostChecked postChecked) {
//        pageNum: 1
//        pageSize: 10
//        checkWorkgroupName: 工作组
//        checkGroupName: 检查小组
//        checkedDeptName: 部门
//        postCode: 编号 post_code
//        startPage();
        startPage("desc", "t1.create_time");
        List<PostChecked> list = postCheckedService.selectPostCheckedList(postChecked);
        return getDataTable(list);
    }

    /**
     * 导出岗检表管理列表
     *
     * @ApiOperation("导出岗检表管理列表")
     * @PreAuthorize("@ss.hasPermi('postCheck:postChecked:export')")
     * @Log(title = "岗检表管理", businessType = BusinessType.EXPORT)
     * @PostMapping("/export") public void export(HttpServletResponse response, PostChecked postChecked) {
     * List<PostChecked> list = postCheckedService.selectPostCheckedList(postChecked);
     * ExcelUtil<PostChecked> util = new ExcelUtil<PostChecked>(PostChecked.class);
     * util.exportExcel(response, list, "岗检表管理数据");
     * }
     */



    /**
     * 获取岗检表管理详细信息
     */
    @ApiOperation("获取岗检表管理详细信息")
//    @PreAuthorize("@ss.hasPermi('postCheck:postChecked:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(
            @ApiParam(name = "id", value = "检查表id", required = true)
            @PathVariable("id") Long id) {
        return success(postCheckedService.selectPostCheckedById(id));
    }


    @ApiOperation("新增岗检表管理")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "checkWorkgroupId", value = "检查工作组ID", dataType = "Long", dataTypeClass = Long.class),
//            @ApiImplicitParam(name = "checkGroupId", value = "检查小组ID", dataType = "Long", dataTypeClass = Long.class),
//            @ApiImplicitParam(name = "checkedDeptId", value = "被检查部门ID", dataType = "Long", dataTypeClass = Long.class),
//            @ApiImplicitParam(name = "checkedPostId", value = "被检查岗位ID", dataType = "Long", dataTypeClass = Long.class),
//            @ApiImplicitParam(name = "children", value = "检查表明细数组", dataType = "List", dataTypeClass = PostCheckedItems.class),
//    })
    @PreAuthorize("@ss.hasPermi('postCheck:postChecked:add')")
    @Log(title = "岗检表管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PostChecked postChecked) {

        if (postChecked != null) {
            postChecked.setCheckedType(PostCheckedEnum.CHECKED_TYPE_CUSTOM.getValue());
            postChecked.setCreateUserId(SecurityUtils.getUserId());
        }

        return toAjax(postCheckedService.insertPostChecked(postChecked));
    }

    /**
     * 修改岗检表管理
     */
    @ApiOperation("修改岗检表管理")
    /*@ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键ID", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "checkWorkgroupId", value = "检查工作组ID", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "checkGroupId", value = "检查小组ID", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "checkedDeptId", value = "被检查部门ID", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "checkedPostId", value = "被检查岗位ID", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "children", value = "检查表明细数组", dataType = "List", dataTypeClass = PostCheckedItems.class),
    })*/
    @PreAuthorize("@ss.hasPermi('postCheck:postChecked:edit')")
    @Log(title = "岗检表管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PostChecked postChecked) {
        return toAjax(postCheckedService.updatePostChecked(postChecked));
    }

    /**
     * 删除岗检表管理
     */
    @ApiOperation("删除岗检表管理")
//    @ApiImplicitParam(name = "ids", value = "Long类型的主键数组", dataType = "Long[]", dataTypeClass = Long[].class)
    @PreAuthorize("@ss.hasPermi('postCheck:postChecked:remove')")
    @Log(title = "岗检表管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(
            @ApiParam(name = "ids", value = "岗检表ids", required = true)
            @PathVariable Long[] ids) {
        return toAjax(postCheckedService.deletePostCheckedByIds(ids));
    }

    @ApiOperation("岗检表提交")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键ID", dataType = "String", dataTypeClass = String.class),
    })
    @Log(title = "岗检表提交", businessType = BusinessType.UPDATE)
    @GetMapping("/submitApprove")
    public AjaxResult submitApprove(Long id) {
        return toAjax(postCheckedService.submitApprove(id));
    }

    @ApiOperation("岗检表审核")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "status", value = "状态：3-通过；4-驳回；", dataType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "reason", value = "未通过理由", dataType = "String", dataTypeClass = String.class),
    })
    @Log(title = "岗检表审核", businessType = BusinessType.UPDATE)
    @PutMapping("/statusApprove")
    public AjaxResult statusApprove(String ids, Integer status, String reason) {

        // 判断审核的权限
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (!SecurityUtils.isAdmin(loginUser.getUserId())) {
            return AjaxResult.error(HttpStatus.FORBIDDEN, "没有权限，请联系管理员授权");
        }

        int count = 0;
        String[] idArr = ids.split(",");
        for (String id : idArr) {
            count += postCheckedService.statusApprove(Long.parseLong(id), status, reason);
        }
        return toAjax(count);
    }

/*
2024年2月5日方总说不要了，岗位责任制清单审核完成的时候，自动生成全要素岗检表即可
    @ApiOperation("岗检表批量导入（先调用上传文件接口再将上传文件的相对路径放到设置到参数中）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileNameList", value = "数组：前端上传文件接口返回的相对路径（含文件名称）,例如：/upload/2024/02/23/办公室主任_2A003.xlsx", dataType = "String[]", dataTypeClass = String[].class),
    })
    @PostMapping(value = "/batchImport")
    public AjaxResult batchImport(String[] fileNameList) {
        //TODO 待开发：岗检表批量导入，仅定义接口，为开发功能
        try {
            postCheckedService.batchImport(fileNameList);
        } catch (Exception e) {
            e.printStackTrace();
            return error("全部失败，本次操作为批量，发现文件中存在以下问题，请检查！" + e.getMessage());
        }

        return success(1);
    }
*/


    /**
     * 获取岗检表管理详细信息
     */
    @ApiOperation("岗检表预览详情")
    @GetMapping(value = "/preview/{id}")
    public AjaxResult preview(
            @ApiParam(name = "id", value = "岗检表id", required = true)
            @PathVariable("id") Long id) {
        PostChecked postChecked = postCheckedService.selectPostCheckedById(id);
        PostCheckedCreateExcel postCheckedCreateExcel = new PostCheckedCreateExcel();
        String fileName = postCheckedCreateExcel.createExcel(postChecked, postChecked.getChildren());

//        /upload/2024/01/15/2024岗检方案_20240115131209A001_20240115155951A001.docx
//        return success("/upload/2024/01/18/岗位责任制检查表_20240118001.xlsx");

        return success(File.separator + "download" + File.separator + fileName);
    }


    /**
     * 岗检表-批量下载 返回的压缩包地址，前端再去调用下载文件接口保存文件即可
     * @param ids
     * @return
     */
    @ApiOperation("岗检表批量下载")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "岗检表ids", dataType = "String", dataTypeClass = String.class),
    })
    @GetMapping(value = "/batchExport")
    public AjaxResult batchExport(String ids) {
        String downloadPath = ruoYiConfig.getDownloadPath();


        if (StringUtils.isBlank(ids)) {
            return error("请选择要导出的检查表！");
        }

        String[] idSplit = ids.split(",");
        List<Long> idList = new ArrayList<>();
        for (String id : idSplit) {
            idList.add(Long.parseLong(id));
        }

        if (CollectionUtils.isEmpty(idList)) {
            return error("请选择要导出的检查表！");
        }

        PostChecked param = new PostChecked();
        param.setIdList(idList);
        List<PostChecked> postCheckedList = postCheckedService.selectPostCheckedList(param);
        if (idList.size() != postCheckedList.size()) {
            return error("页面选择的记录数与数据库不匹配，请刷新页面再试！页面选择 " + idList.size() + " 条， 数据库匹配 " + postCheckedList.size() + " 条");
        }

        int index = 0;
        List<String> fileNameList = new ArrayList<>();
        for (PostChecked postChecked : postCheckedList) {
            if (index > 0) {
                try {
                    Thread.sleep(600l);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            index++;

            String fileName = new PostCheckedCreateExcel().createExcel(postChecked, postChecked.getChildren());
            fileNameList.add(downloadPath + fileName);
        }

        String zipFileName = "批量导出岗位检查表-" + DateUtils.dateTimeNow() + ".zip";//"C:\\gnhz\\uploadPath\\download\\批量导出岗位检查表-" + DateUtils.dateTimeNow() + ".zip";
        new ZipFileUtils().createZipFile(fileNameList, downloadPath + zipFileName);

        return success(File.separator + "download" + File.separator + zipFileName);
        //        /upload/2024/01/15/2024岗检方案_20240115131209A001_20240115155951A001.docx
        //        return success("/upload/2024/01/18/岗位责任制检查表_20240118001.xlsx");
    }
}
