package com.yiboshi.science.rest.v1;

import com.itextpdf.text.DocumentException;
import com.yiboshi.arch.base.ResponseDataModel;
import com.yiboshi.science.base.Pagination;
import com.yiboshi.science.config.annotation.Logs;
import com.yiboshi.science.config.security.SecurityUserHolder;
import com.yiboshi.science.entity.*;
import com.yiboshi.science.enumeration.CommonEnum;
import com.yiboshi.science.param.dto.*;
import com.yiboshi.science.param.query.ComProjectQueryVO;
import com.yiboshi.science.rest.BaseController;
import com.yiboshi.science.service.ComFileService;
import com.yiboshi.science.service.ComProjectService;
import com.yiboshi.science.service.ComProjectTaskService;
import com.yiboshi.science.service.SystemParameterService;
import com.yiboshi.science.utils.ProjectInfoToPDF;
import com.yiboshi.science.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * 功能：项目表 接口
 *
 * @author lkl
 * @version 2021-08-26
 */
@Api(tags = "com-project", description = "项目表")
@RestController
@RequestMapping("/v1/science-admin/com-project")
public class ComProjectController extends BaseController<ComProjectService, ComProjectQueryVO, ComProjectDTO, ComProject> {

    @Autowired
    private ComProjectService comProjectService;

    @Autowired
    private ComProjectTaskService comProjectTaskService;

    @Autowired
    private ComFileService comFileService;

    @Autowired
    private SystemParameterService systemParameterService;

    /**
     * 功能:分页查询
     *
     * @param vo 查询条件
     */
    @ApiOperation(value = "分页查询", httpMethod = "GET", notes = "根据参数获取列表")
    @GetMapping
    @RequestMapping(value = "/getListByPage")
    @PreAuthorize("hasAnyRole('REPORT','ADMIN')")
    public ResponseDataModel<Pagination<ComProjectDTO>> getListByPage(@Validated ComProjectQueryVO vo, BindingResult bindingResult) {
        if (!StringUtil.isContainsRole(SecurityUserHolder.getRoles(), CommonEnum.systemRole.sys.getCode().toString())) {
            vo.setAppPersonId(SecurityUserHolder.getPersonId());
        }
        Pagination<ComProjectDTO> page = comProjectService.getListByPage(vo);
        if (null != page && null != page.getDataList() && page.getDataList().size() != 0) {
            page.getDataList().forEach((e) -> {
                if (null != e.getProjState())
                    e.setProjStateName(CommonEnum.projState.getEnum(e.getProjState()).getDescription());
            });
        }
        return ResponseDataModel.ok(page);
    }

    /**
     * 获取统计数据
     */
    @ApiOperation(value = "获取统计数据", httpMethod = "GET", notes = "获取统计数据")
    @GetMapping
    @RequestMapping("/getCount")
    public ResponseDataModel<DataStatisticsDTO> getCount(@Validated ComProject e) {
        e.setAppPersonId(SecurityUserHolder.getPersonId());
        return ResponseDataModel.ok(comProjectService.getCount(e));
    }

    /**
     * 根据id获取项目信息
     *
     * @param id 查询条件
     */
    @ApiOperation(value = "根据id获取项目信息", httpMethod = "GET", notes = "根据id获取项目信息")
    @GetMapping
    @RequestMapping("/getProjectInfoById")
    public ResponseDataModel<ComProjectDTO> getProjectInfoById(@Validated String id) {
        return ResponseDataModel.ok(comProjectService.getProjectById(id));
    }

    /**
     * 创建基础项目信息
     */
    @ApiOperation(value = "创建基础项目信息", httpMethod = "GET", notes = "创建基础项目信息")
    @GetMapping
    @RequestMapping("/getNewProject")
    public ResponseDataModel<ComProjectDTO> getNewProject(Integer systemType) {
        return ResponseDataModel.ok(comProjectService.getNewProject(systemType));
    }

    /**
     * 保存项目信息
     *
     * @param comProjectDTO
     */
    @ApiOperation(value = "保存项目信息", httpMethod = "POST", notes = "保存项目信息")
    @PostMapping
    @RequestMapping("/save")
    @PreAuthorize("hasAnyRole('REPORT','GOV','ADMIN')")
    @Logs(value = CommonEnum.logType.projectSave)
    public ResponseDataModel<String> save(@RequestBody ComProjectDTO comProjectDTO, BindingResult bindingResult) {
        return ResponseDataModel.ok(comProjectService.save(comProjectDTO));
    }

    /**
     * 保存项目信息
     *
     * @param comProjectDTO
     */
    @ApiOperation(value = "修改申报单位", httpMethod = "POST", notes = "修改申报单位")
    @PostMapping
    @RequestMapping("/updateUnit")
    @PreAuthorize("hasAnyRole('GOV','ADMIN')")
    @Logs(value = CommonEnum.logType.appUnitUpdate)
    public ResponseDataModel<String> updateUnit(@RequestBody ComProjectDTO comProjectDTO, BindingResult bindingResult) {
        return ResponseDataModel.ok(comProjectService.updateUnit(comProjectDTO));
    }

