<script setup lang="ts">
import { onMounted, ref } from 'vue';

import { useRequest } from '@/hooks/request';
import { t } from '@/i18n';
import { addTempProtocol, deleteProtocolBaseInfo, groupList } from '@/api';

import type { DefaultOptionType, SelectValue } from 'ant-design-vue/es/select';
import type { EquipmentTypeItem, SetupProtocolForm, UseGuideStepItemExpose, UseGuideStepItemProps } from '@/types';

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

const { handleRequest } = useRequest();
const deviceTypes = ref<EquipmentTypeItem[]>([]);
const currentStep = props.steps[props.stepIndex];

onMounted(async () => {
  const { id } = props.form.protocolInfo;
  currentStep.title = t('setupProtocol.selectDeviceType');
  props.form.deviceType = undefined;

  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 () => {
    deviceTypes.value = await groupList({
      dataType: 1,
    });
  });
});

let deviceTypeId: number;

const handleDeviceTypeChange = (_value: SelectValue, option: DefaultOptionType) => {
  deviceTypeId = option.key;
};

const finish = async () => {
  const { protocolType, deviceType, protocolInfo } = props.form;
  currentStep.title = deviceType as string;
  protocolInfo.protocolType = protocolType;
  protocolInfo.deviceType = deviceType;
  protocolInfo.deviceTypeId = deviceTypeId;

  protocolInfo.id = await addTempProtocol({
    protocolType,
    deviceType,
    deviceTypeId,
  });
};

defineExpose<UseGuideStepItemExpose>({
  finish,
});
</script>

<template>
  <div>
    <AFormItem :label="$t('setupProtocol.deviceType')" name="deviceType">
      <ASelect
        v-model:value="form.deviceType"
        class="device-select"
        :placeholder="$t('common.plzSelect')"
        @change="handleDeviceTypeChange"
      >
        <ASelectOption v-for="item in deviceTypes" :key="item.id" :value="item.dataName">
          {{ item.dataName }}
        </ASelectOption>
      </ASelect>
    </AFormItem>
  </div>
</template>

<style lang="scss" scoped>
.device-select {
  width: 256px;
}
</style>
