package com.ruoyi.gysl.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.crypto.SmUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.docking.entity.SmartDeclaration;
import com.ruoyi.docking.service.SmartDeclarationService;
import com.ruoyi.gysl.entity.*;
import com.ruoyi.gysl.entity.request.AuditRequest;
import com.ruoyi.gysl.entity.request.BasicInformationPageReq;
import com.ruoyi.gysl.entity.response.BasicInformationResponse;
import com.ruoyi.gysl.entity.response.ProjectExcelInfo;
import com.ruoyi.gysl.login.util.SM2Demo;
import com.ruoyi.gysl.login.util.SM4Demo;
import com.ruoyi.gysl.login.util.StringUtil;
import com.ruoyi.gysl.service.*;
import com.ruoyi.system.mapper.SysDictDataMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.*;

/**
 * 基本信息(BasicInformation)表控制层
 *
 * @author makejava
 * @since 2025-02-24 09:25:51
 */
@Api(tags = "基本信息")
@RestController
@RequestMapping("/gysl/basicInformation")
public class BasicInformationController extends BaseController {
    @Value("${ruoyi.profile}")
    private String fileAddress;

    @Resource
    private SysDictDataMapper sysDictDataMapper;
    /**
     * 基本信息
     */
    @Resource
    private BasicInformationService basicInformationService;

    /**
     * 规划信息
     */
    @Resource
    private PlanInformationService planInformationService;

    /**
     * 模型信息
     */
    @Resource
    private MxService mxService;

    /**
     * 消息通知
     */
    @Resource
    private SmartDeclarationService smartDeclarationService;

    /**
     * 五要素模型信息
     */
    @Resource
    private WysmxInformationService wysmxInformationService;


    /**
     * 企业入驻信息
     */
    @Resource
    private QyrzInformationService qyrzInformationService;

    /**
     * 其他信息
     */
    @Resource
    private ProjectOtherInfoService projectOtherInfoService;


    @Value("${isZs}")
    private Boolean isZs;
    private static final String BOUNDARY = "----WebKitFormBoundary7MA4YWxkTrZu0gW"; // 边界字符串（需唯一）

    @Value("${sm2}")
    private String sm2;

    @Value("${sm4}")
    private String sm4;

    @Value("${accessId}")
    private String accessId;

    @Value("${sceneId}")
    private String sceneId;

