<template>
  <div class="tabs-detail">
    <div class="mt-4">
      <BasicForm @register="registerForm">
        <template #commandSlot>
          <div class="flex">
            <div ref="jsoneditorRef" style="height: 100%; width: 100%"></div>
            <a-button style="margin: -5px 0" type="text" @click="handlePremitter">格式化</a-button>
            <Tooltip title='{"method":"methodThingskit","params":{"pin":7,"value":1}}' class="ml-2">
              <QuestionCircleOutlined style="font-size: 1rem" />
            </Tooltip>
          </div>
        </template>
      </BasicForm>
      <div>
        <Button :disabled="disable" type="primary" @click="handleOk" class="mr-2">确定</Button>
        <Button type="default" @click="handleCancel" class="mr-2">重置</Button>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, onMounted, unref, nextTick } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form';
  import { CommandSchemas } from '../../config/data';
  import { commandIssuanceApi } from '/@/api/device/deviceManager';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Button } from '/@/components/Button';
  import jsoneditor from 'jsoneditor';
  import 'jsoneditor/dist/jsoneditor.min.css';
  import { QuestionCircleOutlined } from '@ant-design/icons-vue';
  import { Tooltip } from 'ant-design-vue';
  import { DeviceRecord } from '/@/api/device/model/deviceModel';
  import { TransportTypeEnum } from '../../../profiles/components/TransportDescript/const';

  interface CommandParams {
    additionalInfo: Recordable;
    cmdType: string;
    method: string;
    params: string | Recordable;
    persistent: boolean;
  }

  export default defineComponent({
    components: { BasicForm, Button, QuestionCircleOutlined, Tooltip },
    props: {
      deviceDetail: {
        type: Object as PropType<DeviceRecord>,
        required: true,
      },
    },
    emits: ['register'],
    setup(props) {
      const { createMessage } = useMessage();
      const jsonData = ref<CommandParams>({} as unknown as CommandParams);
      const disable = ref(false);

      const [registerForm, { getFieldsValue, validate, resetFields }] = useForm({
        labelWidth: 100,
        schemas: CommandSchemas(
          props.deviceDetail.deviceProfile.transportType as TransportTypeEnum
        ),
        labelAlign: 'right',
        showSubmitButton: false,
        showResetButton: false,
        wrapperCol: {
          span: 12,
        },
      });
      // json 以及初始化JSON
      const jsoneditorRef = ref();
      const jsonValue = ref({});
      const jsonInstance = ref();
      onMounted(() => {
        nextTick(() => {
          let options = {
            mode: 'code',
            mainMenuBar: false,
            statusBar: false,
          };
          let editor = new jsoneditor(jsoneditorRef.value, options);
          editor.set(jsonValue.value);
          jsonInstance.value = editor;
        });
      });
      const handlePremitter = () => {
        const value = unref(jsonInstance).get();
        if (!value) return;
        return unref(jsonInstance).set(value);
      };
      const handleCancel = () => {
        resetFields();
        unref(jsonInstance).set({});
      };
      const handleOk = async () => {
        disable.value = true;
        try {
          // 验证
          const valid = await validate();
          if (!valid) return;
          // 收集表单数据
          const field = getFieldsValue();
          let passStatus = false;
          if (field.valueType === 'json') {
            const getJson = unref(jsonInstance).get();
            if (Object.prototype.isPrototypeOf(getJson) && Object.keys(getJson).length === 0) {
              createMessage.error('命令内容不能为空');
              passStatus = true;
            }
            if (getJson === '') {
              passStatus = true;
              createMessage.error('命令内容不能为空');
            }
            jsonData.value.params = getJson;
          } else {
            jsonData.value.params = field.commandText;
            if (!jsonData.value.params) {
              createMessage.error('命令内容不能为空');
              passStatus = true;
            }
            if (
              jsonData.value.params == '""' ||
              jsonData.value.params == "''" ||
              jsonData.value.params == '“”'
            ) {
              createMessage.error('命令内容不能为空');
              passStatus = true;
            }
          }
          jsonData.value.persistent = true;
          jsonData.value.method = 'methodThingskit';
          if (passStatus) return;
          commandIssuanceApi(field.commandType, props.deviceDetail.tbDeviceId, jsonData.value)
            .then((res) => {
              if (!res) return;
              createMessage.success('命令下发成功');
              disable.value = true;
              // 请求
              handleCancel();
            })
            .catch((e) => {
              if (e?.message) {
                createMessage.error(e?.message);
              }
              handleCancel();
            })
            .finally(() => {
              setTimeout(() => {
                disable.value = false;
              }, 300);
            });
        } catch (e) {
        } finally {
          //这里捕获json插件的错误
          disable.value = false;
        }
      };
      return {
        registerForm,
        handleCancel,
        handleOk,
        disable,
        jsonData,
        jsoneditorRef,
        jsonValue,
        jsonInstance,
        handlePremitter,
      };
    },
  });
</script>
<style scoped>
  .jsoneditor-transform {
    background-position: -144px -96px;
    display: none !important;
  }
</style>
