<template>
  <div class="my-form-viewer">
    <div v-show="tabsColumns.length > 1">
      <a-tabs v-model:activeKey="activeTabsKey" style="width: 100%" @change="tabsChange">
        <a-tab-pane v-for="(colItem, index) in tabsColumns" :tab="colItem.label" :key="index">
          <BasicForm :ref="`tabsFormRef${index}`" @register="registerForm" :key="index">
            <template #CardGroup>
              <CardGourp
                v-if="cardGroupData.length > 0 && cardGroupData[index]"
                :data="cardGroupData[index]"
                :formData="cardGourpFormData"
                :parentValue="cardGroupData[index].field"
                ref="groupRef"
                @changeRadioVal="radioVal"
              />
            </template>
          </BasicForm>
          <subTable ref="subTableRef" :data="subTableColumns[index]" :tabsKey="tabsKey" />

          <template v-for="(item, useIndex) in createOrModifyList[index]" :key="useIndex">
            <CreateOrModifyComponent :data="item" />
          </template>
        </a-tab-pane>
      </a-tabs>
    </div>
    <BasicForm
      ref="formRef"
      @register="registerForm"
      v-if="formModalVisible && tabsColumns.length < 1"
    >
      <template #CardGroup>
        <CardGourp
          v-if="cardGroupData.length > 0"
          :data="cardGroupData[0]"
          :formData="cardGourpFormData"
          :parentValue="cardGroupData[0].field"
          ref="groupRef"
          @changeRadioVal="radioVal"
        />
      </template>
    </BasicForm>
    <!-- 设计子表 -->
    <subTable v-if="formModalVisible && tabsColumns.length < 1" :data="subTableColumns[0]" />
    <!-- 卡片 -->
    <template v-for="(item, index) in cardLayout" :key="index">
      <a-row style="width: 100%">
        <a-col :span="item?.colProps?.span || 24" style="padding: 10px">
          <a-card
            :title="item.label"
            :class="
              item.shadow === 'always' ? 'card-always' : item.shadow === 'hover' ? 'card-hover' : ''
            "
          >
            <template v-for="(childItem, childIndex) in item.columns[0].children" :key="childIndex">
              <a-row style="width: 100%; margin-bottom: 10px">
                <a-col :span="childItem?.colProps?.span || 24">
                  <CallModalCardFormItem
                    :data="childItem"
                    :dataKey="item.field"
                    :values="cardValues"
                  />
                </a-col>
              </a-row>
            </template>
          </a-card>
        </a-col>
      </a-row>
    </template>
    <!-- todo  创建/修改  人/时间 -->
    <template v-if="tabsColumns.length < 1">
      <template v-for="(item, index) in createOrModifyList[0]" :key="index">
        <CreateOrModifyComponent :data="item" />
      </template>
    </template>
  </div>
</template>

