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.ComProjectAudit;
import com.yiboshi.science.entity.ComTalentApply;
import com.yiboshi.science.entity.SystemParameter;
import com.yiboshi.science.enumeration.CommonEnum;
import com.yiboshi.science.param.dto.ComProjectAuditDTO;
import com.yiboshi.science.param.dto.ComProjectDTO;
import com.yiboshi.science.param.dto.ComTalentApplyDTO;
import com.yiboshi.science.param.dto.DataStatisticsDTO;
import com.yiboshi.science.param.query.ComTalentApplyQueryVO;
import com.yiboshi.science.rest.BaseController;
import com.yiboshi.science.service.ComProjectService;
import com.yiboshi.science.service.ComTalentApplyService;
import com.yiboshi.science.service.SystemParameterService;
import com.yiboshi.science.utils.ProjectInfoToPDF;
import com.yiboshi.science.utils.StringUtil;
import com.yiboshi.science.utils.TalentToPDF;
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.List;

import static com.yiboshi.science.utils.StringUtil.hideAllIdCardNum;
import static com.yiboshi.science.utils.StringUtil.hideAllPhoneNum;

@Api(tags = "com-talent-apply", description = "项目表")
@RestController
@RequestMapping("/v1/science-admin/com-talent-apply")
public class ComTalentApplyController extends BaseController<ComTalentApplyService, ComTalentApplyQueryVO, ComTalentApplyDTO, ComTalentApply> {

    @Autowired
    private ComTalentApplyService comTalentApplyService;

    @Autowired
    private ComProjectService comProjectService;

    @Autowired
    private SystemParameterService systemParameterService;

    @ApiOperation(value = "分页查询", httpMethod = "GET", notes = "根据参数获取列表")
    @GetMapping
    @RequestMapping(value = "/getListByPage")
    @PreAuthorize("hasAnyRole('REPORT','ADMIN')")
    public ResponseDataModel<Pagination<ComTalentApplyDTO>> getListByPage(@Validated ComTalentApplyQueryVO vo, BindingResult bindingResult) {
        if (!StringUtil.isContainsRole(SecurityUserHolder.getRoles(), CommonEnum.systemRole.sys.getCode().toString())) {
            vo.setAppPersonId(SecurityUserHolder.getPersonId());
        }

        Pagination<ComTalentApplyDTO> page = comTalentApplyService.getListByPage(vo);
        if (null != page && null != page.getDataList() && page.getDataList().size() != 0) {
            page.getDataList().forEach((e) -> {
                e.setCertId(hideAllIdCardNum(e.getCertId()));
                e.setMobile(hideAllPhoneNum(e.getMobile()));
                e.setTalentCategoryName(systemParameterService.getParaName(e.getTalentCategory()));
                if (null != e.getTalentState()) {
                    e.setTalentStateName(CommonEnum.talentState.getEnum(e.getTalentState()).getDescription());
                    if (e.getTalentState() >= 20 && !e.getTalentState().equals(30)) {
                        e.setTalentStateName("已上报");
                        e.setTalentState(20);
                    }
                }
            });
        }

        return ResponseDataModel.ok(page);
    }

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

    /**
     * 根据id获取人才申报信息
     *
     * @param id 查询条件
     */
    @ApiOperation(value = "根据id获取人才申报信息", httpMethod = "GET", notes = "根据id获取人才申报信息")
    @GetMapping
    @RequestMapping("/getTalentApplyById")
    public ResponseDataModel<ComTalentApplyDTO> getTalentApplyById(@Validated String id) {
        return ResponseDataModel.ok(comTalentApplyService.getTalentApplyById(id));
    }

    /**
     * 查询申报人是否当前年度是否上报
     *
     * @param
     */
    @ApiOperation(value = "根据id获取人才申报信息", httpMethod = "GET", notes = "根据id获取人才申报信息")
    @GetMapping
    @RequestMapping("/isTalentExist")
    public ResponseDataModel<Boolean> isTalentExist() {
        return ResponseDataModel.ok(comTalentApplyService.isTalentExist());
    }

    /**
     * 创建基础人才申报信息
     */
    @ApiOperation(value = "创建基础人才申报信息", httpMethod = "GET", notes = "创建基础人才申报信息")
    @GetMapping
    @RequestMapping("/getNewTalentApply")
    public ResponseDataModel<ComTalentApplyDTO> getNewTalentApply() {
        return ResponseDataModel.ok(comTalentApplyService.getNewTalentApply());
    }

    @ApiOperation(value = "保存人才申报信息", httpMethod = "POST", notes = "保存人才申报信息")
    @PostMapping
    @RequestMapping("/save")
    @PreAuthorize("hasAnyRole('REPORT','GOV','ADMIN')")
    @Logs(value = CommonEnum.logType.talentApplySave)
    public ResponseDataModel<String> save(@RequestBody ComTalentApplyDTO comTalentApplyDTO, BindingResult bindingResult) {
        return ResponseDataModel.ok(comTalentApplyService.save(comTalentApplyDTO));
    }

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

    @ApiOperation(value = "人才申报信息上报", httpMethod = "POST", notes = "人才申报信息上报")
    @PostMapping
    @RequestMapping("/report")
    @Logs(value = CommonEnum.logType.talentApplyReport)
    public ResponseDataModel<String> report(@Validated @RequestBody ComProjectAudit comProjectAudit) {
        comTalentApplyService.report(comProjectAudit, SecurityUserHolder.getUnitId(), SecurityUserHolder.getUnitCode());
        return ResponseDataModel.ok("上报成功");
    }

    /**
     * 人才申报信息审核
     */
    @ApiOperation(value = "人才申报信息审核", httpMethod = "POST", notes = "人才申报信息审核")
    @PostMapping
    @RequestMapping("/audit")
    @Logs(value = CommonEnum.logType.talentApplyAudit)
    public ResponseDataModel<String> audit(@Validated @RequestBody ComProjectAuditDTO comProjectAudit, BindingResult bindingResult) {
        comTalentApplyService.audit(comProjectAudit, SecurityUserHolder.getUnitId(), SecurityUserHolder.getUnitCode());
        return ResponseDataModel.ok("审核成功");
    }

    /**
     * 人才申报信息审核
     */
    @ApiOperation(value = "人才申报信息审核", httpMethod = "POST", notes = "人才申报信息审核")
    @PostMapping
    @RequestMapping("/batchAudit")
    @Logs(value = CommonEnum.logType.talentApplyAudit)
    public ResponseDataModel<String> batchAudit(@Validated @RequestBody ComProjectAuditDTO comProjectAudit, BindingResult bindingResult) {
        comTalentApplyService.batchAudit(comProjectAudit, SecurityUserHolder.getUnitId(), SecurityUserHolder.getUnitCode());
        return ResponseDataModel.ok("审核成功");
    }

    @ApiOperation(value = "项目信息导出", httpMethod = "POST", notes = "项目信息导出")
    @RequestMapping("/export/{id}")
    @PostMapping
    public void export(@PathVariable String id) throws DocumentException, IOException {
        try {
            ComTalentApplyDTO dto =comTalentApplyService.getTalentApplyById(id);

            // 生成PDF文件字节数组
            byte[] pdfBytes = TalentToPDF.createContractPdf(dto);

            // 设置响应头
            response.setContentType("application/pdf");
            String fileName = new String((dto.getPersonName() + ".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());
        }
    }

}
