<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 {md5} from "js-md5";
import axios from "axios";

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 params = {
    id: "1855852231820054528",
    type: 'ENTERPRISES_UNIT'
  }
  const sign = generatedSign(params, now, accessKey, secretKey)
  const headers2 = {
    'Access-Key': accessKey,
    'Time-Stamp': now,
    'Sign': sign
  }
  console.log(headers2);
  axios.get('http://127.0.0.1:8765/open/dataView', {
    params: params,
    headers: {
      ...headers2
    }
  })


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

}

/**
 * 生成签名
 * @param params 参数
 * @param timeStamp 时间戳
 * @param accessKey
 * @param secretKey
 */
const generatedSign = (params: Record<string, any>,
                       timeStamp: number,
                       accessKey: string,
                       secretKey: string): string => {
  const paramsMap = new Map<string, any>();
  if (params) {
    for (let paramsKey in params) {
      paramsMap.set(paramsKey, params[paramsKey])
    }
  }
  paramsMap.set('Access-Key', accessKey)
  paramsMap.set('Time-Stamp', timeStamp)
  // 将 Map 转换为数组并排序
  const entries = Array.from(paramsMap.entries());
  // 拼接成 URL 编码的字符串
  const encodedParams = entries
      .filter(([_, value]) => value !== null && value !== undefined && value !== '')
      .sort((a, b) => a[0].localeCompare(b[0], undefined, {sensitivity: 'base', caseFirst: 'upper'}))
      .map(([key, value]) => `${key}=${encodeURIComponent(value).replace(/%([0-9A-Fa-f]{2})/g, (_, p1) => '%' + p1.toUpperCase())}`)
      .join('&') + "&Secret-Key=" + secretKey;
  return md5(encodedParams).toUpperCase();
}

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

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

</script>

<style scoped lang="scss">

</style>
