<template>
  <table-pro-max
      ref="tableRef"
      :request-api="reqApi"
      :is-pagination="false"
      :columns="columns"
  >
    <template #tableHeader>
      <a-space>
        <a-button class="btn-success" @click="saveOrUpdateAccessKey({
            name: '',
            effectiveTime: 300000,
            isEnable:0
            })">添加accessKey
        </a-button>
        <a-button @click="a">a</a-button>
      </a-space>
    </template>
  </table-pro-max>
</template>

<script setup lang="tsx">
import {message} from "ant-design-vue";
import api from "@/axios";
import {onMounted, ref} from "vue";
import {submitSimpleFormModal} from "@/components/tsx/ModalPro.tsx";
import {dictSelectNodes} from "@/config/dict.ts";
import TableProMax from "@/components/table/TableProMax.vue";
import {TableProMaxProps} from "@/types/components/table";
import {AccessKeyRes, GeneratedAccessKeyParams} from "@/types/views/openPlatform/openPlatform.ts";
import {ComponentExposed} from "vue-component-type-helpers";
import axios from "axios";
import {md5} from "js-md5";

type TableProps = TableProMaxProps<AccessKeyRes>

const tableRef = ref<ComponentExposed<typeof TableProMax>>(null)
const columns: TableProps['columns'] = [
  {
    dataIndex: 'name',
    title: '调用方'
  }, {
    dataIndex: 'accessKey',
    title: 'accessKey'
  }, {
    dataIndex: 'secretKey',
    title: 'secretKey'
  }, {
    dataIndex: 'effectiveTime',
    title: '有效时间(ms)'
  }, {
    dataIndex: 'isEnable',
    title: '状态',
    customRender: ({text}) => <a-tag color={text.extData?.color}>{text.label}</a-tag>
  }, {
    dataIndex: 'remark',
    title: '备注',
  }, {
    dataIndex: 'createTime',
    title: '创建时间'
  }, {
    dataIndex: 'opt',
    title: '操作',
    customRender: ({record}) => {
      return <a-space>
        <a-button class="btn-warn" onClick={() => saveOrUpdateAccessKey({
          snowFlakeId: record.snowFlakeId,
          name: record.name,
          effectiveTime: record.effectiveTime,
          isEnable: record.isEnable.value,
          allowedResources: record.allowedResources,
          remark: record.remark
        })}>编辑
        </a-button>

      </a-space>
    }
  }
]

const reqApi: TableProps["requestApi"] = () => api.get('/accessKeys/tableList')

const saveOrUpdateAccessKey = (params: GeneratedAccessKeyParams) => {
  submitSimpleFormModal<GeneratedAccessKeyParams>({
    title: '',
    formOptions: {
      name: {
        type: 'input',
        label: '调用方',
        required: true
      },
      effectiveTime: {
        type: 'inputNumber',
        label: '有效时间(ms)',
        required: true,
        componentsProps: {
          precision: 0
        }
      },
      allowedResources: {
        type: 'select',
        label: '可访问资源',
        options: allowedResources.value,
        componentsProps: {
          mode: 'multiple'
        }
      },
      isEnable: {
        type: "radioGroup",
        label: '是否启用',
        options: dictSelectNodes("IsEnable")
      },
      remark: {
        type: 'inputTextArea',
        label: '备注'
      }
    },
    formParams: {...params},
    submit: async (p) => {
      const resp = await api.post('/accessKeys/generatedAccessKey', p, {loading: true})
      message.success(resp.message)
      await tableRef.value?.requestGetTableData()
    }
  })
}

const a = () => {
  const accessKey = "w2wzi0wefmmo6s735z2el8tfzitya5gj"
  const secretKey = "db1b5214-02ee-497f-957c-88323b4351bf"
  const now = Date.now()
  const paramsMap = new Map();
  paramsMap.set('name', 'zhangsan')
  paramsMap.set('age', 14)
  paramsMap.set('addr', '湖南省长沙市')
  paramsMap.set('access-key', accessKey)
  paramsMap.set('time-stamp', now)

  // 将 Map 转换为数组并排序
  const entries = Array.from(paramsMap.entries());
  entries.sort((a, b) => a[0].localeCompare(b[0]));
  // 拼接成 URL 编码的字符串
  let encodedParams = entries.map(([key, value]) => `${key}=${encodeURIComponent(value).replace(/%([0-9A-Fa-f]{2})/g, function (_, p1) {
    return '%' + p1.toUpperCase();
  })}`).join('&');
  encodedParams = encodedParams + "&secret-key=" + secretKey
  console.log(encodedParams);

  const sign = md5(encodedParams).toUpperCase()
  console.log(sign);

  const headers = {
    'access-key': accessKey,
    'time-stamp': now,
    'sign': sign
  }
  console.log(headers);

  api.get('/open/dataView', null, {
    headers
  })

}

const allowedResources = ref<SelectNodeVo<string>[]>([])

onMounted(() => {
  api.get<SelectNodeVo<string>[]>('/accessKeys/listOpenApi').then(resp => {
    allowedResources.value = resp.data
  })
})

</script>

<style scoped lang="scss">

</style>