    /**
     * 建筑工程施工许可
     */
    @ApiOperation("建筑工程施工许可")
    @GetMapping("/getJzgcsgxk")
    public AjaxResult getJzgcsgxk() throws Exception {
        if (isZs) {
            String czztdm = "91320594608197761G";
            String contacts = "http://172.21.10.46/api/invoke/323018/jzgcsgxk";
            String a1 = Base64.getEncoder().encodeToString((byte[])
                    SM4Demo.exec(accessId.getBytes(),
                            "ECB", "PKCS5Padding", "random", sm4.getBytes(), null));
            String a2 = Base64.getEncoder().encodeToString((byte[])
                    SM4Demo.exec(czztdm.getBytes(),
                            "ECB", "PKCS5Padding", "random", sm4.getBytes(), null));
            String a4 = Base64.getEncoder().encodeToString((byte[])
                    SM4Demo.exec(sceneId.getBytes(),
                            "ECB", "PKCS5Padding", "random", sm4.getBytes(), null));
            //生成sm3签名
            String input = "accessId=" + accessId + "&czztdm=" + czztdm + "&sceneId=" + sceneId;
            try {
                // 1. 构建 URL（含签名参数，处理特殊符号）
                String encodedSignature = URLEncoder.encode(SmUtil.sm3(input), "UTF-8")
                        .replace("+", "%20"); // 确保 + 不被编码为空格
                String fullUrl = contacts + "?signature=" + encodedSignature;
                // 2. 创建连接
                URL url = new URL(fullUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
                conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

                // 3. 构建请求体（严格对齐 curl -F 格式）
                try (DataOutputStream out = new DataOutputStream(conn.getOutputStream())) {
                    writeFormField(out, "accessId", a1);
                    writeFormField(out, "czztdm", a2);
                    writeFormField(out, "sceneId", a4);
                    // 结束标记
                    out.writeBytes("--" + BOUNDARY + "--\r\n");
                }
                // 4. 处理响应
                int statusCode = conn.getResponseCode();
                StringBuilder response = getResponse(statusCode, conn);
                if (statusCode == 200) {
                    JSONObject jsonObj = JSONObject.parseObject(String.valueOf(response));
//                    if ("200".equals(jsonObj.getString("code"))) { // 使用 getString 避免类型问题
                    // 直接获取 data 字段为 JSONObject（无需转换 String）
                    JSONObject reqData = jsonObj.getJSONObject("data");
                    String responseParams = reqData.getString("responseParams");
                    String s = new String((byte[]) SM2Demo.dexec(
                            Base64.getDecoder().decode(responseParams), "C1C2C3",
                            Base64.getDecoder().decode(sm2)),
                            StandardCharsets.UTF_8);
                    return AjaxResult.success(StringUtil.getFinalData(s));
                }
//                }
            } catch (Exception y) {
                y.printStackTrace();
            }
        }
        return success();
    }

    /**
     * 建筑工程竣工验收备案表
     */
    @ApiOperation("建筑工程竣工验收备案表")
    @GetMapping("/getJgysbab")
    public AjaxResult getJgysbab() throws Exception {
        if (isZs) {
            String czztdm = "9132059456176406XP";
            String czztmc = "苏州纳米科技发展有限公司";
            System.out.println(czztdm);
            System.out.println(czztmc);
            String contacts = "http://172.21.10.46/api/invoke/323018/jzgcjgysbab";
            String a1 = Base64.getEncoder().encodeToString((byte[])
                    SM4Demo.exec(accessId.getBytes(),
                            "ECB", "PKCS5Padding", "random", sm4.getBytes(), null));
            String a2 = Base64.getEncoder().encodeToString((byte[])
                    SM4Demo.exec(czztdm.getBytes(),
                            "ECB", "PKCS5Padding", "random", sm4.getBytes(), null));
            String a3 = Base64.getEncoder().encodeToString((byte[])
                    SM4Demo.exec(czztmc.getBytes(),
                            "ECB", "PKCS5Padding", "random", sm4.getBytes(), null));
            String a4 = Base64.getEncoder().encodeToString((byte[])
                    SM4Demo.exec(sceneId.getBytes(),
                            "ECB", "PKCS5Padding", "random", sm4.getBytes(), null));
            //生成sm3签名
            String input = "accessId=" + accessId + "&czztdm=" + czztdm + "&czztmc=" + czztmc + "&sceneId=" + sceneId;
            try {
                // 1. 构建 URL（含签名参数，处理特殊符号）
                String encodedSignature = URLEncoder.encode(SmUtil.sm3(input), "UTF-8")
                        .replace("+", "%20"); // 确保 + 不被编码为空格
                String fullUrl = contacts + "?signature=" + encodedSignature;
                // 2. 创建连接
                URL url = new URL(fullUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
                conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

                // 3. 构建请求体（严格对齐 curl -F 格式）
                try (DataOutputStream out = new DataOutputStream(conn.getOutputStream())) {
                    writeFormField(out, "accessId", a1);
                    writeFormField(out, "czztdm", a2);
                    writeFormField(out, "czztmc", a3);
                    writeFormField(out, "sceneId", a4);
                    // 结束标记
                    out.writeBytes("--" + BOUNDARY + "--\r\n");
                }
                // 4. 处理响应
                int statusCode = conn.getResponseCode();
                StringBuilder response = getResponse(statusCode, conn);
                if (statusCode == 200) {
                    JSONObject jsonObj = JSONObject.parseObject(String.valueOf(response));
//                    if ("200".equals(jsonObj.getString("code"))) { // 使用 getString 避免类型问题
                    // 直接获取 data 字段为 JSONObject（无需转换 String）
                    JSONObject reqData = jsonObj.getJSONObject("data");
                    String responseParams = reqData.getString("responseParams");
                    String s = new String((byte[]) SM2Demo.dexec(
                            Base64.getDecoder().decode(responseParams), "C1C2C3",
                            Base64.getDecoder().decode(sm2)),
                            StandardCharsets.UTF_8);
                    System.out.println(s);
                    return AjaxResult.success(StringUtil.getFinalData(s));
                }
            } catch (Exception y) {
                y.printStackTrace();
            }
        }
        return success();
    }

    private static StringBuilder getResponse(int statusCode, HttpURLConnection conn) throws IOException {
        StringBuilder response = new StringBuilder();
        try (BufferedReader in = new BufferedReader(new InputStreamReader(
                (statusCode >= 200 && statusCode < 300) ? conn.getInputStream() : conn.getErrorStream(),
                StandardCharsets.UTF_8))) {
            String line;
            while ((line = in.readLine()) != null) {
                response.append(line);
            }
        }
        return response;
    }

    private static void writeFormField(DataOutputStream out, String name, String value) throws Exception {
        out.writeBytes("--" + BOUNDARY + "\r\n");
        out.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"\r\n");
        out.writeBytes("Content-Type: text/plain; charset=UTF-8\r\n\r\n");
        out.writeBytes(value + "\r\n");
    }

    /**
     * 分页查询所有数据
     *
     * @param page                    分页对象
     * @param basicInformationPageReq 查询实体
     * @return 所有数据
     */
    @ApiOperation(value = "分页查询所有数据", response = BasicInformation.class)
    @GetMapping("/page")
    public AjaxResult selectAll(Page<BasicInformation> page, BasicInformationPageReq basicInformationPageReq) {
        // 获取当前登录用户是否是企业端
        try {
            if (SecurityUtils.hasRole("company") && !SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
                basicInformationPageReq.setTyshxydm(SecurityUtils.getUsername());
            }
        } catch (Exception ignored) {
        }
        return success(basicInformationService.page(page, basicInformationPageReq));
    }

    /**
     * 企业端暂存
     */
    @PreAuthorize("@ss.hasAnyRoles('company')")
    @ApiOperation(value = "企业端暂存")
    @PostMapping("/staging")
    public AjaxResult staging(@RequestBody AuditRequest req) {
        BasicInformation byId = basicInformationService.getById(req.getBasicInformation().getId());
        if (byId.getStatus() != 1) {
            throw new ServiceException("不能暂存!");
        }
        return success(basicInformationService.staging(req));
    }

    /**
     * 企业端提交填报
     */
    @PreAuthorize("@ss.hasAnyRoles('company')")
    @ApiOperation(value = "企业端提交填报")
    @PostMapping("/fill")
    public AjaxResult fill(@RequestBody AuditRequest req) {
        BasicInformation byId = basicInformationService.getById(req.getBasicInformation().getId());
        if (byId.getStatus() != 1) {
            throw new ServiceException("暂不能提交!");
        }
        return success(basicInformationService.audit(req, 2, byId.getStatus()));
    }

    /**
     * 政务端审核
     */
    @PreAuthorize("@ss.hasAnyRoles('admin,common,gov')")
    @ApiOperation(value = "政务端审核")
    @PostMapping("/audit")
    public AjaxResult audit(@RequestBody AuditRequest req) {
        BasicInformation byId = basicInformationService.getById(req.getBasicInformation().getId());
        if (byId.getStatus() == 1) {
            throw new ServiceException("请等待企业填报!");
        }
        return success(basicInformationService.audit(req, 3, byId.getStatus()));
    }

    /**
     * 通过主键查询单条项目所有数据(企业端)
     *
     * @param id 主键
     * @return 单条数据
     */
    @PreAuthorize("@ss.hasAnyRoles('company')")
    @ApiOperation(value = "通过主键查询单条项目所有数据(企业端)", response = BasicInformationResponse.class)
    @GetMapping("/stagingInfo/{id}")
    public AjaxResult stagingInfo(@PathVariable Long id) {
        return success(basicInformationService.stagingInfo(id));
    }


    /**
     * 通过主键查询单条项目所有数据(政务端)
     *
     * @param id 主键
     * @return 单条数据
     */
    @PreAuthorize("@ss.hasAnyRoles('admin,common,gov')")
    @ApiOperation(value = "通过主键查询单条项目所有数据(政务端)", response = BasicInformationResponse.class)
    @GetMapping("/{id}")
    public AjaxResult selectOne(@PathVariable Long id) {
        return success(basicInformationService.selectOne(id));
    }


    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @ApiOperation("删除数据")
    @DeleteMapping("/delete")
    public AjaxResult delete(@RequestParam("idList") List<Long> idList) {
        //要删除其余所有表对应的数据
        basicInformationService.removeByXmIds(idList);
        return success();
    }

    /**
     * 项目基本信息批量导入
     */
    @ApiOperation(value = "项目基本信息批量导入")
//    @PreAuthorize("@ss.hasAnyRoles('admin,common')")
    @PostMapping(value = "/import", consumes = "multipart/form-data")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult importTemplateProject(@RequestPart("file") MultipartFile file) throws Exception {
        ExcelUtil<BasicInformation> util = new ExcelUtil<>(BasicInformation.class);
        List<BasicInformation> proList = util.importExcel(file.getInputStream());
        StringBuilder successMsg = new StringBuilder();
        if (proList == null || proList.isEmpty()) {
            throw new ServiceException("项目导入数据不能为空");
        } else {
            List<Mx> list = mxService.list();
            basicInformationService.saveBatch(proList);
            proList.forEach(x -> {
                //添加项目规划信息
                PlanInformation planInformation = new PlanInformation();
                planInformation.setXmId(x.getId());
                planInformationService.save(planInformation);
                //添加五要素模型信息
                List<WysmxInformation> wys = new ArrayList<>();
                list.forEach(y -> {
                    WysmxInformation wysmxInformation = new WysmxInformation();
                    wysmxInformation.setYsmc(y.getName());
                    wysmxInformation.setZdname(y.getJtzb());
                    wysmxInformation.setXmId(x.getId());
                    wys.add(wysmxInformation);
                });
                wysmxInformationService.saveBatch(wys);
                //企业入驻信息
                QyrzInformation qyrzInformation = new QyrzInformation();
                qyrzInformation.setXmId(x.getId());
                qyrzInformationService.save(qyrzInformation);
                //基本信息
                String[] otherInfo = {"改造前容积率", "改造后容积率", "亩均税收(万元/每亩)", "亩均销售(万元/每亩)", "贷款情况", "荣誉情况"};
                List<ProjectOtherInfo> saveOther = new ArrayList<>();
                Arrays.asList(otherInfo).forEach(y -> {
                    ProjectOtherInfo projectOtherInfo = new ProjectOtherInfo();
                    projectOtherInfo.setXmId(x.getId());
                    projectOtherInfo.setZdname(y);
                    saveOther.add(projectOtherInfo);
                });
                projectOtherInfoService.saveBatch(saveOther);
                //新增消息(也就是智能提醒)
                SmartDeclaration notice = new SmartDeclaration();
                notice.setTyshxydm(x.getTyshxydm());
                notice.setContent("关于" + x.getName() + "项目,待填报的通知");
                smartDeclarationService.save(notice);
            });
            successMsg.append("导入成功");
        }
        return AjaxResult.success(successMsg);
    }

    /**
     * 导出项目数据
     */
//    @PreAuthorize("@ss.hasAnyRoles('admin,common')")
    @ApiOperation("导出项目数据")
    @PostMapping("/exportInfo")
    public void exportInfo(HttpServletResponse response) {
        List<ProjectExcelInfo> pE = basicInformationService.selectList();
        ExcelUtil<ProjectExcelInfo> util = new ExcelUtil<>(ProjectExcelInfo.class);
        util.exportExcel(response, pE, "项目数据");
    }


    /**
     * 模板信息
     */
    @ApiOperation("导出基本信息模板")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<BasicInformation> util = new ExcelUtil<>(BasicInformation.class);
        util.importTemplateExcel(response, "项目数据");
    }

