package com.weaver.seconddev.chapanda.hrm.controller;

import com.alibaba.fastjson.JSONArray;
import com.weaver.common.authority.annotation.WeaPermission;
import com.weaver.common.base.entity.result.WeaResult;
import com.weaver.seconddev.chapanda.hrm.constant.Constants;
import com.weaver.seconddev.chapanda.hrm.constant.DownLoadTypeEnum;
import com.weaver.seconddev.chapanda.hrm.service.HrmDownloadFilesService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/secondev/chapanda/hrm/cert")
public class HrmCertificateFilesController {

    private final Logger log = LoggerFactory.getLogger(HrmCertificateFilesController.class);

    @Autowired
    HrmDownloadFilesService hrmDownloadFilesService;

    /***
     *
     * @param paramMap
     * @return
     */
    @WeaPermission(publicPermission = true)
    @PostMapping("/getincomepath")
    public WeaResult<Object> getIncomePath(@RequestBody Map<String,Object> paramMap){
        String data = String.valueOf(paramMap.get("data"));
        log.error("data:{}",data);
        JSONArray dataArray = new JSONArray();
        if(StringUtils.isNotBlank(data)){
            String decodedData = hrmDownloadFilesService.convertBase64Data(data);
            log.error("decodedData:{}",decodedData);
            if(StringUtils.isNotBlank(decodedData)){
                try{
                    dataArray = JSONArray.parseArray(decodedData);
                }catch (Exception e){
                    log.error("{}",e);
                }
            }
        }
        log.error("dataArray:{}",dataArray.size());

        String newZipFilePath = hrmDownloadFilesService.convertZipFile(dataArray, DownLoadTypeEnum.INCOME.getPath());

        Map<String,Object> dataMap = new HashMap<String,Object>();
        dataMap.put("filepath",newZipFilePath);
        return WeaResult.success(dataMap);
    }


    /***
     * 离职证明下载接口
     * @param paramMap
     * @return
     */
    @WeaPermission(publicPermission = true)
    @PostMapping("/getresignpath")
    public WeaResult<Object> getResignPath(@RequestBody Map<String,Object> paramMap){
        String data = String.valueOf(paramMap.get("data"));
        log.error("data:{}",data);
        JSONArray dataArray = new JSONArray();
        if(StringUtils.isNotBlank(data)){
            String decodedData = hrmDownloadFilesService.convertBase64Data(data);
            log.error("decodedData:{}",decodedData);
            if(StringUtils.isNotBlank(decodedData)){
                try{
                    dataArray = JSONArray.parseArray(decodedData);
                }catch (Exception e){
                    log.error("{}",e);
                }
            }
        }
        log.error("dataArray:{}",dataArray.size());

        String newZipFilePath = hrmDownloadFilesService.convertZipFile(dataArray, DownLoadTypeEnum.RESIGN.getPath());
        Map<String,Object> dataMap = new HashMap<String,Object>();
        dataMap.put("filepath",newZipFilePath);
        return WeaResult.success(dataMap);
    }


    /***
     * 在职证明下载接口
     * @param paramMap
     * @return
     */
    @WeaPermission(publicPermission = true)
    @PostMapping("/getemploymentpath")
    public WeaResult<Object> getEmploymentPath(@RequestBody Map<String,Object> paramMap){
        String data = String.valueOf(paramMap.get("data"));
        log.error("data:{}",data);
        JSONArray dataArray = new JSONArray();
        if(StringUtils.isNotBlank(data)){
            String decodedData = hrmDownloadFilesService.convertBase64Data(data);
            if(StringUtils.isNotBlank(decodedData)){
                try{
                    dataArray = JSONArray.parseArray(decodedData);
                }catch (Exception e){
                    log.error("{}",e);
                }
            }
        }
        log.error("dataArray:{}",dataArray.size());

        String newZipFilePath = hrmDownloadFilesService.convertZipFile(dataArray,DownLoadTypeEnum.EMPLOYMENT.getPath());

        Map<String,Object> dataMap = new HashMap<String,Object>();
        dataMap.put("filepath",newZipFilePath);
        return WeaResult.success(dataMap);
    }


    @WeaPermission(publicPermission = true)
    @PostMapping("/getcontractpath")
    public WeaResult<Object> getContractPath(@RequestBody Map<String,Object> paramMap){
        String data = String.valueOf(paramMap.get("data"));
        log.error("data:{}",data);
        JSONArray dataArray = new JSONArray();
        if(StringUtils.isNotBlank(data)){
            String decodedData = hrmDownloadFilesService.convertBase64Data(data);
            if(StringUtils.isNotBlank(decodedData)){
                try{
                    dataArray = JSONArray.parseArray(decodedData);
                }catch (Exception e){
                    log.error("{}",e);
                }
            }
        }
        log.error("dataArray:{}",dataArray.size());

        String newZipFilePath = hrmDownloadFilesService.convertZipFile(dataArray, DownLoadTypeEnum.CONTRACT.getPath());

        Map<String,Object> dataMap = new HashMap<String,Object>();
        dataMap.put("filepath",newZipFilePath);
        return WeaResult.success(dataMap);
    }

    /***
     * 电子签名模板预览接口
     * @return
     * @throws IOException
     */
    @WeaPermission(publicPermission = true)
    @GetMapping("/downloadZip")
    public ResponseEntity downloadZip(HttpServletRequest request) throws IOException{
        String data = request.getParameter("data");
        String type = request.getParameter("type");
        log.error("data2:{}",data);
        log.error("typ2e:{}",type);
        String filename = "";
        try{
            DownLoadTypeEnum[] values = DownLoadTypeEnum.values();
            for (DownLoadTypeEnum item : values) {
                log.error("item.getCode():{}",item.getCode());
                if(item.getCode().equals(type)){
                    filename = DownLoadTypeEnum.INCOME.getFileName();
                }
            }
            if(StringUtils.isNotBlank(filename)){
                filename = URLEncoder.encode(filename, "UTF-8");  // 使用UTF-8编码
            }
        }catch (Exception e){
            log.error("e:{}",e);
        }

        log.error("filename2:{}",filename);

        if(StringUtils.isNotBlank(filename)){
            log.error("data:{}",data);
            String zipFilePath = "";
            if(StringUtils.isNotBlank(data)){
                zipFilePath = hrmDownloadFilesService.convertBase64Data(data);
            }
            log.error("zipFilePath:{}",zipFilePath);
            if(StringUtils.isNotBlank(zipFilePath) && zipFilePath.contains(Constants.templatePath) && new File(zipFilePath).exists()){
                // 文件转成字节数组
                File file = ResourceUtils.getFile(zipFilePath);
                byte[] fileBytes = Files.readAllBytes(file.toPath());
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                String filename2 = filename+"-"+sdf.format(new Date())+".zip";
                log.error("filename2:{}",filename2);

                return ResponseEntity.ok().contentType(MediaType.APPLICATION_OCTET_STREAM)
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + new String(filename2.getBytes(), "UTF-8") + "\"")
                        .body(fileBytes);
            }else{
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new String("文件下载失败".getBytes(), "utf-8"));
            }
        }else{
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new String("文件下载失败".getBytes(), "utf-8"));
        }
    }



    /**
     * 测试接口
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @WeaPermission(publicPermission = true)
    @GetMapping("/test")
    public WeaResult<Object> test(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String, Object> recordMap = new HashMap<String,Object>();
        recordMap.put("test","test");
        return WeaResult.success(recordMap);
    }

}
