<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`"> 慧创 表单设计 </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"
        />
      </div>
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, provide, computed } from 'vue';
  import { message } from 'ant-design-vue';

  import { BasicModal, useModalInner } from '@/components/Modal';
  import FormPage from './form/index.vue';
  import FormDesign from '../../form-design/index.vue';
  import {
    getBaseConfigList,
    addFormDesignData,
    editFormDesignData,
    getOutKeyList,
  } from '@/api/formdesign/index';

  defineOptions({ name: 'FormModal' });

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

  let formScheme = ref();

  let saveFormDatas: any = ref({});
  const primaryKey: any = ref();
  provide(
    'handleNextStepsData',
    computed(() => saveFormDatas.value),
  );

  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 tabArr: any = [];
    let tabLabelArr: any = [];
    designTab.schemas.forEach((item) => {
      if (item.componentProps.defaultValue) {
        item.defaultValue = item.componentProps.defaultValue;
      }
      if (item.componentProps.fieldName) {
        let params = {
          dbCode: schems.dbCode,
          tableNames: item.componentProps.dataTable,
        };
        getOutKeyList(params).then((res: Recordable) => {
          res[0].db_codecolumnsList.forEach((val) => {
            if (item.componentProps.fieldName == val.dbColumnName) {
              item.csType = val.csType;
            }
          });
        });
      }
      tabArr.push(item.componentProps.fieldName);
      if (!item.componentProps.fieldName) {
        tabLabelArr.push(item.label);
      }
    });
    schems.primaryKey = primaryKey.value;
    schems.formInfo = designTab;
    if (tabArr.includes(undefined)) {
      message.warning('请' + tabLabelArr[0] + '绑定数据表字段！', 2);
    } else {
      setTimeout(() => {
        saveFormDatas.value.scheme.scheme = JSON.stringify(schems);
        submitSaveClick();
      }, 100);
    }
  }
  provide('designSendGrandson', designSendGrandson);

  let editCreateUserName: string = '';

  const [registerModal, { closeModal }] = useModalInner((data: any) => {
    stepsCurrent.value = 0;
    isSubmitClick.value = false;
    isStageClick.value = false;
    if (data.id) {
      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: {},
      };
    }
  });

  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);
      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() {
    if (!saveFormDatas.value.info.type) {
      isStageClick.value = false;
      isSubmitClick.value = false;
      return;
    }
    let param = {
      info: saveFormDatas.value.info,
      scheme: saveFormDatas.value.scheme,
    };
    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>