    /**
     * 根据条件导出基本信息
     */
    @ApiOperation(value = "根据条件导出基本信息")
    @PostMapping(value = "/export")
    public void export(HttpServletResponse response, @RequestParam Long xmid) throws Exception {
        List<BasicInformation> filteredList = new ArrayList<>();
        BasicInformation a1 = basicInformationService.getById(xmid);
        filteredList.add(a1);
        ExcelUtil<BasicInformation> util = new ExcelUtil<>(BasicInformation.class);
        util.exportExcel(response, filteredList, "基本信息");
    }

//    @ApiOperation(value = "123")
////    @PreAuthorize("@ss.hasAnyRoles('admin,common')")
//    @PostMapping(value = "/import1", consumes = "multipart/form-data")
//    @Transactional(rollbackFor = Exception.class)
//    public AjaxResult import1(@RequestPart("file") MultipartFile file) throws Exception {
//        ExcelUtil<ProjectExcelInfo> util = new ExcelUtil<>(ProjectExcelInfo.class);
//        List<ProjectExcelInfo> proList = util.importExcel(file.getInputStream());
//        proList.forEach(x->{
//            // 1. 分割字符串
//            String[] dates = x.getA1().split("-");
//            if (dates.length != 2) {
//                throw new IllegalArgumentException("无效的日期范围格式");
//            }
//            BasicInformation basicInformation = new BasicInformation();
//            basicInformation.setName(x.getName());
//            basicInformation.setXmfrdwxz(x.getXmfrdwxz());
//            basicInformation.setNature(x.getNature());
//            basicInformation.setBegainTime(dates[0].replace(".","-").trim());
//            basicInformation.setEndTime(dates[1].replace(".","-").trim());
//            basicInformation.setXzfl(x.getXzfl());
//            basicInformation.setJhtze(x.getJhtze());
//            basicInformation.setProjectLeader(x.getProjectLeader());
//            basicInformation.setPhone(x.getPhone());
//            basicInformation.setJsjd(x.getJsjd());
//            basicInformation.setJsms(x.getJsms());
//            basicInformation.setPrioritize(x.getPrioritize());
//            basicInformation.setStatus(3);
//            PlanInformation planInformation = new PlanInformation();
//            planInformation.setZydmj(x.getZydmj());
//            planInformation.setRjl(x.getRjl());
//            planInformation.setZjzmj(x.getZjzmj());
//            planInformation.setBzcjzmj(x.getBzcjzmj());
//            basicInformationService.save(basicInformation);
//            planInformation.setXmId(basicInformation.getId());
//            planInformationService.save(planInformation);
//        });
//        return AjaxResult.success();
//    }

//    /**
//     * 123
//     */
//    @ApiOperation("66666")
//    @PostMapping("/a5")
//    public void e1() {
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        // 待转换的字符串
//        String dateTimeStr = "2025-04-11 16:52:19";
//        // 转换为 LocalDateTime
//        List<BasicInformation> list = basicInformationService.list();
//        List<Mx> mx1 = mxService.list();
//        list.forEach(x-> {
//            //添加五要素模型信息
//            List<WysmxInformation> wys = new ArrayList<>();
//            mx1.forEach(y -> {
//                WysmxInformation wysmxInformation = new WysmxInformation();
//                wysmxInformation.setYsmc(y.getName());
//                wysmxInformation.setZdname(y.getJtzb());
//                wysmxInformation.setXmId(x.getId());
//                wys.add(wysmxInformation);
//            });
//            wysmxInformationService.saveBatch(wys);
//        });W
//    }

