<template>
  <div>
    <BasicModal
      :maskClosable="false"
      v-bind="$attrs"
      :width="dynamicWidth"
      @register="register"
      @ok="handleSubmit"
      @cancel="handleCancel"
    >
      <div v-if="!isViewDetail" class="step-form-form">
        <a-steps :current="current">
          <a-step v-for="item in steps" :key="item.title" :title="item.title" />
        </a-steps>
      </div>
      <div v-if="!isViewDetail" class="mt-5">
        <DeviceConfigurationStep
          v-show="current === 0"
          ref="DevConStRef"
          @next="handleStepNext(true, null)"
        />
        <TransportConfigurationStep
          v-show="current === 1"
          ref="TransConStRef"
          @prev="handleStepPrev"
        />
      </div>
      <div v-if="isViewDetail">
        <Tabs
          type="card"
          :animated="true"
          v-model:activeKey="activeKey"
          :size="size"
          @change="handleChange"
        >
          <TabPane forceRender key="1" tab="产品">
            <div class="relative">
              <DeviceConfigurationStep
                :ifShowBtn="isViewDetail ? false : true"
                v-show="activeKey === '1'"
                ref="DevConStRef"
              />
              <div
                v-show="isViewDetail"
                class="absolute w-full h-full top-0 cursor-not-allowed"
              ></div>
            </div>
          </TabPane>
          <TabPane forceRender key="2" tab="传输配置">
            <div class="relative">
              <TransportConfigurationStep
                :ifShowBtn="isViewDetail ? false : true"
                v-show="activeKey === '2'"
                ref="TransConStRef"
              />
              <div
                v-show="isViewDetail"
                class="absolute w-full h-full top-0 cursor-not-allowed"
              ></div>
            </div>
          </TabPane>
          <TabPane forceRender key="3" v-show="activeKey === '3'" tab="物模型管理">
            <PhysicalModelManagementStep v-show="activeKey === '3'" ref="PhysicalModManRef" />
          </TabPane>
        </Tabs>
      </div>
    </BasicModal>
  </div>
</template>
<script lang="ts" setup>
  import { ref, unref, reactive } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { deviceConfigAddOrEdit, deviceConfigGetDetail } from '/@/api/device/deviceConfigApi';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { steps } from './device.profile.data';
  import { isEmpty } from '/@/utils/is';
  import { Tabs, TabPane } from 'ant-design-vue';
  import DeviceConfigurationStep from './step/DeviceConfigurationStep.vue';
  import TransportConfigurationStep from './step/TransportConfigurationStep.vue';
  import PhysicalModelManagementStep from './step/PhysicalModelManagementStep.vue';

  const emits = defineEmits(['success', 'register']);
  const activeKey = ref('1');
  const size = ref('small');
  const isEditId = ref('');
  const isEditCreatTime = ref('');
  const { createMessage } = useMessage();
  const isViewDetail = ref(false);
  const isUpdate = ref(false);
  const current = ref(0);
  const DevConStRef = ref<InstanceType<typeof DeviceConfigurationStep>>();
  const TransConStRef = ref<InstanceType<typeof TransportConfigurationStep>>();
  const PhysicalModManRef = ref<InstanceType<typeof PhysicalModelManagementStep>>();
  const postSubmitFormData: any = reactive({
    deviceConfData: {},
  });
  const transportConfData: any = reactive({
    profileData: {},
  });
  const transportTypeStr = ref('');
  const dynamicWidth = ref('55rem');
  const [register, { closeModal, setModalProps }] = useModalInner(async (data) => {
    setModalProps({ confirmLoading: false });
    current.value = 0;
    isUpdate.value = data.isUpdate;
    isViewDetail.value = data.isView;
    const res = data.record !== undefined ? await deviceConfigGetDetail(data.record.id) : {};
    isEditId.value = data.record !== undefined ? data.record.id : null;
    isEditCreatTime.value = data.record !== undefined ? data.record.createTime : null;

    const title = unref(isUpdate) ? '编辑产品' : '新增产品';
    setModalProps({ title, showOkBtn: true, showCancelBtn: true });
    if (unref(isUpdate)) {
      await setDeviceConfEditFormData(res);
      await setTransConfEditFormData(res);
      handleStepNext(false, res);
      unref(DevConStRef)?.editOrAddDeviceTypeStatus(true);
    } else {
      unref(DevConStRef)?.editOrAddDeviceTypeStatus(false);
    }
  });
  const handleChange = (e) => {
    if (e == '2') {
      handleStepNext(true, null);
    }
  };
  const handleStepNext = (e, data) => {
    if (e) {
      current.value++;
      unref(isUpdate)
        ? unref(TransConStRef)?.editOrAddTransportTypeStatus(true)
        : unref(TransConStRef)?.editOrAddTransportTypeStatus(false);
    } else {
      setTransConfEditFormData(data);
    }
  };
  const handleStepPrev = () => {
    current.value--;
  };

  const setDeviceConfEditFormData = async (res) => {
    await DevConStRef.value?.setFormData(res);
  };
  const setTransConfEditFormData = async (res) => {
    await TransConStRef.value?.setFormData(res);
  };

  const getDeviceConfFormData = async () => {
    postSubmitFormData.deviceConfData = await DevConStRef.value?.getFormData();
  };
  const getTransConfData = async () => {
    transportConfData.profileData = await TransConStRef.value?.getFormData();
    transportTypeStr.value = transportConfData.profileData.transportConfiguration.type;
    Reflect.deleteProperty(transportConfData.profileData?.transportConfiguration, 'transportType');
  };

  const handleSubmit = async () => {
    await getDeviceConfFormData();
    await getTransConfData();
    const isEmptyObj = isEmpty(transportConfData.profileData.transportConfiguration);
    await deviceConfigAddOrEdit({
      ...postSubmitFormData.deviceConfData,
      ...{ transportType: !isEmptyObj ? transportTypeStr.value : 'DEFAULT' },
      ...{ profileData: !isEmptyObj ? transportConfData.profileData : null },
      ...{ id: isUpdate.value ? isEditId.value : null },
      ...{ createTime: isUpdate.value ? isEditCreatTime.value : null },
    });
    createMessage.success(isUpdate.value ? `编辑成功` : `新增成功`);
    handleCancel();
    emits('success');
  };

  const handleCancel = () => {
    closeModal();
    activeKey.value = '1';
    DevConStRef.value?.resetFormData();
    TransConStRef.value?.resetFormData();
  };
</script>

<style lang="less" scope>
  :deep(.ant-modal-content) {
    height: 700px !important;
  }
</style>