    /**
     * 项目/任务书/中期考核表上报
     */
    @ApiOperation(value = "项目/任务书/中期考核表上报", httpMethod = "POST", notes = "项目/任务书/中期考核表上报")
    @PostMapping
    @RequestMapping("/report")
    @Logs(value = CommonEnum.logType.projectReport)
    public ResponseDataModel<String> report(@Validated @RequestBody ComProjectAudit comProjectAudit) {
        comProjectService.report(comProjectAudit, SecurityUserHolder.getUnitId(), SecurityUserHolder.getUnitCode());
        return ResponseDataModel.ok("上报成功");
    }

    /**
     * 项目/任务书/中期考核表审核
     */
    @ApiOperation(value = "项目/任务书/中期考核表审核", httpMethod = "POST", notes = "项目/任务书/中期考核表审核")
    @PostMapping
    @RequestMapping("/audit")
    @Logs(value = CommonEnum.logType.projectAudit)
    public ResponseDataModel<String> audit(@Validated @RequestBody ComProjectAuditDTO comProjectAudit, BindingResult bindingResult) {
        comProjectService.audit(comProjectAudit, SecurityUserHolder.getUnitId(), SecurityUserHolder.getUnitCode());
        return ResponseDataModel.ok("审核成功");
    }

    /**
     * 项目/任务书/中期考核表审核
     */
    @ApiOperation(value = "项目/任务书/中期考核表审核", httpMethod = "POST", notes = "项目/任务书/中期考核表审核")
    @PostMapping
    @RequestMapping("/batchAudit")
    @Logs(value = CommonEnum.logType.projectAudit)
    public ResponseDataModel<String> batchAudit(@Validated @RequestBody ComProjectAuditDTO comProjectAudit, BindingResult bindingResult) {
        comProjectService.batchAudit(comProjectAudit, SecurityUserHolder.getUnitId(), SecurityUserHolder.getUnitCode());
        return ResponseDataModel.ok("审核成功");
    }

    @ApiOperation(value = "获取项目状态", httpMethod = "GET", notes = "获取项目状态")
    @GetMapping
    @RequestMapping("/getProjStateList")
    public ResponseDataModel<List<SelectListItem>> getProjStateList() {
        List<SelectListItem> list = new ArrayList<>(CommonEnum.projState.values().length);
        for (CommonEnum.projState type : CommonEnum.projState.values()) {
            SelectListItem item = new SelectListItem();
            item.setKey(type.getCode().toString());
            item.setTitle(type.getDescription());
            list.add(item);
        }
        return ResponseDataModel.ok(list);
    }

    /**
     * @param id
     * @return
     */
    @ApiOperation(value = "删除", httpMethod = "DELETE", notes = "删除")
    @DeleteMapping
    @RequestMapping(value = "delete/{id}")
    @Logs(value = CommonEnum.logType.projectDelete)
    public ResponseDataModel<String> delete(@PathVariable String id) {
        return ResponseDataModel.ok(comProjectService.delete(id));
    }

    @ApiOperation(value = "项目导入", httpMethod = "POST", notes = "项目导入")
    @RequestMapping("/projectImport")
    @PostMapping
    public ResponseDataModel<List<ProjectImportDTO>> projectImport (@Validated @RequestBody List<ProjectImportDTO> list) throws IOException {
        return ResponseDataModel.ok(comProjectService.projectImport(list));
    }

    @ApiOperation(value = "项目信息导出", httpMethod = "POST", notes = "项目信息导出")
    @RequestMapping("/projectExport/{id}")
    @PostMapping
    public void projectExport(@PathVariable String id) throws DocumentException, IOException {
        try {
            List<SystemParameter> list = systemParameterService.getListByType(67);
            ComProjectDTO dto = comProjectService.getProjectById(id);

            // 生成PDF文件字节数组
            byte[] pdfBytes = ProjectInfoToPDF.generateProjectPDF(dto, list);

            // 设置响应头
            response.setContentType("application/pdf");
            String fileName = new String((dto.getProjName() + ".pdf").getBytes("UTF-8"), "ISO-8859-1");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            response.setContentLength(pdfBytes.length);

            // 写入响应流
            try (ServletOutputStream out = response.getOutputStream()) {
                out.write(pdfBytes);
                out.flush();
            }
        } catch (Exception e) {
            response.setContentType("text/plain;charset=UTF-8");
            response.getWriter().write("导出PDF失败：" + e.getMessage());
        }
    }

    @ApiOperation(value = "1.02", httpMethod = "POST", notes = "1.02 修改人员状态")
    @RequestMapping("/updateDefenseScore")
    @PostMapping
    @PreAuthorize("hasAnyRole('GOV')")
    public ResponseDataModel<String> updateDefenseScore(@RequestBody ComProject e) {
        return ResponseDataModel.ok(comProjectService.updateDefenseScore(e.getId(), e.getDefenseTechnologyScore(), e.getDefenseEconomyScore()));
    }

}