    @ApiOperation(value = "导出单片材料")
    @PostMapping("/wordExport")
    public void wordExport(HttpServletResponse response, @RequestParam String ids) throws Exception {
        List<SysDictData> sysDictData = sysDictDataMapper.selectDictDataList(new SysDictData());
        String fatherFile = fileAddress + "/项目压缩文件";
        FileUtil.mkdir(fatherFile);
        for (String id : ids.split(",")) {
            BasicInformationResponse a1 = basicInformationService.selectOne(Long.valueOf(id));
            Map<String, Object> map = new HashMap<>();
            map.put("issuingTime", a1.getBasicInformation().getIssuingTime() != null ? a1.getBasicInformation().getIssuingTime() : "/");
            map.put("jsjd", a1.getBasicInformation().getJsjd() != null ? a1.getBasicInformation().getJsjd() : "/");
            map.put("xzfl", a1.getBasicInformation().getXzfl() != null ?
                    basicInformationService.getDictLabel("xzfl", String.valueOf(a1.getBasicInformation().getXzfl()), sysDictData) : "/");
            map.put("nature", a1.getBasicInformation().getNature() != null ?
                    basicInformationService.getDictLabel("xmfrdwxz", String.valueOf(a1.getBasicInformation().getNature()), sysDictData) : "/");
            map.put("name", a1.getBasicInformation().getName() != null ? a1.getBasicInformation().getName() : "/");
            map.put("ssgnq", a1.getBasicInformation().getSsgnq() != null ?
                    basicInformationService.getDictLabel("ssgnq", String.valueOf(a1.getBasicInformation().getSsgnq()), sysDictData) : "/");
            map.put("jsdd", a1.getBasicInformation().getJsdd() != null ? a1.getBasicInformation().getJsdd() : "/");
            map.put("xmfrdwxz", a1.getBasicInformation().getXmfrdwxz() != null ? a1.getBasicInformation().getXmfrdwxz() : "/");
            map.put("tyshxydm", a1.getBasicInformation().getTyshxydm() != null ? a1.getBasicInformation().getTyshxydm() : "/");
            map.put("sgdw", a1.getBasicInformation().getSgdw() != null ? a1.getBasicInformation().getSgdw() : "/");
            map.put("sjdw", a1.getBasicInformation().getSjdw() != null ? a1.getBasicInformation().getSjdw() : "/");
            map.put("begainTime", a1.getBasicInformation().getBegainTime() != null ? a1.getBasicInformation().getBegainTime() : "/");
            map.put("endTime", a1.getBasicInformation().getEndTime() != null ? a1.getBasicInformation().getEndTime() : "/");
            map.put("prioritize", a1.getBasicInformation().getPrioritize() != null ? a1.getBasicInformation().getPrioritize() : "/");
            map.put("label", a1.getBasicInformation().getLabel() != null ? a1.getBasicInformation().getLabel() : "/");
            map.put("projectLeader", a1.getBasicInformation().getProjectLeader() != null ? a1.getBasicInformation().getProjectLeader() : "/");
            map.put("phone", a1.getBasicInformation().getPhone() != null ? a1.getBasicInformation().getPhone() : "/");
            map.put("zydmj", a1.getPlanInformation().getZydmj() != null ? a1.getPlanInformation().getZydmj() : "/");
            map.put("rjl", a1.getPlanInformation().getRjl() != null ? a1.getPlanInformation().getRjl() : "/");
            map.put("zjzmj", a1.getPlanInformation().getZjzmj() != null ? a1.getPlanInformation().getZjzmj() : "/");
            map.put("jzds", a1.getPlanInformation().getJzds() != null ? a1.getPlanInformation().getJzds() : "/");
            map.put("bzcjzmj", a1.getPlanInformation().getBzcjzmj() != null ? a1.getPlanInformation().getBzcjzmj() : "/");
            map.put("jzmd", a1.getPlanInformation().getJzmd() != null ? a1.getPlanInformation().getJzmd() : "/");
            map.put("zgjzcs", a1.getPlanInformation().getZgjzcs() != null ? a1.getPlanInformation().getZgjzcs() : "/");
            map.put("zgjzgd", a1.getPlanInformation().getZgjzgd() != null ? a1.getPlanInformation().getZgjzgd() : "/");
            map.put("fhdj", a1.getPlanInformation().getFhdj() != null ? a1.getPlanInformation().getFhdj() : "/");
            map.put("jdctcw", a1.getPlanInformation().getJdctcw() != null ? a1.getPlanInformation().getJdctcw() : "/");
            map.put("fjdctcw", a1.getPlanInformation().getFjdctcw() != null ? a1.getPlanInformation().getFjdctcw() : "/");
            map.put("jhtze", a1.getBasicInformation().getJhtze() != null ? a1.getBasicInformation().getJhtze() : "/");
            map.put("ztze", a1.getBasicInformation().getZtze() != null ? a1.getBasicInformation().getZtze() : "/");

            map.put("rzqys", a1.getQyrzInformation().getRzqys() != null ? a1.getQyrzInformation().getRzqys() : "/");
            map.put("rzqyhylx", a1.getQyrzInformation().getRzqyhylx() != null ? a1.getQyrzInformation().getRzqyhylx() : "/");
            map.put("rysl", a1.getQyrzInformation().getRysl() != null ? a1.getQyrzInformation().getRysl() : "/");
            map.put("rzl", a1.getQyrzInformation().getRzl() != null ? a1.getQyrzInformation().getRzl() : "/");
            map.put("yczmj", a1.getQyrzInformation().getYczmj() != null ? a1.getQyrzInformation().getYczmj() : "/");
            map.put("kzczmj", a1.getQyrzInformation().getKzczmj() != null ? a1.getQyrzInformation().getKzczmj() : "/");
            map.put("gycfpjzj", a1.getQyrzInformation().getGycfpjzj() != null ? a1.getQyrzInformation().getGycfpjzj() : "/");
            try {
                String itemsFileName = fatherFile + "/" + a1.getBasicInformation().getName() + ".docx";
                Path targetPath = Paths.get(itemsFileName);
                Files.createDirectories(targetPath.getParent());
                // 2. 打开输出流（自动覆盖已有文件）
                try (OutputStream out = new BufferedOutputStream(
                        Files.newOutputStream(targetPath,
                                StandardOpenOption.CREATE,
                                StandardOpenOption.TRUNCATE_EXISTING))) {
                    basicInformationService.generateDocument(map, "xmdtcl.docx", out);
                }
            } catch (Exception e) {
                throw new RuntimeException("文件下载失败");
            }
        }
        // 压缩后的文件路径
        String zipFilePath = fatherFile + ".zip";
        ZipUtil.zip(fatherFile, zipFilePath);
        File file = new File(zipFilePath);// 创建File对象
        response.setContentType("application/zip");// 设置内容类型为ZIP文件
        response.setHeader("Content-Disposition", "attachment; filename=\"file.zip\"");//设置文件名
        try (FileInputStream fileInputStream = new FileInputStream(file);
             OutputStream outputStream = response.getOutputStream()) {
            byte[] buffer = new byte[4096];
            int by;
            while ((by = fileInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, by);
            }
        }
        FileUtil.del(zipFilePath);
        FileUtil.del(fatherFile);
    }
}

