<script lang="ts" setup>
import type { UploadChangeParam } from 'ant-design-vue';

import type { LicenseApi } from '#/api/license/license';

import { h } from 'vue';

import { downloadFileFromBlobPart } from '@vben/utils';

import { Button, message, UploadDragger } from 'ant-design-vue';

import { updateLicenseDetail } from '#/api/license/license';
import { useDescription } from '#/components/description';
import { DictTagGroup } from '#/components/dict-tag';
import { useUpload } from '#/components/upload/use-upload';
import { $t } from '#/locales';
import { DICT_TYPE } from '#/utils';

import { useDetailSchema } from '../data';

const props = defineProps<{
  formData?: LicenseApi.License;
}>();

const emit = defineEmits(['getDetailById']);

const columns = [
  {
    title: '网元',
    dataIndex: 'neListMap',
    key: 'neListMap',
    customRender: (data: any) => {
      if (!data.value.old) {
        data.value.old = [];
      }
      if (!data.value.new) {
        data.value.new = [];
      }
      const oldDict = h(DictTagGroup, {
        type: [
          DICT_TYPE.LIC_NE_ALL,
          DICT_TYPE.LIC_NE_5G,
          DICT_TYPE.LIC_NE_4G,
          DICT_TYPE.LIC_NE_23G,
          DICT_TYPE.LIC_NE_ADD,
        ],
        value: data.value.old,
      });
      function arrayEquals(arr1: any[], arr2: any[]) {
        if (arr1.length !== arr2.length) {
          return false;
        }
        return arr1.some((item) => arr2.includes(item));
      }
      if (!arrayEquals(data.value.old, data.value.new)) {
        const newDict = data.value.new
          ? h(DictTagGroup, {
              type: [
                DICT_TYPE.LIC_NE_ALL,
                DICT_TYPE.LIC_NE_5G,
                DICT_TYPE.LIC_NE_4G,
                DICT_TYPE.LIC_NE_23G,
                DICT_TYPE.LIC_NE_ADD,
              ],
              color: 'red',
              value: data.value.new,
            })
          : '';
        const after = h(
          'span',
          {
            style: {
              color: 'red',
            },
          },
          [` → `, newDict],
        );
        return h('div', {}, [oldDict, after]);
      }
      return oldDict;
    },
  },
  {
    title: '激活码',
    dataIndex: 'activationCodeMap',
    key: 'activationCodeMap',
    customRender: (data: any) => {
      if (!data.value.new) {
        data.value.new = '';
      }
      if (data.value.old !== data.value.new) {
        const after = h(
          'span',
          {
            style: {
              color: 'red',
            },
          },
          ` ${data.value.new ? '→' : ''} ${data.value.new}`,
        );
        return h('div', {}, [data.value.old, after]);
      }
      return data.value.old;
    },
  },
  {
    title: 'License文件',
    dataIndex: 'fileUrlListMap',
    key: 'fileUrlListMap',
  },
];

const [Description] = useDescription({
  componentProps: {
    bordered: true,
    column: 1,
    class: 'mx-4',
  },
  schema: useDetailSchema(),
});

const handleDownload = async (item: string) => {
  const res = await fetch(item);
  if (!res.ok) {
    message.error($t('license.downloadFailed'));
    return;
  }
  const blob1 = await res.blob();

  downloadFileFromBlobPart({
    fileName: `${item?.slice(
      Math.max(0, item.lastIndexOf('/') + 1),
      item.lastIndexOf('_'),
    )}.ini`,
    source: blob1,
  });
};

/** 上传前 */
function beforeUpload() {
  return false;
}

const handleChange = (info: UploadChangeParam, record: any) => {
  record.fileList = info.fileList;
};

const handleUpload = async (record: any) => {
  try {
    // 1. 上传，获取 URL
    record.uploading = true;
    for (const item of record.fileList) {
      const { httpRequest } = useUpload();
      // 将 Blob 转换为 File
      const fileObj = new File([item.originFileObj], item.name, {
        type: item.type,
      });
      const fileUrl = await httpRequest(fileObj);

      await updateLicenseDetail({
        id: record.id,
        neList: [],
        activationCode: '',
        fileUrl,
      });
    }

    emit('getDetailById', props.formData?.id || 0);
    message.success('上传成功');
  } catch {
    message.error($t('上传失败'));
  }
  record.fileList = [];
  record.uploading = false;
};
</script>

<template>
  <div class="flex-1 overflow-auto py-4">
    <Description :data="props.formData" :label-style="{ width: '15%' }" />
    <div class="mt-3">
      <a-table
        :data-source="props.formData?.neCodeList"
        :columns="columns"
        bordered
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'fileUrlListMap'">
            <template
              v-if="
                record.fileUrlListMap.old &&
                record.fileUrlListMap.old.length > 0
              "
            >
              <div
                v-for="(item, index) in record.fileUrlListMap.old"
                :key="index"
                style="display: flex; align-items: center; margin-top: 8px"
              >
                <span style="margin-right: 15px">{{
                  `${item?.slice(
                    Math.max(0, item.lastIndexOf('/') + 1),
                    item.lastIndexOf('_'),
                  )}.ini`
                }}</span>
                <Button @click="handleDownload(item)" type="primary">
                  {{ $t('license.download') }}
                </Button>
              </div>
            </template>
            <template
              v-else-if="
                props.formData?.status === 3 &&
                props.formData?.showUpload &&
                false
              "
            >
              <div
                style="
                  display: flex;
                  flex-direction: column;
                  align-items: center;
                  justify-content: center;
                "
              >
                <div class="w-full">
                  <UploadDragger
                    accept=".ini"
                    :max-count="2"
                    :file-list="record.fileList"
                    :before-upload="beforeUpload"
                    @change="handleChange($event, record)"
                  >
                    <p class="ant-upload-drag-icon">
                      <span class="icon-[ep--upload-filled] size-12"></span>
                    </p>

                    <p class="ant-upload-text">选择要导入的License文件</p>
                  </UploadDragger>
                </div>
                <Button
                  style="margin-top: 5px"
                  :disabled="!record.fileList || record.fileList.length === 0"
                  :loading="record.uploading"
                  @click="handleUpload(record)"
                  type="primary"
                >
                  确定导入
                </Button>
              </div>
            </template>
          </template>
        </template>
      </a-table>
    </div>
  </div>
</template>
