package com.jeeplus.business.inscription.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeeplus.business.drive.service.dto.DriveApplyDTO;
import com.jeeplus.business.finance.util.EasyPoiUtil;
import com.jeeplus.business.goOut.service.dto.GoOutDTO;
import com.jeeplus.business.inscription.domain.Inscription;
import com.jeeplus.business.inscription.service.InscriptionService;
import com.jeeplus.business.inscription.service.dto.InscriptionDTO;
import com.jeeplus.business.project.domain.JyProject;
import com.jeeplus.business.project.utils.FreemarkerUtil;
import com.jeeplus.business.project.utils.JyResponseUtil;
import com.jeeplus.common.excel.ExcelOptions;
import com.jeeplus.common.excel.annotation.ExportMode;
import com.jeeplus.common.utils.ResponseUtil;
import com.jeeplus.logging.annotation.ApiLog;
import com.jeeplus.logging.constant.enums.LogTypeEnum;
import com.jeeplus.sys.domain.WorkAttachmentInfo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Api(tags ="文印申请")
@RestController
@RequestMapping(value = "/inscription")
public class InscriptionController {

    @Resource
    private InscriptionService inscriptionService;


    /**
     * 文印申请列表
     */
    @ApiOperation(value = "文印申请列表")
    @GetMapping(value = "/findList")
    public ResponseEntity<IPage<InscriptionDTO>> applyList(InscriptionDTO inscriptionDTO, Page<InscriptionDTO> page) throws Exception {
        IPage<InscriptionDTO> pageList=inscriptionService.findPageList(inscriptionDTO,page);
        return ResponseEntity.ok(pageList);
    }

    /**
     * 获取附件总页数
     */
    @ApiOperation(value = "获取附件总页数")
    @PostMapping(value = "/getPageTotal")
    public Integer getPageTotal(@RequestBody InscriptionDTO inscriptionDTO) throws IOException {
        Integer total=inscriptionService.getPageTotal(inscriptionDTO);
        return total;
    }


    /**
     * 新增/修改
     */
    @ApiOperation(value = "新增或修改")
    @PostMapping(value = "/saveForm")
    public ResponseEntity saveForm(@RequestBody InscriptionDTO inscriptionDTO){
        String id=inscriptionService.save(inscriptionDTO);
        return ResponseUtil.newInstance().add("businessTable","jy_inscription").add("businessId",id).ok("操作成功");
    }

    /**
     * 根据id查找文印信息
     */
    @ApiOperation(value = "根据id查找文印信息")
    @GetMapping(value = "findById")
    public ResponseEntity<InscriptionDTO> findById(@RequestParam String id){
        InscriptionDTO inscriptionDTO=inscriptionService.findById(id);
        return ResponseEntity.ok(inscriptionDTO);
    }

    /**
     * 根据id修改状态status
     * @param
     */
    @ApiOperation(value = "根据id修改状态status")
    @PostMapping(value = "/updateStatusById")
    public void updateStatusById(@RequestBody InscriptionDTO inscriptionDTO) {
        inscriptionService.updateStatusById(inscriptionDTO);
    }

    /**
     * 根据id进行删除
     */
    @ApiOperation(value = "根据id进行删除")
    @DeleteMapping(value = "/delete")
    public ResponseEntity<String> deleteById(@RequestParam String id){
        String s = inscriptionService.deleteById(id);
        return ResponseEntity.ok(s);
    }

    /**
     * 下载文印申请表
     */
    @RequestMapping(value="downloadInscription")
    @ResponseBody
    public void downloadInscription(HttpServletResponse response, Inscription inscription) throws ParseException {
        Map data = inscriptionService.getAuditInfoMap(inscription);
        //模板对象
        Template template=null;
        //下载文件地址
        String filePath = null;
        if(System.getProperty("os.name").toLowerCase().contains("win")){
            filePath = this.getClass().getResource("/").getPath()+"/freemarker";
        }else{
            filePath = "/mnt/project/cloud/freemarker";
        }
        //freemaker模板路径
        File path = new File(filePath);

        Configuration cfg = new Configuration();
        try {
            cfg.setDirectoryForTemplateLoading(path);
            //选择对应的ftl文件
            template = cfg.getTemplate("文印申请单.ftl","UTF-8");
            File docFile = new File("文印申请单.doc");
            FreemarkerUtil.generateFile(data,template,docFile);
            JyResponseUtil.docResponse("文印申请单.doc",docFile,response);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(System.getProperty("os.name").toLowerCase().contains("win")){
                //获取tomcat的路径
                String tomcatFilePath=System.getProperty("catalina.home");
                //删除tomcat目录下的处理后的文件信息
                File tomcatFile = new File(tomcatFilePath+"/bin/文印申请单.doc");
                if (tomcatFile.isFile()) {
                    tomcatFile.delete();
                }
            }else{
                //删除目录下的处理后的文件信息
                File tomcatFile = new File("/mnt/project/cloud/文印申请单.doc");
                if (tomcatFile.isFile()) {
                    tomcatFile.delete();
                }
            }
        }
    }

    /**
     * 管理员修改
     */
    @ApiOperation(value = "管理员修改")
    @PostMapping(value = "/adminEditForm")
    public ResponseEntity adminEditForm(@RequestBody InscriptionDTO inscriptionDTO){
        inscriptionService.adminEditForm(inscriptionDTO);
        return ResponseEntity.ok("操作成功");
    }

    @ApiLog(value = "导出文印申请数据", type = LogTypeEnum.EXPORT)
    @GetMapping("export")
    @ApiOperation(value = "导出文印申请数据")
    public void exportFile(InscriptionDTO inscriptionDTO, Page <InscriptionDTO> page, ExcelOptions options, HttpServletResponse response) throws Exception {
        String fileName = options.getFilename();
        String sheetName = options.getSheetName();
        List<InscriptionDTO> result = new ArrayList<>();
        if ( ExportMode.current.equals ( options.getMode() ) ) {
            result = inscriptionService.findPageList(inscriptionDTO,page).getRecords();
        } else if (ExportMode.selected.equals ( options.getMode() )) {
            result = inscriptionService.findPageList(inscriptionDTO,page).getRecords().stream ( ).filter ( item ->
                    options.getSelectIds ( ).contains ( item.getId ( ) )
            ).collect ( Collectors.toList ( ) );
        } else {
            page.setSize (-1);
            page.setCurrent (0);
            result = inscriptionService.findPageList(inscriptionDTO,page).getRecords();
        }
        EasyPoiUtil.exportExcel ( result, sheetName,  sheetName, InscriptionDTO.class, fileName, response );

    }


}
