package com.ruoyi.gysl.controller;


import cn.hutool.crypto.SmUtil;
import com.alibaba.fastjson2.JSONArray;
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.exception.ServiceException;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.gysl.entity.Cybq;
import com.ruoyi.gysl.entity.request.CybqRequest;
import com.ruoyi.gysl.login.util.SM2Demo;
import com.ruoyi.gysl.login.util.SM4Demo;
import com.ruoyi.gysl.service.CybqService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
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.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

/**
 * 产业标签(GyslCybq)表控制层
 *
 * @author makejava
 * @since 2025-04-02 11:02:34
 */
@Api(tags = "产业标签")
@RestController
@RequestMapping("/gysl/Cybq")
public class CybqController extends BaseController {
    /**
     * 服务对象
     */
    @Resource
    private CybqService cybqService;


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

    /**
     * 企业经济标签信息(统一社会信用代码)
     */
    @ApiOperation("企业经济标签信息(统一社会信用代码)")
    @GetMapping("/getCybq")
    public AjaxResult getCybq() throws Exception {
        if (isZs) {
            String contacts = "http://172.21.10.46/api/invoke/323018/qyjjbqxx";
            String uscc = Base64.getEncoder().encodeToString((byte[])
                    SM4Demo.exec("91320594067622605M".getBytes(),
                            "ECB", "PKCS5Padding", "random", "ef5323158e0d43e69442718cd4932116".getBytes(), null));
            String pageIndex = Base64.getEncoder().encodeToString((byte[])
                    SM4Demo.exec("1".getBytes(),
                            "ECB", "PKCS5Padding", "random", "ef5323158e0d43e69442718cd4932116".getBytes(), null));
            //生成sm3签名
            String input = "pageIndex=1&uscc=91320594067622605M";
            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())) {
                    // 参数 uscc
                    writeFormField(out, "uscc", uscc);
                    // 参数 pageIndex
                    writeFormField(out, "pageIndex", pageIndex);
                    // 结束标记
                    out.writeBytes("--" + BOUNDARY + "--\r\n");
                }
                // 4. 处理响应
                int statusCode = conn.getResponseCode();
                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);
                    }
                }
                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("MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgefIcY79Be48T8ryF9tMOKDFZ4XmeB9JzBSmEZHGmvhKhRANCAAQmjPisOvJfv2r7mpj06FszOkAlJiyVL6OoefMmXmqSANNqyT8ZxnFpnToYgtqjQqX44IG8fXk49eLjKXQSfJ2J")), StandardCharsets.UTF_8);
                        // 解析解密后的 JSON
                        JSONObject getAllData = JSONObject.parseObject(s);
                        // 提取 data 字段为 JSONArray
                        JSONArray js1 = getAllData.getJSONArray("data");
                        // 转换为 Java 对象列表
                        List<Cybq> returnData = new ArrayList<>();
                        for (int i = 0; i < js1.size(); i++) {
                            JSONObject item = js1.getJSONObject(i);
                            Cybq res = item.toJavaObject(Cybq.class);
                            returnData.add(res);
                        }
                        return AjaxResult.success(returnData);
                    }
                }
            } catch (Exception y) {
                y.printStackTrace();
            }
        }
        return success();
    }

    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 gyslCybq 查询实体
     * @return 所有数据
     */
    @ApiOperation("分页查询所有数据")
    @GetMapping("/page")
    public AjaxResult selectAll(Page<Cybq> page, CybqRequest gyslCybq) {
        return success(cybqService.page(page, gyslCybq));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "通过主键查询单条数据", response = Cybq.class)
    public AjaxResult selectOne(@PathVariable Serializable id) {
        return success(cybqService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param gyslCybq 实体对象
     * @return 新增结果
     */
    @PostMapping("/add")
    @ApiOperation("新增数据")
    public AjaxResult insert(@RequestBody Cybq gyslCybq) {
        return success(cybqService.save(gyslCybq));
    }

    /**
     * 修改数据
     *
     * @param gyslCybq 实体对象
     * @return 修改结果
     */
    @PostMapping("/edit")
    @ApiOperation("修改数据")
    public AjaxResult update(@RequestBody Cybq gyslCybq) {
        return success(cybqService.updateById(gyslCybq));
    }

    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @ApiOperation("删除数据")
    @DeleteMapping("/delete")
    public AjaxResult delete(@RequestParam("idList") List<Long> idList) {
        return success(cybqService.removeByIds(idList));
    }

    /**
     * 产业标签批量导入
     */
    @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<Cybq> util = new ExcelUtil<>(Cybq.class);
        List<Cybq> proList = util.importExcel(file.getInputStream());
        StringBuilder successMsg = new StringBuilder();
        if (proList == null || proList.isEmpty()) {
            throw new ServiceException("产业标签导入数据不能为空");
        } else {
            cybqService.saveBatch(proList);
            successMsg.append("导入成功");
        }
        return AjaxResult.success(successMsg);
    }

    /**
     * 根据条件导出所有产业标签
     */
    @ApiOperation(value = "根据条件导出所有产业标签")
    @PostMapping(value = "/export")
    public void exportMl(HttpServletResponse response, CybqRequest req) {
        List<Cybq> filteredList = cybqService.page(req);
        ExcelUtil<Cybq> util = new ExcelUtil<>(Cybq.class);
        util.exportExcel(response, filteredList, "产业标签");
    }
}

