<template>
  <BasicModal
    v-bind="$attrs"
    width="50rem"
    :title="getTitle"
    @register="register"
    @cancel="handleCancel"
    @ok="handleOk"
    destroyOnClose
    centered
  >
    <div class="step-form-form">
      <Steps :current="current" v-if="!isUpdate">
        <Step title="填写设备信息" />
        <Step title="添加设备凭证" />
      </Steps>
    </div>
    <div class="mt-4">
      <DeviceStep1
        @next="handleStep1Next"
        ref="DeviceStep1Ref"
        v-show="current === 0"
        :isUpdate="!isUpdate"
      />
      <DeviceStep2
        ref="DeviceStep2Ref"
        @prev="handleStepPrev"
        @next="handleStep2Next"
        v-show="current === 1"
        v-if="!isUpdate"
      />
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { createOrEditDevice } from '/@/api/device/deviceManager';
  import DeviceStep1 from '../step/DeviceStep1.vue';
  import DeviceStep2 from '../step/DeviceStep2.vue';
  import { Steps } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { credentialTypeEnum } from '../../config/data';

  export default defineComponent({
    name: 'DeviceModal',
    components: {
      BasicModal,
      DeviceStep1,
      DeviceStep2,
      Steps,
      Step: Steps.Step,
    },
    props: {
      userData: { type: Object },
    },
    emits: ['reload', 'register'],
    setup(_, { emit }) {
      const DeviceStep1Ref = ref<InstanceType<typeof DeviceStep1>>();
      const DeviceStep2Ref = ref<InstanceType<typeof DeviceStep2>>();
      const { createMessage } = useMessage();
      const current = ref(0);
      const isUpdate = ref<Boolean>(false);
      const deviceInfo = ref({});
      let currentDeviceData = {} as Recordable;
      const getTitle = computed(() => (!unref(isUpdate) ? '新增设备' : '编辑设备'));
      // 所有参数
      let stepState = ref();
      // 编辑回显
      const [register, { closeModal, setModalProps }] = useModalInner((data) => {
        setModalProps({ confirmLoading: false, loading: true });
        isUpdate.value = data?.isUpdate;
        if (unref(isUpdate)) {
          const { record } = data;
          currentDeviceData = record;
          unref(DeviceStep1Ref)?.parentSetFieldsValue({
            ...record,
            profile: record.deviceProfile.name,
            profileId: record.profileId,
            deviceType: record.deviceType,
            deviceInfo: record.deviceInfo,
          });
          unref(DeviceStep1Ref)?.disabledDeviceType(true);
        } else {
          unref(DeviceStep1Ref)?.disabledDeviceType(false);
          unref(DeviceStep1Ref)?.parentResetPositionState();
        }
        setModalProps({ loading: false });
      });

      // 上一步
      function handleStepPrev() {
        current.value--;
      }
      // 下一步
      function handleStep1Next(step1Values: any) {
        current.value++;
        stepState.value = { ...step1Values };
      }
      //
      function handleStep2Next(step2Values: any) {
        stepState.value = { ...stepState, ...step2Values };
      }
      function handleCancel() {
        if (unref(isUpdate)) {
          unref(DeviceStep1Ref)?.parentResetDevicePic(deviceInfo.value);
        }
        current.value = 0;
        unref(DeviceStep1Ref)?.resetFields();
        unref(DeviceStep2Ref)?.resetFieldsValueAndStatus();
      }
      // 提交
      const msg = computed(() => (unref(isUpdate) ? '更新设备成功' : '新增设备成功'));
      async function handleOk() {
        try {
          if (current.value === 0) {
            // 验证
            const valid = await unref(DeviceStep1Ref)?.parentValidate();
            if (!valid) return;
            stepState.value = unref(DeviceStep1Ref)?.parentGetFieldsValue();
          } else {
            // !!!此处需要删除地图的属性，否则会报堆栈溢出的错误 Uncaught RangeError: Maximum call stack size exceeded
            Reflect.deleteProperty(stepState.value, 'map');
            Reflect.deleteProperty(stepState.value, 'marker');
            if (unref(DeviceStep2Ref)?.getFieldsValue().addAgree) {
              const valid = await unref(DeviceStep2Ref)?.validate();
              if (!valid) return;
              // 第二页验证通过情况
              stepState.value = {
                ...unref(stepState),
                ...unref(DeviceStep2Ref)?.getFieldsValue(),
              };
            }
          }
          // 验证成功 --调-- 新增或者编辑接口
          // !!!此处需要删除地图的属性，否则会报堆栈溢出的错误 Uncaught RangeError: Maximum call stack size exceeded
          Reflect.deleteProperty(DeviceStep1Ref.value.positionState, 'map');
          Reflect.deleteProperty(DeviceStep1Ref.value.positionState, 'marker');
          setModalProps({
            confirmLoading: true,
          });
          if (unref(isUpdate)) {
            console.log(currentDeviceData);
            const editData = {
              ...unref(stepState),
              customerId: currentDeviceData.customerId,
              deviceInfo: {
                avatar: DeviceStep1Ref.value?.devicePic,
                ...DeviceStep1Ref.value?.positionState,
              },
            };
            await createOrEditDevice(editData);
          } else {
            const createData = {
              ...unref(stepState),
              deviceInfo: {
                avatar: DeviceStep1Ref.value?.devicePic,
                ...DeviceStep1Ref.value?.positionState,
              },
              deviceToken:
                unref(current) === 0 || !unref(stepState).addAgree
                  ? null
                  : {
                      credentialsType: unref(stepState).credentialType,
                      credentialsId: unref(stepState).credentialsId,
                      credentialsValue:
                        unref(stepState).credentialType === credentialTypeEnum.MQTT_BASIC
                          ? JSON.stringify({
                              userName: unref(stepState).username,
                              password: unref(stepState).password,
                              clientId: unref(stepState).clientId,
                            })
                          : unref(stepState).credentialType === credentialTypeEnum.X_509
                          ? unref(stepState).publicKey
                          : null,
                    },
            };
            await createOrEditDevice(createData);
          }
          createMessage.success(unref(msg));
          handleCancel();
          closeModal();
          emit('reload');
        } catch (error) {
        } finally {
          setModalProps({
            confirmLoading: false,
          });
        }
      }
      return {
        getTitle,
        current,
        DeviceStep1Ref,
        DeviceStep2Ref,
        deviceInfo,
        isUpdate,
        register,
        handleStepPrev,
        handleStep1Next,
        handleStep2Next,
        handleCancel,
        handleOk,
      };
    },
  });
</script>
