<template>
  <BasicModal
    @register="registerModal"
    v-bind="$attrs"
    title="管理设备凭证"
    @cancel="handleCancel"
    @ok="handleOk"
    centered
    :canFullscreen="false"
  >
    <BasicForm @register="registerForm">
      <template #clientId="{ field, model }">
        <div class="flex items-center">
          <Input v-model:value="model[field]" placeholder="请输入客户端ID" />
          <Tooltip title="刷新客户端ID">
            <ReloadOutlined class="ml-3 !text-blue-600" @click="handleCreateUUID" />
          </Tooltip>
        </div>
      </template>
      <template #credentialsId="{ field, model }">
        <div class="flex items-center">
          <Input v-model:value="model[field]" placeholder="请输入访问令牌" />
          <Tooltip title="刷新访问令牌">
            <ReloadOutlined class="ml-3 !text-blue-600" @click="handleCreateCredentialsId" />
          </Tooltip>
        </div>
      </template>
    </BasicForm>
  </BasicModal>
</template>

<script lang="ts">
  import { defineComponent } from 'vue';
  import { useModalInner, BasicModal } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { TokenSchemas, credentialTypeEnum } from '../../config/data';
  import { saveDeviceToken } from '/@/api/device/deviceManager';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Input, Tooltip } from 'ant-design-vue';
  import { buildUUID, randomString } from '/@/utils/uuid';
  import { ReloadOutlined } from '@ant-design/icons-vue';
  export default defineComponent({
    components: {
      BasicModal,
      BasicForm,
      Input,
      ReloadOutlined,
      Tooltip,
    },
    emits: ['register'],
    setup() {
      const [
        registerForm,
        { getFieldsValue, updateSchema, validate, resetFields, setFieldsValue },
      ] = useForm({
        labelWidth: 100,
        schemas: TokenSchemas,
        labelAlign: 'right',
        showSubmitButton: false,
        showResetButton: false,
        wrapperCol: {
          span: 16,
        },
      });
      const [registerModal, { closeModal }] = useModalInner(async (data) => {
        if (data.credentialsType === credentialTypeEnum.ACCESS_TOKEN) {
          updateSchema([
            {
              field: 'credentialType',
              ifShow: true,
            },
            {
              field: 'credentialsId',
              ifShow: true,
            },
          ]);
          setFieldsValue({
            credentialType: data.credentialsType,
            credentialsId: data.credentialsId,
            id: data.id.id,
            tbDeviceId: data.deviceId.id,
          });
        } else if (data.credentialsType === credentialTypeEnum.X_509) {
          updateSchema([
            {
              field: 'credentialType',
              ifShow: true,
            },
            {
              field: 'publicKey',
              ifShow: true,
            },
          ]);
          setFieldsValue({
            credentialType: data.credentialsType,
            publicKey: data.credentialsValue,
            id: data.id.id,
            tbDeviceId: data.deviceId.id,
          });
        } else {
          updateSchema([
            {
              field: 'credentialType',
              ifShow: true,
            },
            {
              field: 'clientId',
              ifShow: true,
            },
            {
              field: 'username',
              ifShow: true,
            },
            {
              field: 'password',
              ifShow: true,
            },
          ]);
          const credentialsValue = JSON.parse(data.credentialsValue);
          setFieldsValue({
            credentialType: data.credentialsType,
            clientId: credentialsValue?.clientId,
            username: credentialsValue?.userName,
            password: credentialsValue?.password,
            id: data.id.id,
            tbDeviceId: data.deviceId.id,
          });
        }
      });
      const checkedChange = (e) => {
        if (!e.target.checked) {
          updateSchema([
            {
              field: 'credentialsId',
              ifShow: false,
            },
            {
              field: 'clientId',
              ifShow: false,
            },
            {
              field: 'username',
              ifShow: false,
            },
            {
              field: 'password',
              ifShow: false,
            },
            {
              field: 'publicKey',
              ifShow: false,
            },
            {
              field: 'credentialType',
              ifShow: false,
            },
          ]);
          setFieldsValue({
            credentialType: '',
          });
        } else {
          updateSchema([
            {
              field: 'credentialType',
              ifShow: true,
            },
          ]);
        }
      };
      const handleCancel = () => {
        resetFields();

        updateSchema([
          {
            field: 'publicKey',
            ifShow: false,
          },
          {
            field: 'credentialsId',
            ifShow: false,
          },
          {
            field: 'clientId',
            ifShow: false,
          },
          {
            field: 'username',
            ifShow: false,
          },
          {
            field: 'password',
            ifShow: false,
          },
        ]);
      };
      const handleOk = async () => {
        const { createMessage } = useMessage();
        // 验证
        const valid = await validate();
        if (!valid) return;
        // 收集表单数据
        const field = getFieldsValue();
        const editData = {
          id: {
            id: field.id,
          },
          deviceId: {
            id: field.tbDeviceId,
            entityType: 'DEVICE',
          },
          credentialsType: field.credentialType,
          credentialsId: field.credentialsId,
          credentialsValue:
            field.credentialType === credentialTypeEnum.MQTT_BASIC
              ? JSON.stringify({
                  userName: field.username,
                  password: field.password,
                  clientId: field.clientId,
                })
              : field.credentialType === credentialTypeEnum.X_509
              ? field.publicKey
              : null,
        };
        saveDeviceToken(editData)
          .then((res) => {
            if (!res) return;
            createMessage.success('修改设备凭证成功');
            // 请求
            closeModal();
            handleCancel();
          })
          .catch(() => {});
      };

      const handleCreateUUID = () => {
        setFieldsValue({ clientId: buildUUID() });
      };

      const handleCreateCredentialsId = () => {
        setFieldsValue({ credentialsId: randomString() });
      };
      return {
        registerModal,
        registerForm,
        checkedChange,
        handleCancel,
        handleOk,
        handleCreateUUID,
        handleCreateCredentialsId,
      };
    },
  });
</script>
