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

import SvgIcon from '@/components/SvgIcon.vue';
import { useRequest } from '@/hooks/request';
import { t } from '@/i18n';
import { deleteProtocolBaseInfo, downloadProtocolTemplate, getDictTypeData } from '@/api';
import { downloadBlob } from '@/utils';
import { DictCode, ProtocolType } from '@/constants';

import type { SetupProtocolForm, UseGuideStepItemProps } from '@/types';

const props = defineProps<UseGuideStepItemProps<SetupProtocolForm>>();

const { handleRequest } = useRequest();
let fileName: string | undefined;

onMounted(async () => {
  const { id } = props.form.protocolInfo;

  Object.assign(props.form.protocolInfo, {
    id: undefined,
    protocolName: '',
    protocolType: undefined,
    deviceType: undefined,
    deviceTypeId: undefined,
    dataBit: 5,
    parityBit: 'N',
    stopBit: '1',
    baudRate: undefined,
    dataSendInterval: undefined,
    highFreqSendInterval: undefined,
    readTimeout: undefined,
    nextDataReadDelay: undefined,
    nextRoundDataReadDelay: undefined,
    readContinuousAddr: '关',
    readContinuousAddrCode: 0,
    readContinuousAddrLength: undefined,
    byteOrder: undefined,
    byteOrderCode: undefined,
    addrOrder: undefined,
    addrOrderCode: undefined,
  });

  // 协议 id 存在时删除草稿协议
  try {
    if (id) {
      await deleteProtocolBaseInfo(id);
    }
  } catch (err) {
    console.log(err);
  }

  handleRequest(async () => {
    const data = await getDictTypeData({
      dictCode: DictCode.ProtocolTemplateFileName,
    });

    if (data.length) {
      const { protocolType } = props.form;
      const fileNameList = data[0].dictTypeDataList.map((item) => item.dictValue);

      if (protocolType?.includes(ProtocolType.ModbusRTU)) {
        fileName = fileNameList.find((item) => item.includes(ProtocolType.ModbusRTU));
      } else if (protocolType?.includes(ProtocolType.ModbusTCP)) {
        fileName = fileNameList.find((item) => item.includes(ProtocolType.ModbusTCP));
      } else if (protocolType?.includes(ProtocolType.S7)) {
        fileName = fileNameList.find((item) => item.includes(ProtocolType.S7));
      }
    }
  });
});

const downloadTemplate = () => {
  handleRequest(async () => {
    if (!fileName) {
      throw new Error(t('setupProtocol.canNotDownloadByEmptyFileName'));
    }

    const file = await downloadProtocolTemplate(fileName);
    downloadBlob(file, fileName);
    message.success(t('setupProtocol.downloadTemplateSuccessful', { name: fileName }));
  });
};
</script>

<template>
  <div>
    <div class="upload-step-text">1. {{ $t('setupProtocol.clickToDownloadTemplate') }}</div>
    <AButton class="icon-button upload-template-button" type="primary" @click="downloadTemplate">
      <SvgIcon name="download" />
      {{ $t('setupProtocol.downloadTemplate') }}
    </AButton>
    <div class="upload-step-text">2. {{ $t('setupProtocol.clickToUpload') }}</div>
    <AFormItem class="upload-drag-area" name="protocolFile">
      <AUploadDragger
        v-model:file-list="form.protocolFile"
        :max-count="1"
        :multiple="false"
        :before-upload="() => false"
      >
        <img class="upload-folder-icon" src="@/assets/img/folder.png" />
        <div class="ant-upload-text">{{ $t('setupProtocol.uploadFileTip') }}</div>
        <div class="ant-upload-hint">{{ $t('setupProtocol.uploadFileFormat') }}</div>
      </AUploadDragger>
    </AFormItem>
  </div>
</template>

<style lang="scss" scoped>
.upload-step-text {
  margin-bottom: 16px;
  font-size: 14px;
  line-height: 22px;
  color: #333;
}

.upload-template-button {
  height: 40px;
  margin-bottom: 40px;
}

.upload-drag-area {
  width: 100%;
  max-width: 468px;

  :deep(.ant-upload-drag) {
    height: 176px;
    background-color: #f5f7fa;
    border-color: #dcdfe6;

    .ant-upload {
      padding: 40px 0;
    }

    .ant-upload-text {
      font-size: 14px;
      font-weight: 500;
      line-height: 24px;
      color: #333;
    }

    .ant-upload-hint {
      font-size: 12px;
      font-weight: 500;
      line-height: 24px;
      color: #666;
    }
  }
}

.upload-folder-icon {
  margin-bottom: 8px;
}
</style>
