<template>
  <div>
    <Tabs v-model:activeKey="currentKey" :size="currentSize" :animated="true">
      <TabPane forceRender key="1" tab="LWM2M Model">
        <BasicForm :showResetButton="false" :showSubmitButton="false" @register="registerModel" />
      </TabPane>
      <TabPane forceRender key="2" tab="Bootstrap">
        <div>
          <Checkbox
            @change="handleCheckChange($event)"
            v-model:checked="bootstrapServerUpdateEnable"
            >包括引导服务器更新
          </Checkbox>
          <CollapseContainer
            @hchange="hChange"
            @change="eChange(item, index)"
            v-for="(item, index) in dynamicBOOTSTRAP.bootstrap"
            :key="item"
            :title="collapseTitle(item)"
            class="mt-4"
            :isClose="item.close"
          >
            <template #action>
              <Popconfirm
                title="您确定要删除该项？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleRemove(index)"
              >
                <Button style="margin-right: 1vw" size="small" type="text">
                  <template #icon>
                    <DeleteOutlined />
                  </template>
                </Button>
              </Popconfirm>
            </template>
            <div style="border: 1px solid #d9d9d9; width: 100%">
              <div style="margin: 10px 15px">
                <BootStrapForm
                  :ref="dynamicBindRef.BootStrapFormItemRef"
                  :index="index"
                  :item="item"
                />
              </div>
            </div>
          </CollapseContainer>
          <div style="margin-top: 2vh">
            <Button size="middle" type="text" @click="handleAdd">
              <template #icon>
                <PlusCircleOutlined />
              </template>
              <span v-if="selectCheckStatus">Add server config</span>
              <span v-else>Add LwM2M Server</span>
            </Button>
          </div>
        </div>
      </TabPane>
      <TabPane forceRender key="3" tab="Other settings">
        <div
          style="
            display: flex;
            width: 43vw;
            border: 1px solid gray;
            border-radius: 5px;
            overflow: hidden;
          "
        >
          <div style="margin-left: -2vw; margin-top: 1.5vh">
            <BasicForm
              :showResetButton="false"
              :showSubmitButton="false"
              @register="registerSettings"
            />
          </div>
        </div>
      </TabPane>
      <TabPane forceRender key="4" tab="Json Config Profile Device">
        <BasicForm :showResetButton="false" :showSubmitButton="false" @register="registerDevice" />
      </TabPane>
    </Tabs>
    <ServerConfigModal @register="registerModal" @emitSelect="acceptEmitFunc" />
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, nextTick, unref } from 'vue';
  import { Tabs, TabPane } from 'ant-design-vue';
  import { BasicForm, useForm } from '/@/components/Form';
  import { modelSchemas, settingsSchemas, deviceSchemas } from './index';
  import BootStrapForm from './cpns/BootStrapForm.vue';
  import { DeleteOutlined, PlusCircleOutlined } from '@ant-design/icons-vue';
  import { Button, Checkbox, Popconfirm } from 'ant-design-vue';
  import { CollapseContainer } from '/@/components/Container';
  import { useModal } from '/@/components/Modal';
  import ServerConfigModal from './cpns/ServerConfigModal.vue';

  const eChange = (_, e1) => {
    if (eS) {
      dynamicBOOTSTRAP.bootstrap.forEach((bootstrap, index: number) => {
        if (index === e1) {
          bootstrap.close = true;
        }
      });
    }
  };
  let eS = false;
  const hChange = (e) => {
    eS = e;
  };
  const collapseTitle = (item) => {
    return `LwM2M Server        Short server ID: ${item.shortServerId}        Security config mode: ${item.securityMode}`;
  };
  const bootstrapServerUpdateEnable = ref(false);
  const dynamicBOOTSTRAP: any = reactive({
    bootstrap: [{ securityMode: 'NO_SEC', shortServerId: 1234, close: false }],
  });
  const dynamicBindRef: any = {
    BootStrapFormItemRef: ref([]),
  };
  const currentKey = ref('1');
  const currentSize = ref('large');
  let allObj: any = reactive({});
  let allEchoObj: any = reactive({});
  let clientLwM2mSettingsObj = reactive({});
  let observeAttrObj = reactive({
    attribute: [],
    attributeLwm2m: {},
    keyName: {},
    observe: [],
    telemetry: [],
  });

  const [registerModel, { resetFields: resetObjectListValue, getFieldsValue: getObjectListValue }] =
    useForm({
      labelWidth: 100,
      schemas: modelSchemas,
      actionColOptions: {
        span: 14,
      },
    });
  const [
    registerSettings,
    {
      resetFields: resetSettingsValue,
      validate: settingsValidate,
      setFieldsValue: settingsSetFieldsValueFunc,
    },
  ] = useForm({
    labelWidth: 180,
    schemas: settingsSchemas,
    actionColOptions: {
      span: 14,
    },
  });
  const [registerDevice, { resetFields: resetDeviceValue, getFieldsValue: getDeviceValue }] =
    useForm({
      labelWidth: 100,
      schemas: deviceSchemas,
      actionColOptions: {
        span: 14,
      },
    });
  const [registerModal, { openModal }] = useModal();

  const handleAdd = () => {
    //TODO 如果是server config 则只弹窗一次
    if (selectCheckStatus.value) {
      openModal(true, {
        isUpdate: true,
      });
    } else {
      dynamicBOOTSTRAP.bootstrap.push({
        securityMode: 'NO_SEC',
        shortServerId: 1234,
        close: false,
      });
    }
  };
  const handleRemove = (index) => {
    dynamicBOOTSTRAP.bootstrap.splice(index, 1);
  };
  const setFormData = (v) => {
    if (v) {
      allEchoObj = v;
      settingsSetFieldsValueFunc({
        ...allEchoObj?.clientLwM2mSettings,
      });
      nextTick(() => {
        bootstrapServerUpdateEnable.value = allEchoObj.bootstrapServerUpdateEnable;
        dynamicBOOTSTRAP.bootstrap = allEchoObj.bootstrap;
        dynamicBOOTSTRAP.bootstrap.forEach((bootstrap, index: number) => {
          nextTick(() => {
            unref(dynamicBindRef.BootStrapFormItemRef)[index]?.editBootStrapFormFunc(bootstrap);
          });
        });
      });
    }
  };
  const tempBootStrap: any = [];
  const getBootStrapFormValue = () => {
    //获取BootStrap的值
    unref(dynamicBindRef.BootStrapFormItemRef)?.map((item: any) =>
      tempBootStrap.push(item.getBootStrapFormFunc())
    );
  };

  const getFormData = async () => {
    const objectListVal = getObjectListValue();
    const deviceVal = getDeviceValue();
    console.log('第一个tab', objectListVal);
    console.log('第四个tab', deviceVal);
    getBootStrapFormValue();
    const settingsVal = await settingsValidate();
    if (!settingsVal) return;
    delete settingsVal.unit;
    delete settingsVal.unit2;
    clientLwM2mSettingsObj = {
      ...settingsVal,
    };
    allObj = {
      ...{
        clientLwM2mSettings: clientLwM2mSettingsObj,
      },
      ...{
        bootstrap: tempBootStrap,
      },
      ...{ bootstrapServerUpdateEnable: bootstrapServerUpdateEnable.value },
      ...{
        observeAttr: observeAttrObj,
      },
      type: 'LWM2M',
    };
    return allObj;
  };

  const resetFormData = () => {
    nextTick(() => {
      resetObjectListValue();
      resetSettingsValue();
      resetDeviceValue();
      unref(dynamicBindRef.BootStrapFormItemRef).map((item) => {
        item.resetFormData();
      });
    });
  };
  const selectCheckStatus = ref(false);
  const handleCheckChange = (e) => {
    selectCheckStatus.value = e.target.checked;
    if (!selectCheckStatus.value) {
      const findIndex = dynamicBOOTSTRAP.bootstrap.findIndex((o) => o.type == 'Bootstrap');
      if (findIndex !== -1) {
        dynamicBOOTSTRAP.bootstrap.splice(findIndex, 1);
      }
    }
  };
  const acceptEmitFunc = (e) => {
    switch (e) {
      case 'LwM2M':
        dynamicBOOTSTRAP.bootstrap.push({
          securityMode: 'NO_SEC',
          shortServerId: 1234,
          close: false,
        });
        break;
      case 'Bootstrap':
        dynamicBOOTSTRAP.bootstrap.push({
          securityMode: 'NO_SEC',
          shortServerId: 1234,
          close: false,
        });
        break;
    }
  };
  defineExpose({
    currentKey,
    currentSize,
    registerModel,
    registerSettings,
    registerDevice,
    getFormData,
    setFormData,
    resetFormData,
    dynamicBOOTSTRAP,
    dynamicBindRef,
    handleAdd,
    handleRemove,
    bootstrapServerUpdateEnable,
    collapseTitle,
    handleCheckChange,
    registerModal,
    acceptEmitFunc,
    selectCheckStatus,
  });
</script>

<style lang="less" scoped>
  :deep(.ant-select-selector) {
    max-width: 42rem !important;
  }
</style>