<script lang="ts" setup>
  import { onMounted, ref, defineProps, defineEmits, getCurrentInstance, nextTick } from 'vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { functionGetFormDataFormScheme, LoadFormScheme } from '@/api/demo/formScheme';
  import { PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue';
  import CallModalCardFormItem from '@/views/demo/onlineform/formCall/CallModalFormItem/index.vue';
  import CreateOrModifyComponent from '@/views/demo/onlineform/formCall/CreateOrModifyComponent/index.vue';
  import { SubTable, CardGourp } from './index';
  import { v4 as uuidv4 } from 'uuid';
  import { cardNestStructure } from '@/views/demo/onlineform/util.ts';
  import { subTableStore } from '@/store/modules/subTable';
  import dayjs from 'dayjs';

  const { proxy } = getCurrentInstance();
  const emit = defineEmits(['getFormSuccess']);
  const subTableDataStore = subTableStore();
  const tabsFormRef0 = ref();
  const tabsFormRef1 = ref();
  const tabsFormRef2 = ref();
  const tabsFormRef3 = ref();
  const tabsFormRef4 = ref();
  const formRef = ref();
  const activeTabsKey = ref();
  let formColumns: FormSchema[] = [];
  const props = defineProps({
    formConfig: Object,
    processId: String,
    formVerison: String,
    formRelationId: String,
    flowFormData: Object,
    instanceInfo: Object,
    issueId: String,
    isDetail: Boolean,
  });
  const subTableId = ref(null);
  const subTableColumns: any = ref([]);
  const subTableDB = ref([]);
  const cardLayout = ref([]);
  const cardValues = ref({});
  const createOrModifyList = ref([]);
  const formModalVisible = ref(false);
  const tabsColumns: any = ref([]);
  const infoUseSubTableData = ref();
  const infoUseMainTableData = ref({});
  const tabsKey = ref(0);
  const keyValue = ref('');
  const FieldsValue = ref({});
  const subTableRef = ref<any>();
  const cardGroupData = ref([]);
  const cardGourpFormData = ref({});
  subTableDataStore.clearGoupData();
  const nowTime = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'));
  const userName = localStorage.getItem('fireUserLoginName');
  const getCardLayoutKey = (dataList, key) => {
    dataList.forEach((item) => {
      if (item.component === 'Card') {
        getCardLayoutKey(item.columns[0].children, key);
      } else if (item.type === 'subTable') {
        cardValues.value[key][item.field] = [];
      } else {
        cardValues.value[key][item.field] = '';
      }
    });
  };
  const [
    registerForm,
    { getFieldsValue, setFieldsValue, updateSchema, resetFields, validate, clearValidate },
  ] = useForm({
    labelWidth: 100,
    schemas: formColumns,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
  });
  async function getFormHistory() {
    const data = await LoadFormScheme({
      schemeId: props.formVerison,
    });
    if (data) {
      const scheme = JSON.parse(data.scheme);
      scheme.formInfo.tabList.forEach((tabElement, index) => {
        createOrModifyList.value.push([]);
        tabElement.schemas.forEach((element) => {
          //流程设置的表单显示和编辑与表单做关联
          props.formConfig.forEach((configElement) => {
            if (configElement.field == element.field) {
              element.componentProps.disabled = !configElement.disabled;
              element.ifShow = configElement.ifShow;
              if (configElement.required) {
                element.itemProps.required = configElement.required;
              }
            }
            if (
              props.isDetail &&
              ['createuser', 'createtime', 'modifyuser', 'modifytime'].includes(element.type)
            ) {
              element.ifShow = true;
              element.component = 'Input';
              element.componentProps.disabled = true;
            }
            if (element.columns) {
              element.columns.forEach((child) => {
                child.children.forEach((t) => {
                  if (configElement.field == t.field) {
                    t.componentProps.disabled = !configElement.disabled;
                    t.ifShow = configElement.ifShow;
                    if (configElement.required) {
                      t.itemProps.required = configElement.required;
                    }
                  }
                  if (
                    props.isDetail &&
                    ['createuser', 'createtime', 'modifyuser', 'modifytime'].includes(t.type)
                  ) {
                    t.ifShow = true;
                    t.component = 'Input';
                    t.componentProps.disabled = true;
                  }
                });
              });
            }
          });
        });
      });
      subTableColumns.value = [];
      // 将card组件嵌套起来
      scheme.formInfo.tabList = cardNestStructure(scheme.formInfo.tabList);
      subTableDB.value = scheme.db;
      let disDetail = false;
      let tableColumns = [];
      scheme.formInfo.tabList.forEach((tabElement, index) => {
        subTableColumns.value.push({
          indexValue: index,
          parentFileId: '',
          child: [],
          multiterm: '',
        });
        tabElement.schemas.forEach((element) => {
          if (element.field == props.formRelationId) {
            keyValue.value = element.componentProps.fieldName;
            getFormDetail(scheme.formInfo.tabList);
            disDetail = true;
          }
          if (element.component === 'InputGuid') {
            element.ifShow = false;
          }
          // 验证规则
          if (element.rules !== undefined) {
            let myString = element.rules[0].pattern;
            const lastCharacter = myString.charAt(myString.length - 1);
            if (lastCharacter === 'i' || lastCharacter === 's') {
              element.rules[0].pattern = new RegExp(
                element.rules[0].pattern.slice(1, -2),
                lastCharacter,
              );
            } else {
              element.rules[0].pattern = new RegExp(element.rules[0].pattern.slice(1, -1));
            }
          }
          // 卡片布局
          if (element.component === 'Card') {
            cardLayout.value.push(element);
            cardValues.value[element.field] = {};
            getCardLayoutKey(element.columns[0].children, element.field);
          }
          if (['createuser', 'createtime', 'modifyuser', 'modifytime'].includes(element.type)) {
            createOrModifyList.value[index].push(element);
          }
          // 选项卡
          if (element.type === 'subTable') {
            subTableId.value = element.field;
            subTableColumns.value[index].parentFileId = element.field;
            (subTableColumns.value[index].multiterm = element.componentProps.multiterm),
              tableColumns.push({
                parentFileId: element.field,
                child: [],
                dataTable: element.componentProps.dataTable,
              });
            element.columns.forEach((itemColumn) => {
              itemColumn.children.forEach((itemColumnChild) => {
                subTableColumns.value[index].child.push({
                  key: itemColumnChild.field,
                  title: itemColumnChild.label,
                  dataIndex: itemColumnChild.field,
                  ...itemColumnChild,
                  width: 120,
                });
              });
            });
          }
          // 卡片组布局
          if (element.component === 'CardGroup') {
            element.slot = 'CardGroup';
            if (cardGroupData.value.length !== index) {
              cardGroupData.value.push(null);
            }
            cardGroupData.value.push(element);
            // cardGroupData.value.push({
            //   ...element,
            // });
          }
          //栅格
          if (element.component === 'Grid' && element.label === '栅格布局') {
            element.columns.forEach((itemColumn) => {
              itemColumn.children.forEach((itemColumnChild) => {
                itemColumnChild.colProps.span = itemColumn.span;
                formColumns.push({
                  parentValue: index,
                  ...itemColumnChild,
                  show: index == 0 ? true : false,
                });
              });
            });
          }
          formColumns.push({
            parentValue: index,
            ...element,
            show: index == 0 ? true : false,
          });
        });
        //
        if (tabElement.text != '') {
          tabsColumns.value.push({
            label: tabElement.text,
            value: index,
            children: tabElement.schemas,
          });
        }
      });
      formModalVisible.value = true;
      setTimeout(() => {
        subTableDataStore.setTableData(tableColumns);
        resetFields();
        if (!disDetail) {
          if (props.flowFormData) {
            if (props.flowFormData.mapGeom) {
              props.flowFormData.MapGeom = props.flowFormData.mapGeom;
            }
            console.log('flowFormDataAfter', props.flowFormData);
            setFieldsValue(props.flowFormData);
          }
        }
      }, 10);
    }
  }
  function tabsChange(e) {
    tabsKey.value = e;
    formColumns.forEach((element) => {
      element.show = false;
      if (element.parentValue == e) {
        element.show = true;
      }
    });
    // 切换时保存值
    // const values = await validate();
    const values = getFieldsValue();
    if (Object.keys(FieldsValue.value).length == 0) {
      FieldsValue.value = values;
    }
    for (const key in values) {
      for (const fieKey in FieldsValue.value) {
        if (key == fieKey) {
          if (values[key] != undefined) {
            FieldsValue.value[key] = values[key];
          }
        }
      }
    }
    setTimeout(() => {
      setFieldsValue(FieldsValue.value);
      clearValidate();
    }, 10);
  }

  async function getFormDetail(element) {
    var instance = props.instanceInfo;
    const querys = {
      id: props.formVerison,
      key: keyValue.value,
      keyValue: instance.pkeyValue,
    };
    const data = await functionGetFormDataFormScheme(querys);
    let obj = new Object();
    for (var i in data) {
      subTableDB.value.forEach((element) => {
        if (element.type == 'chlid') {
          subTableDataStore.getTableData.forEach((element) => {
            if (element.dataTable == i) {
              subTableDataStore.setSingleData(element.parentFileId, data[i]);
            }
          });
        } else {
          for (var j in data[i]) {
            Object.assign(obj, data[i][j]);
          }
        }
      });
    }
    cardGourpFormData.value = obj;
    let cardGroupKeys = [];
    element.forEach((tabItem) => {
      tabItem.schemas.forEach((elItem) => {
        if (elItem.component == 'CardGroup' && elItem.field.indexOf('guid') == -1) {
          cardGroupKeys = cardGroupGetKey(elItem, cardGroupKeys);
        }
      });
    });
    let setGroupDataObj = {};
    Object.keys(obj).forEach((itemKey) => {
      if (cardGroupKeys.includes(itemKey)) {
        setGroupDataObj[itemKey] = obj[itemKey];
      }
    });
    subTableDataStore.setGroupData(setGroupDataObj);
    subTableDataStore.setOldDefaultGroupData(setGroupDataObj);
    subTableDataStore.setToSetGroupData();
    FieldsValue.value = obj;
    setFieldsValue({
      ...obj,
    });
    if (subTableDB.value.length > 1) {
      let childTableName = subTableDB.value.find((item) => item.type === 'chlid').name;
      let mainTableName = subTableDB.value.find((item) => item.type === 'main').name;
      infoUseSubTableData.value = data[childTableName].map((item) => {
        return {
          ...item,
          key: uuidv4(),
        };
      });
      data[mainTableName].forEach((item) => {
        infoUseMainTableData.value = { ...infoUseMainTableData.value, ...item };
      });
    }
    if (Object.keys(cardValues.value).length > 0) {
      Object.keys(cardValues.value).forEach((cardItem) => {
        let cardItemKeyList = Object.keys(cardValues.value[cardItem]);
        Object.keys(infoUseMainTableData.value).forEach((item) => {
          if (cardItemKeyList.includes(item)) {
            cardValues.value[cardItem][item] = infoUseMainTableData.value[item];
          }
        });
        // todo
        cardItemKeyList.forEach((item) => {
          if (item.indexOf('grid') !== -1) {
            cardValues.value[cardItem][item] = infoUseSubTableData.value;
          }
        });
      });
    }
    let mainTable = subTableDB.value.find((item) => item.type === 'main').name;
    emit('getFormSuccess', data[mainTable][0]);
  }
  const groupRef = ref();
  const cardGroupGetKey = (element, resultList) => {
    resultList.push(element.field);
    element.componentProps.options.forEach((groupItem) => {
      groupItem.children.forEach((childItem) => {
        resultList.push(childItem.field);
        if (childItem.component == 'CardGroup' && childItem.field.indexOf('guid') == -1) {
          resultList = cardGroupGetKey(childItem, resultList);
        }
      });
    });
    return resultList;
  };
  async function getForm() {
    try {
      // 验证卡片组必填项
      if (groupRef.value) {
        if (groupRef.value.length > 0) {
          for (let index = 0; index < groupRef.value.length; index++) {
            await groupRef.value[index].submitChangeFrom();
            if (!(await groupRef.value[index].verify())) {
              return false;
            }
          }
        } else {
          await groupRef.value.submitChangeFrom();
          if (!(await groupRef.value.verify())) {
            return false;
          }
        }
      }
      let resultObj = {};
      let values;
      switch (activeTabsKey.value) {
        case 0:
          resultObj = proxy.$refs.tabsFormRef0[0].getFieldsValue();
          proxy.$refs.tabsFormRef0[0].setFieldsValue({
            ...resultObj,
            ...subTableDataStore.getGroupData,
          });
          await proxy.$refs.tabsFormRef0[0].validate();
          values = proxy.$refs.tabsFormRef0[0].getFieldsValue();
          break;
        case 1:
          resultObj = proxy.$refs.tabsFormRef1[0].getFieldsValue();
          proxy.$refs.tabsFormRef1[0].setFieldsValue({
            ...resultObj,
            ...subTableDataStore.getGroupData,
          });
          await proxy.$refs.tabsFormRef1[0].validate();
          values = proxy.$refs.tabsFormRef1[0].getFieldsValue();
          console.log('resultValue111', JSON.parse(JSON.stringify(values)));
          break;
        case 2:
          resultObj = proxy.$refs.tabsFormRef2[0].getFieldsValue();
          proxy.$refs.tabsFormRef2[0].setFieldsValue({
            ...resultObj,
            ...subTableDataStore.getGroupData,
          });
          await proxy.$refs.tabsFormRef2[0].validate();
          values = proxy.$refs.tabsFormRef2[0].getFieldsValue();
          break;
        case 3:
          resultObj = proxy.$refs.tabsFormRef3[0].getFieldsValue();
          proxy.$refs.tabsFormRef3[0].setFieldsValue({
            ...resultObj,
            ...subTableDataStore.getGroupData,
          });
          await proxy.$refs.tabsFormRef3[0].validate();
          values = proxy.$refs.tabsFormRef3[0].getFieldsValue();
          break;
        case 4:
          resultObj = proxy.$refs.tabsFormRef4[0].getFieldsValue();
          proxy.$refs.tabsFormRef4[0].setFieldsValue({
            ...resultObj,
            ...subTableDataStore.getGroupData,
          });
          await proxy.$refs.tabsFormRef4[0].validate();
          values = proxy.$refs.tabsFormRef4[0].getFieldsValue();
          break;
        case 5:
          resultObj = proxy.$refs.tabsFormRef5[0].getFieldsValue();
          proxy.$refs.tabsFormRef5[0].setFieldsValue({
            ...resultObj,
            ...subTableDataStore.getGroupData,
          });
          await proxy.$refs.tabsFormRef5[0].validate();
          values = proxy.$refs.tabsFormRef5[0].getFieldsValue();
          break;
        case 6:
          resultObj = proxy.$refs.tabsFormRef6[0].getFieldsValue();
          proxy.$refs.tabsFormRef6[0].setFieldsValue({
            ...resultObj,
            ...subTableDataStore.getGroupData,
          });
          await proxy.$refs.tabsFormRef6[0].validate();
          values = proxy.$refs.tabsFormRef6[0].getFieldsValue();
          break;
        default:
          resultObj = getFieldsValue();
          setFieldsValue({
            ...resultObj,
            ...subTableDataStore.getGroupData,
          });
          values = await validate();
          break;
      }
      for (const key in values) {
        for (const fieKey in FieldsValue.value) {
          if (key == fieKey) {
            if (values[key] == null || values[key] == undefined) {
              values[key] = FieldsValue.value[key];
            }
          }
        }
      }
      let cardValueList = Object.values(cardValues.value);
      cardValueList.forEach((item) => {
        values = { ...values, ...item };
      });
      let query = values;
      // 存储子表的信息
      if (subTableDataStore.getTableData.length > 0) {
        subTableDataStore.getTableData.forEach((item) => {
          query[item.parentFileId] = JSON.stringify(item.child);
        });
      }
      // 储存卡片组信息
      setTimeout(() => {
        if (Object.keys(subTableDataStore.getGroupData).length > 0) {
          for (const key in subTableDataStore.getGroupData) {
            query[key] = subTableDataStore.getGroupData[key];
          }
        }
      }, 100);
      // 存储创建人、创建时间等内容
      if (createOrModifyList.value.length > 0) {
        createOrModifyList.value.forEach((childTab) => {
          childTab.forEach((item) => {
            if (!item.componentProps.disabled) {
              if (item.type == 'createuser' || item.type == 'modifyuser') {
                query[item.field] = userName;
              } else if (item.type == 'createtime' || item.type == 'modifytime') {
                query[item.field] = nowTime.value;
              }
            }
          });
        });
      }
      console.log(query);
      return query;
    } catch (error) {
      console.error(error);
      return false;
    }
  }
  defineExpose({
    getForm,
  });
  onMounted(() => {
    if (props.flowFormData) {
      FieldsValue.value = props.flowFormData;
    }
    if (props.formVerison) {
      getFormHistory();
    }
    // tabsFormRef.value && tabsFormRef.value.clearValidate();
    // formRef.value && formRef.value.clearValidate();
  });
  function radioVal() {
    console.log('radioVal');
    clearValidate();
    //切换卡片组选项时，卡片组的值赋值给form，优化卡片组必填验证不通过
    setFieldsValue({
      ...subTableDataStore.getGroupData,
    });
  }
</script>

<style lang="less" scoped>
  .my-process-designer {
    width: 100%;
  }
  .my-form-viewer {
    overflow: auto;
    width: 100%;
    height: calc(100vh - 350px);
  }
  ::v-deep .ant-tabs .ant-tabs-nav-wrap {
    position: fixed;
    width: 100%;
    z-index: 1;
    background-color: @component-background;
    border-bottom: 1px solid rgba(5, 5, 5, 0.06);
  }
  ::v-deep .ant-tabs-content-holder {
    margin-top: 40px;
  }
</style>
