<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :canFullscreen="false"
    :defaultFullscreen="true"
    :showCancelBtn="false"
    :showOkBtn="false"
    :draggable="false"
    title="慧创 表单设计"
  >
    <div :class="`${prefixCls}`">
      <div :class="`${prefixCls}-header`">
        <div :class="`${prefixCls}-header-logo`">
          <img src="/huichuang_logo.png" alt="慧创科技" /> <span>表单设计</span>
        </div>
        <div :class="`${prefixCls}-header-stepsBox`">
          <a-steps
            :current="stepsCurrent"
            :items="[
              {
                title: '基本配置',
              },
              {
                title: '表单设计',
              },
            ]"
          />
        </div>
        <div :class="`${prefixCls}-header-btnBox`">
          <a-button :disabled="stepsCurrent !== 1" @click="formPrevClick">上一步</a-button>
          <a-button :disabled="stepsCurrent == 1" @click="formNextClick">下一步</a-button>
          <a-button @click="stageClick" type="success">暂存</a-button>
          <a-button :disabled="stepsCurrent !== 1" @click="submitClick" type="primary">
            保存
          </a-button>
          <a-button type="primary" danger @click="closeModalClick">关闭</a-button>
        </div>
      </div>
      <div :class="`${prefixCls}-content`">
        <FormDesign
          v-show="stepsCurrent == 1"
          :isSubmitClick="isSubmitClick"
          @designformback="designformback"
        />
        <FormPage
          v-show="stepsCurrent == 0"
          :formScheme="formScheme"
          :isNextSteps="isNextSteps"
          :isAddVisible="isAddVisible"
          :isStageClick="isStageClick"
          @form-data-back="formDataBack"
          @form-data-no-back="formDataNoBack"
          @automatic-form-data-back="automaticFormDataBack"
        />
      </div>
    </div>
    <AutomaticModal
      @register="automaticModal"
      :isAddVisible="isAddVisible"
      :isStageClick="isStageClick"
      @automatic-modal-submitsuccess="automaticModalSubmitsuccess"
    />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, provide, computed } from 'vue';
  import { message } from 'ant-design-vue';
  import { BasicModal, useModal, useModalInner } from '@/components/Modal';
  // 子组件
  import AutomaticModal from './modal/AutomaticModal.vue';
  import FormPage from './form/index.vue';
  import FormDesign from '../../form-design/index.vue';
  import {
    getBaseConfigList,
    addFormDesignData,
    editFormDesignData,
    getOutKeyList,
  } from '@/api/formdesign/index';
  import { functionGetForm } from '@/api/demo/formScheme';
  import { cardNestStructure, changeCardStructure } from '@/views/demo/onlineform/util.ts';

  defineOptions({ name: 'FormModal' });

  const emit = defineEmits(['submitsuccess']);
  let isAddVisible = ref();

  let formScheme: any = ref({ info: {}, scheme: {} });

  let formScheme_id = '';
  let formScheme_type = '';

  let saveFormDatas: any = ref({});
  const primaryKey: any = ref();
  provide(
    'handleNextStepsData',
    computed(() => saveFormDatas.value),
  );
  provide(
    'thisFormType',
    computed(() => saveFormDatas.value),
  );
  async function getTableColumnData(schems) {
    var arr: any = [];
    for (var i = 0; i < schems.db.length; i++) {
      let params = {
        dbCode: schems.dbCode,
        tableNames: schems.db[i].name,
      };
      await getOutKeyList(params).then((res: Recordable) => {
        // console.log(res);
        if (res.length > 0) {
          arr.push({
            name: schems.db[i].name,
            data: res[0]?.db_codecolumnsList,
          });
        }
      });
    }
    return arr;
  }
  async function designSendGrandson(value) {
    let designTab = JSON.parse(value);
    let schems = saveFormDatas.value.scheme.scheme
      ? JSON.parse(saveFormDatas.value.scheme.scheme)
      : JSON.parse(
          '{"db":[{"name":"form_scheme","type":"main"}],"rdb":[],"dbCode":"hcsystemdb","formInfo":{"schemas":[]},"primaryKey":"Id"}',
        );
    let tableData = await getTableColumnData(schems);
    let tabArr: any = [];
    let tabLabelArr: any = [];
    console.log('beforedesignTab', designTab);
    designTab.schemas.forEach((item) => {
      if (item.component !== 'Tabs') {
        if (item.componentProps.defaultValue) {
          item.defaultValue = item.componentProps.defaultValue;
        }
        if (item.componentProps.fieldName) {
          tableData.forEach((element) => {
            if (element.name == item.componentProps.dataTable) {
              var currentIndex = element.data.findIndex(
                (childItem) => childItem.dbColumnName === item.componentProps.fieldName,
              );
              item.csType = element.data[currentIndex].csType;
            }
          });
          if (item.csType == 'int') {
            if (item.componentProps.options && item.componentProps.options.length > 0) {
              item.componentProps.options.forEach((optionChild) => {
                optionChild.value = Number(optionChild.value);
              });
            }
          }
        }
        // 设计子表给里面的控件增加csType字段
        if (item.type == 'subTable') {
          item.columns = changeCloums(item.columns, tableData);
        }
        if (item.columns) {
          item.columns = changeCloums(item.columns, tableData);
        }
        if (item.component === 'CardGroup') {
          item.componentProps.options = changeCloums(item.componentProps.options, tableData);
        }
        if (
          item.component != 'CardGroup' &&
          item.component != 'Grid' &&
          item.component != 'MapGeom' &&
          item.component != 'Divider' &&
          item.component != 'Slider' &&
          item.component != 'Card' &&
          item.component != 'Location'
        ) {
          tabArr.push(item.componentProps.fieldName);
          if (!item.componentProps.fieldName) {
            tabLabelArr.push(item.label);
          }
        }
      } else {
        item.componentProps.options.forEach((val) => {
          val.children.forEach((list) => {
            if (list.componentProps && list.componentProps.defaultValue) {
              list.defaultValue = list.componentProps.defaultValue;
            }
            if (list.componentProps && list.componentProps.fieldName) {
              tableData.forEach((element) => {
                if (element.name == list.componentProps.dataTable) {
                  var currentIndex = element.data.findIndex(
                    (childItem) => childItem.dbColumnName === list.componentProps.fieldName,
                  );
                  list.csType = element.data[currentIndex].csType;
                }
              });
              if (list.csType == 'int') {
                if (list.componentProps.options && list.componentProps.options.length > 0) {
                  list.componentProps.options.forEach((optionChild) => {
                    optionChild.value = Number(optionChild.value);
                  });
                }
              }
            }
            // 设计子表给里面的控件增加csType字段
            if (list.type == 'subTable') {
              list.columns = changeCloums(list.columns, tableData);
            }
            if (list.columns) {
              list.columns = changeCloums(list.columns, tableData);
            }
            if (list.component === 'CardGroup') {
              list.componentProps.options = changeCloums(list.componentProps.options, tableData);
            }
            if (
              list.component != 'CardGroup' &&
              list.component != 'Grid' &&
              list.component != 'MapGeom' &&
              list.component != 'Divider' &&
              list.component != 'Slider' &&
              list.component != 'Card' &&
              list.component != 'Location' &&
              list.field.indexOf('use_card') === -1
            ) {
              tabArr.push(list.componentProps.fieldName);
              if (!list.componentProps.fieldName) {
                tabLabelArr.push(list.label);
              }
            }
          });
        });
      }
    });
    // 将Card的孩子改成和Card同级别
    designTab.schemas = changeCardStructure(designTab.schemas);
    let tabList: any = [];
    if (designTab.schemas.length > 1) {
      tabList.push({
        text: '',
        schemas: [],
      });
      designTab.schemas.forEach((item) => {
        tabList[0].schemas.push(item);
      });
    } else {
      designTab.schemas[0].componentProps?.options?.forEach((item) => {
        tabList.push({
          text: item.label,
          schemas: item.children,
        });
      });
    }
    designTab.tabList = tabList;
    delete designTab.schemas;
    schems.primaryKey = primaryKey.value;
    schems.formInfo = designTab;
    // 表结构配置
    tableCallBack(schems, tabArr, tabLabelArr);
  }
  function changeCloums(columns, tableData) {
    columns.forEach((item) => {
      if (item.children && item.children.length > 0) {
        item.children.forEach((childItem) => {
          tableData.forEach((element) => {
            if (element.name == childItem.componentProps.dataTable) {
              var currentIndex = element.data.findIndex(
                (dataChildItem) =>
                  dataChildItem.dbColumnName === childItem.componentProps.fieldName,
              );
              childItem.csType = element.data[currentIndex].csType;
              if (childItem.csType == 'int') {
                if (
                  childItem.componentProps.options &&
                  childItem.componentProps.options.length > 0
                ) {
                  childItem.componentProps.options.forEach((optionChild) => {
                    optionChild.value = Number(optionChild.value);
                  });
                }
              }
            }
          });
          if (childItem.component === 'CardGroup') {
            childItem.componentProps.options = changeCloums(
              childItem.componentProps.options,
              tableData,
            );
          } else if (childItem.columns) {
            childItem.columns = changeCloums(childItem.columns, tableData);
          }
        });
      }
    });
    return columns;
  }
  function tableCallBack(schems, tabArr, tabLabelArr) {
    if (saveFormDatas.value.info.formType == 2 && !isStageClick.value) {
      // 自动建表+保存
      if (isAddVisible.value) {
        if (schems.db.length == 0) {
          schems.db.push({
            name: 'table' + new Date().getTime(),
            type: 'main',
            tableName: 'table' + new Date().getTime(),
            description: '主表',
          });
        }
      }
      saveFormDatas.value.scheme.scheme = JSON.stringify(schems);
      openModal(true, { saveFormDatas: saveFormDatas.value });
    } else if (saveFormDatas.value.info.formType == 2 && isStageClick.value) {
      // 自动建表+暂存
      setTimeout(async () => {
        if (isAddVisible.value) {
          schems.db = [];
          schems.db.push({
            name: 'table' + new Date().getTime(),
            type: 'main',
            tableName: 'table' + new Date().getTime(),
            description: '主表',
          });
        } else {
          formScheme_id = formScheme_id ? formScheme_id : saveFormDatas.value.info.id;
          let query: any = { id: formScheme_id };
          let result: any = await functionGetForm(query);
          let result_json = JSON.parse(result.scheme.scheme);
          schems.db = result_json.db;
        }
        // saveFormDatas.value.scheme.scheme = JSON.stringify(schems);
        console.log('自动建表暂存');
        submitSaveClick(schems);
      }, 500);
    } else if (tabArr.includes(undefined)) {
      message.warning('请' + tabLabelArr[0] + '绑定数据表字段！', 2);
    } else {
      console.log('正常提交');
      // saveFormDatas.value.scheme.scheme = JSON.stringify(schems);
      setTimeout(() => {
        // console.log(schems);
        submitSaveClick(schems);
      }, 500);
    }
  }
  provide('designSendGrandson', designSendGrandson);

  let editCreateUserName: string = '';

  const [registerModal, { closeModal }] = useModalInner((data: any) => {
    stepsCurrent.value = 0;
    isSubmitClick.value = false;
    isStageClick.value = false;

    if (data.id) {
      formScheme_id = data.id;
      formScheme_type = data.type;
      editCreateUserName = data.createUserName;
      isAddVisible.value = false;
      getBaseConfigList({ id: data.id }).then((res: Recordable) => {
        formScheme.value = res;
        saveFormDatas.value = res;
      });
    } else {
      isAddVisible.value = true;
      formScheme.value = {
        info: {},
        scheme: {},
      };
      saveFormDatas.value = {
        info: {},
        scheme: {},
      };
    }
  });

  // 表结构配置弹窗
  const [automaticModal, { openModal }] = useModal();

  function automaticModalSubmitsuccess(value) {
    saveFormDatas.value = value;
    submitSaveClick(null);
  }

  let stepsCurrent = ref();
  let isNextSteps = ref(false);
  let isSubmitClick = ref(false);
  let isStageClick = ref(false);

  function formNextClick() {
    isNextSteps.value = true;
    isSubmitClick.value = false;
    isStageClick.value = false;
  }
  function formPrevClick() {
    isNextSteps.value = false;
    stepsCurrent.value = 0;
  }

  function closeModalClick() {
    stepsCurrent.value = 1;
    formScheme = ref();
    isNextSteps.value = false;
    closeModal();
  }
  function formDataNoBack() {
    isNextSteps.value = false;
  }
  function formDataBack(data) {
    if (isStageClick.value && stepsCurrent.value === 0) {
      stepsCurrent.value = 0;
    } else {
      stepsCurrent.value = 1;
    }
    let arr: any[] = [];
    if (data.table) {
      data.table.forEach((item) => {
        arr.push({
          field: item.field,
          name: item.name,
          relationField: item.relationField,
          relationName: item.relationName,
          type: item.type,
        });
      });
    }
    let params = {
      dbCode: data.form.DbCode,
      tableNames: data.table[0].name,
    };
    getOutKeyList(params).then((res: Recordable) => {
      res[0]?.db_codecolumnsList.forEach((item) => {
        if (item.isPrimaryKey == 1) {
          primaryKey.value = item.dbColumnName;
        }
      });
    });
    if (isAddVisible.value) {
      //新增
      let schems;
      if (saveFormDatas.value.scheme.scheme) {
        schems = JSON.parse(saveFormDatas.value.scheme.scheme) || {
          db: arr,
          rdb: data.connect || [],
          dbCode: data.form.DbCode,
          formInfo: {},
        };

        schems.db = arr;
        (schems.rdb = data.connect || []), (schems.dbCode = data.form.DbCode);
      } else {
        schems = {
          db: arr,
          rdb: data.connect || [],
          dbCode: data.form.DbCode,
          formInfo: {},
        };
      }
      let loginUser = localStorage.getItem('fireUserLoginName');
      saveFormDatas.value.info = data.form;
      saveFormDatas.value.info.createUserName = loginUser;
      if (isStageClick.value) {
        saveFormDatas.value.info.type = 2;
        saveFormDatas.value.scheme.type = 2;
        editCreateUserName = loginUser || '';
      } else {
        saveFormDatas.value.info.type = 1;
        saveFormDatas.value.scheme.type = 1;
      }
      saveFormDatas.value.scheme.scheme = JSON.stringify(schems);
    } else {
      //编辑
      let schems = JSON.parse(saveFormDatas.value.scheme.scheme);
      // 将Card同级嵌套起来
      schems.formInfo.tabList = cardNestStructure(schems.formInfo.tabList);
      schems.db = arr;
      (schems.rdb = data.connect || []), (saveFormDatas.value.info.category = data.form.category);
      saveFormDatas.value.info.description = data.form.description;
      saveFormDatas.value.info.enabledMark = data.form.enabledMark;
      saveFormDatas.value.info.name = data.form.name;
      saveFormDatas.value.info.DbCode = data.form.DbCode;
      saveFormDatas.value.info.formType = data.form.formType;
      saveFormDatas.value.info.createUserName = editCreateUserName;
      saveFormDatas.value.info.createDate = data.form.createDate;
      saveFormDatas.value.scheme.scheme = JSON.stringify(schems);
      saveFormDatas.value.scheme.type = 1;
    }
  }
  // 自动建表返回后，保存数据
  function automaticFormDataBack(data) {
    if (isStageClick.value && stepsCurrent.value === 0) {
      stepsCurrent.value = 0;
    } else {
      stepsCurrent.value = 1;
    }
    let arr: any[] = [];

    if (isAddVisible.value) {
      //新增
      let schems;
      if (saveFormDatas.value.scheme.scheme) {
        schems = JSON.parse(saveFormDatas.value.scheme.scheme) || {
          db: arr,
          rdb: data.connect || [],
          dbCode: data.form.DbCode,
          formInfo: {},
        };

        schems.db = arr;
        (schems.rdb = data.connect || []), (schems.dbCode = data.form.DbCode);
      } else {
        schems = {
          db: arr,
          rdb: data.connect || [],
          dbCode: data.form.DbCode,
          formInfo: {},
        };
      }
      let loginUser = localStorage.getItem('fireUserLoginName');
      saveFormDatas.value.info = data.form;
      saveFormDatas.value.info.createUserName = loginUser;
      if (isStageClick.value) {
        saveFormDatas.value.info.type = 2;
        saveFormDatas.value.scheme.type = 2;
        editCreateUserName = loginUser || '';
      } else {
        saveFormDatas.value.info.type = 1;
        saveFormDatas.value.scheme.type = 1;
      }
      saveFormDatas.value.scheme.scheme = JSON.stringify(schems);
    } else {
      //编辑
      let schems = JSON.parse(saveFormDatas.value.scheme.scheme);
      schems.db = arr;
      (schems.rdb = data.connect || []), (saveFormDatas.value.info.category = data.form.category);
      saveFormDatas.value.info.description = data.form.description;
      saveFormDatas.value.info.enabledMark = data.form.enabledMark;
      saveFormDatas.value.info.name = data.form.name;
      saveFormDatas.value.info.DbCode = data.form.DbCode;
      saveFormDatas.value.info.formType = data.form.formType;
      saveFormDatas.value.info.createUserName = editCreateUserName;
      saveFormDatas.value.info.createDate = data.form.createDate;
      saveFormDatas.value.scheme.scheme = JSON.stringify(schems);
      saveFormDatas.value.scheme.type = 1;
    }
  }

  function submitClick() {
    isSubmitClick.value = true;
    isStageClick.value = false;
  }
  function stageClick() {
    isSubmitClick.value = true;
    isStageClick.value = true;
  }
  function designformback() {
    isSubmitClick.value = false;
  }
  function submitSaveClick(schems) {
    if (schems) {
      saveFormDatas.value.scheme.scheme = JSON.stringify(schems);
    }
    if (!saveFormDatas.value.info.type) {
      isStageClick.value = false;
      isSubmitClick.value = false;
      return;
    }
    let param = {
      info: saveFormDatas.value.info,
      scheme: saveFormDatas.value.scheme,
    };
    // 草稿状态下暂存，再暂存还是草稿状态
    if (isStageClick.value && param.info.type == 2) {
      param.scheme.type = formScheme_type ? formScheme_type : 2;
    }
    if (isAddVisible.value) {
      addFormDesignData(param).then((res: Recordable) => {
        if (!isStageClick.value) {
          closeModalClick();
          isAddVisible.value = false;
        } else {
          isAddVisible.value = false;
          getBaseConfigList({ id: res }).then((res: Recordable) => {
            formScheme.value = res;
            saveFormDatas.value = res;
          });
        }
        message.success('操作成功', 2);
        emit('submitsuccess');
      });
    } else {
      editFormDesignData(param).then((res: Recordable) => {
        if (!isStageClick.value) {
          closeModalClick();
        }
        message.success('操作成功', 2);
        emit('submitsuccess');
        console.log(res);
        isStageClick.value = false;
      });
    }
  }

  const prefixCls = 'form-box';
</script>
<style lang="less" scoped>
  .form-box {
    position: fixed;
    z-index: 1111;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: @component-background;

    &-header {
      height: 55px;

      &-logo {
        margin-left: 20px;
        font-size: 18px;
        font-weight: bold;
        line-height: 55px;
      }

      &-stepsBox {
        display: flex;
        position: fixed;
        top: 0;
        left: 50%;
        align-items: center;
        width: 320px;
        height: 56px;
        margin-left: -160px;
      }

      &-btnBox {
        display: flex;
        position: fixed;
        top: 0;
        right: 10px;
        align-items: center;
        justify-content: space-around;
        width: 380px;
        height: 56px;
      }
    }

    &-content {
      height: calc(100% - 55px);
      padding: 10px;
      background-color: @component-background;
    }
  }
</style>
