<template>
  <div class="my-form-viewer">
    <template v-if="tabsColumns.length > 1">
      <a-tabs style="width: 100%" @change="tabsChange">
        <a-tab-pane v-for="(colItem, index) in tabsColumns" :tab="colItem.label" :key="index">
          <BasicForm ref="myDataBaseFormRef" @register="registerForm" />
          <subTable ref="subTableRef" :data="subTableColumns[index]" :tabsKey="tabsKey" />
          <CardGourp
            v-if="cardGroupData.length > 0 && cardGroupData[index]"
            :data="cardGroupData[index]"
            :formData="cardGourpFormData"
            :parentValue="cardGroupData[index].field"
            ref="groupRef"
          />
        </a-tab-pane>
      </a-tabs>
    </template>
    <BasicForm
      ref="myDataBaseFormRef"
      @register="registerForm"
      v-if="formModalVisible && tabsColumns.length < 1"
    />
    <!-- 设计子表 -->
    <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>
    <!-- 卡片组 -->
    <template v-if="formModalVisible && tabsColumns.length < 1">
      <CardGourp
        v-if="cardGroupData.length > 0"
        :data="cardGroupData[0]"
        :formData="cardGourpFormData"
        :parentValue="cardGroupData[0].field"
        ref="groupRef"
      />
    </template>
    <!-- todo  创建/修改  人/时间 -->
    <template v-for="(item, index) in createOrModifyList" :key="index">
      <CreateOrModifyComponent :data="item" />
    </template>
  </div>
</template>

<script lang="ts" setup>
  import { onMounted, ref, defineProps } 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 subTableDataStore = subTableStore();

  let formColumns: FormSchema[] = [];
  const props = defineProps({
    formConfig: Object,
    processId: String,
    formVerison: String,
    formRelationId: String,
    flowFormData: Object,
    instanceInfo: String,
    issueId: String,
  });
  console.log(props);
  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 }] =
    useForm({
      labelWidth: 100,
      schemas: formColumns,
      showActionButtonGroup: false,
      actionColOptions: {
        span: 24,
      },
    });
  async function getFormHistory() {
    console.log('getFormHistory');

    const data = await LoadFormScheme({
      schemeId: props.formVerison,
    });
    if (data) {
      const scheme = JSON.parse(data.scheme);
      scheme.formInfo.tabList.forEach((tabElement, index) => {
        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 (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;
                    }
                  }
                });
              });
            }
          });
        });
      });
      subTableColumns.value = [];
      // 将card组件嵌套起来
      scheme.formInfo.tabList = cardNestStructure(scheme.formInfo.tabList);
      console.log(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();
            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.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') {
            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;
      console.log(formColumns);
      setTimeout(() => {
        subTableDataStore.setTableData(tableColumns);
        resetFields();
        if (!disDetail) {
          console.log('赋值赋值');
          if (props.flowFormData) {
            setFieldsValue(props.flowFormData);
          }
        }
      }, 10);
    }
  }
  async function tabsChange(e) {
    console.log('tabsChange');
    tabsKey.value = e;
    formColumns.forEach((element) => {
      element.show = false;
      if (element.parentValue == e) {
        element.show = true;
      }
    });
    console.log(formColumns);
    // 切换时保存值
    const values = await validate();
    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];
          }
        }
      }
    }
    setFieldsValue({
      ...FieldsValue.value,
    });
  }

  async function getFormDetail() {
    console.log('getFormDetail');
    var instance = JSON.parse(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]);
          }
        }
      });
    }
    console.log(obj);
    cardGourpFormData.value = obj;
    subTableDataStore.setGroupData(obj);
    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;
          }
        });
      });
    }
  }
  const groupRef = ref();
  async function getForm() {
    // console.log(groupRef.value.verify());
    try {
      let values = await validate();
      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];
            }
          }
        }
      }
      console.log(values);
      console.log(FieldsValue.value);
      let cardValueList = Object.values(cardValues.value);
      cardValueList.forEach((item) => {
        values = { ...values, ...item };
      });
      let query = values;
      console.log(query);
      // 存储子表的信息
      if (subTableDataStore.getTableData.length > 0) {
        subTableDataStore.getTableData.forEach((item) => {
          query[item.parentFileId] = JSON.stringify(item.child);
        });
      }
      // 储存卡片组信息
      if (Object.keys(subTableDataStore.getGroupData).length > 0) {
        for (const key in subTableDataStore.getGroupData) {
          query[key] = subTableDataStore.getGroupData[key];
        }
      }
      console.log(query);
      // 存储创建人、创建时间等内容
      if (createOrModifyList.value.length > 0) {
        createOrModifyList.value.forEach((item) => {
          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.log(error);
      return false;
    }
  }
  async function getIssueInfo() {
    console.log("111",props.issueId);
  }
  defineExpose({
    getForm,
  });
  onMounted(() => {
    if (props.flowFormData) {
      FieldsValue.value = props.flowFormData;
    }
    if (props.formVerison) {
      getFormHistory();
    }
    if (props.issueId) {
      getIssueInfo();
    }
  });
</script>

<style lang="less" scoped>
  .my-process-designer {
    width: 100%;
  }
  .my-form-viewer {
    overflow: auto;
    height: calc( 100vh - 350px);
  }
</style>
