<template>
  <div v-if="tableData.ifShow">
    <div style="display: flex; margin-bottom: 10px">
      <div style="margin-left: 10px">
        <a-radio-group
          :disabled="tableData.componentProps.disabled"
          v-model:value="noTitleKey"
          :options="tableData.componentProps.options"
          @change="onTabChange($event, tableData.field)"
        />
      </div>
    </div>
    <!-- <a-card
      style="width: 100%"
      v-for="(item,index) in tableData.componentProps.options"
      :key="index"
      v-show="noTitleKey === item.value"
      :title="item.label"
    > -->
    <a-card style="width: 100%">
      <BasicForm ref="cardRef" @register="registerForm" @change="changeForm">
        <template #CardGroup>
          <template v-if="Object.keys(childItem).length > 0">
            <CardGourp
              :data="childItem"
              :parentValue="props.parentValue"
              :formData="props.formData"
              v-if="childItem"
              :callModal="props.callModal"
            />
          </template>
        </template>
      </BasicForm>
    </a-card>
  </div>
</template>
<script lang="ts" setup>
  import { BasicForm, useForm } from '@/components/Form';
  import { CardGourp } from './index';
  import { ref, watch, nextTick } from 'vue';
  import { subTableStore } from '@/store/modules/subTable';
  import dayjs from 'dayjs';

  const emits = defineEmits(['changeRadioVal']);

  const subTableDataStore = subTableStore();
  const props = defineProps({
    data: {
      type: Object,
      default: () => ({}),
    },
    parentValue: {
      type: String,
      default: () => '',
    },
    formData: {
      type: Object,
      default: () => ({}),
    },
    callModal: {
      type: Boolean,
      default: () => false,
    },
  });
  const noTitleKey = ref(0);
  const formColumns = ref([]);
  const tabListNoTitle: any = ref([]);
  const tableData = props.data;
  const childGourp = ref([]);
  const childItem = ref({});
  let cardFormData = props.formData;
  const nowTime = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'));
  const userName = localStorage.getItem('fireUserLoginName');
  const cardRef = ref<any>();
  if (props.callModal) {
    tableData.ifShow = true;
  }
  const [
    registerForm,
    { getFieldsValue, setFieldsValue, updateSchema, resetFields, validate, clearValidate },
  ] = useForm({
    labelWidth: 100,
    schemas: formColumns.value,
    showActionButtonGroup: false,
    baseColProps: { lg: 24, md: 24 },
  });
  watch(
    () => subTableDataStore.getToSetGroupData,
    () => {
      if (subTableDataStore.getToSetGroupData) {
        if (Object.keys(subTableDataStore.getGroupData).includes(tableData.field)) {
          noTitleKey.value = subTableDataStore.getGroupData[tableData.field];
          if (tableData.ifShow) {
            onTabChange({ target: { value: noTitleKey.value } }, tableData.field);
          }
        } else {
          noTitleKey.value = tableData.componentProps.options[0].value;
          if (tableData.ifShow) {
            onTabChange({ target: { value: noTitleKey.value } }, tableData.field);
          }
        }
      }
    },
  );
  watch(
    () => props.formData,
    (newVal) => {
      cardFormData = newVal;
      formColumns.value.forEach((element) => {
        for (const key in cardFormData) {
          if (element.field == key) {
            var obj = {};
            obj[key] = cardFormData[key];
            subTableDataStore.setGroupData(obj);
          }
        }
      });
      setTimeout(() => {
        setFieldsValue(subTableDataStore.getGroupData);
      }, 10);
    },
    { deep: true },
  );
  const onTabChange = (event, field) => {
    clearValidate();
    let value = event.target.value;
    subTableDataStore.setOneGroupData(field, value);
    noTitleKey.value = value;
    var currentIndex = (childGourp.value || []).findIndex((element) => element.index === value);

    if (currentIndex == -1) {
      childItem.value = {};
    } else {
      childItem.value = childGourp.value[currentIndex];
    }
    formColumns.value.forEach((element) => {
      if (element.component === 'CardGroup') {
        element.slot = 'CardGroup';
      }
      element.show = false;
      updateSchema([{ field: element.field, show: false }]);
      if (element.index == value) {
        element.show = true;
        if (element.requiredString) {
          element.itemProps.required = true;
          updateSchema([{ field: element.field, itemProps: { required: true } }]);
        }
        updateSchema([{ field: element.field, show: true }]);
      } else {
        element.itemProps.required = false;
        // delete element.itemProps.required;
        clearValidate(element.field);
        updateSchema([{ field: element.field, itemProps: { required: false } }]);
        // updateSchema([{ field: element.field, itemProps: element.itemProps }]);
      }
    });

    setTimeout(() => {
      resetFields();
      setFieldsValue(subTableDataStore.getGroupData);
    }, 10);
    emits('changeRadioVal');
  };
  if (tableData.componentProps) {
    tableData.componentProps.options.forEach((element, index) => {
      tabListNoTitle.value.push({
        key: index,
        tab: element.label,
        ...element,
        index: index,
      });
      element.children.forEach((childElement) => {
        formColumns.value.push({
          parentValue: element.field,
          ...childElement,
          show: index == 0 ? true : false,
          index: element.value,
          requiredString: childElement.itemProps.required,
        });
        if (childElement.component == 'CardGroup') {
          childGourp.value.push({
            ...childElement,
            index: element.value,
          });
        }
        if (['createuser', 'modifyuser'].includes(childElement.type)) {
          var obj = {};
          obj[childElement.field] = userName;
          subTableDataStore.setGroupData(obj);
        }
        if (['createtime', 'modifytime'].includes(childElement.type)) {
          var obj = {};
          obj[childElement.field] = nowTime.value;
          subTableDataStore.setGroupData(obj);
        }
      });
    });

    nextTick(() => {
      if (Object.keys(subTableDataStore.getGroupData).includes(tableData.field)) {
        noTitleKey.value = subTableDataStore.getGroupData[tableData.field];
        if (tableData.ifShow) {
          onTabChange({ target: { value: noTitleKey.value } }, tableData.field);
        }
      } else {
        noTitleKey.value = tableData.componentProps.options[0].value;
        if (tableData.ifShow) {
          onTabChange({ target: { value: noTitleKey.value } }, tableData.field);
        }
      }
    });
  }
  if (tableData.ifShow) {
    setTimeout(() => {
      resetFields();
    }, 10);
  }

  function changeForm() {
    setTimeout(() => {
      let data = getFieldsValue();
      console.log(data);
      let result = {};
      Object.keys(data).forEach((key) => {
        if (key.indexOf('card_group') == -1) {
          result[key] = data[key];
        }
      });
      subTableDataStore.setGroupData(result);
    }, 100);
  }

  async function verify() {
    const data = await validate()
      .then(async (data) => {
        return true;
      })
      .catch(async (err) => {
        console.log(err);
        if (err.errorFields.length > 0) {
          return false;
        } else {
          return true;
        }
      });
    return data;
  }
  defineExpose({
    verify,
    changeForm,
  });
</script>
