<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    fullscreen
    switchFullscreen
    @ok="handleOk"
    :okButtonProps="{ class:{'jee-hidden': disableSubmit} }"
    @cancel="handleCancel"
    cancelText="关闭1">

    <template v-slot:footer>
      <a-button @click="handleCancel">关闭</a-button>
      <a-button key="submit" type="primary" :loading="confirmLoading" @click="handleOk">保存</a-button>
    </template>

    <a-spin :spinning="confirmLoading">
      <j-form-container :disabled="disableSubmit">

      </j-form-container>
    </a-spin>

    <a-form :form="form" class="online-config-cust">

      <a-list>
        <a-list-item>
          <a-row style="width: 100%">
            <a-col :span="24" layout="inline">
              <a-row style="width: 100%" :gutter="gutter">
                <a-col :span="8">
                  <a-form-item style="width: 100%"
                               :labelCol="threeCol.label"
                               :wrapperCol="threeCol.wrapper"
                               label="稽核名称">
                    <a-input v-decorator="['tableName', validatorRules.tableName ]" :readOnly="editPageFlag" placeholder="请输入稽核名称"></a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item style="width: 100%"
                               :labelCol="threeCol.label"
                               :wrapperCol="threeCol.wrapper"
                               label="稽核描述">
                    <a-input v-decorator="['tableTxt', validatorRules.tableTxt ]" :readOnly="editPageFlag" placeholder="请输入稽核描述"></a-input>
                  </a-form-item>
                </a-col>
              </a-row>

              <a-row style="width: 100%" :gutter="gutter">
                <a-col :span="8">
                  <a-form-item style="width: 100%"
                               :labelCol="threeCol.label"
                               :wrapperCol="threeCol.wrapper"
                               label="任务模式">
                    <a-select v-decorator="[ 'isTree1', {initialValue: 'N'}]">
                      <a-select-option value="Y">有</a-select-option>
                      <a-select-option value="N">无</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item style="width: 100%"
                               :labelCol="threeCol.label"
                               :wrapperCol="threeCol.wrapper"
                               label="导入功能">
                    <a-select v-decorator="[ 'isPage1', {initialValue: 'N'}]">
                      <a-select-option value="Y">有</a-select-option>
                      <a-select-option value="N">无</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item style="width: 100%"
                               :labelCol="threeCol.label"
                               :wrapperCol="threeCol.wrapper"
                               label="菜单排序">
                    <a-input-number v-decorator="['sortIndex', {initialValue: 10}]" placeholder="请输入菜单排序"></a-input-number>
                  </a-form-item>
                </a-col>
              </a-row>


              <a-row style="width: 100%" :gutter="gutter" v-show="false">
                <a-col :span="8">
                  <a-form-item style="width: 100%"
                               :labelCol="threeCol.label"
                               :wrapperCol="threeCol.wrapper"
                               label="表名">
                    <a-input v-decorator="['tableName3', validatorRules.tableName ]" :readOnly="editPageFlag" placeholder="请输入表名"></a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item style="width: 100%"
                               :labelCol="threeCol.label"
                               :wrapperCol="threeCol.wrapper"
                               label="表描述">
                    <a-input v-decorator="['tableTxt3', validatorRules.tableTxt ]" :readOnly="editPageFlag" placeholder="请输入表描述"></a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item style="width: 100%"
                               :labelCol="threeCol.label"
                               :wrapperCol="threeCol.wrapper"
                               label="表类型">
                    <a-select v-decorator="[ 'tableType', {initialValue: 1}]">
                      <a-select-option :value="1">单表</a-select-option>
                      <a-select-option :value="2">主表</a-select-option>
                      <a-select-option :value="3">附表</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>

                <a-col :span="8">
                  <a-form-item style="width: 100%"
                               :labelCol="threeCol.label"
                               :wrapperCol="threeCol.wrapper"
                               label="表类型">
                    <a-radio-group v-decorator="[ 'relationType', {initialValue:0}]">
                      <a-radio :value="0">一对多</a-radio>
                      <a-radio :value="1">一对一</a-radio>
                    </a-radio-group>
                  </a-form-item>
                </a-col>

                <a-col :span="8">
                  <a-form-item style="width: 100%"
                               :labelCol="threeCol.label"
                               :wrapperCol="threeCol.wrapper"
                               label="序号">
                    <a-input-number v-decorator="[ 'tabOrderNum', validatorRules.tabOrderNum]" placeholder="请输入序号">
                    </a-input-number>
                  </a-form-item>
                </a-col>
              </a-row>

              <a-row style="width: 100%" :gutter="gutter" v-show="false">
                <a-col :span="8">
                  <a-form-item style="width: 100%"
                               :labelCol="threeCol.label"
                               :wrapperCol="threeCol.wrapper"
                               label="表单分类">
                    <j-dict-select-tag v-decorator="[ 'formCategory', {initialValue: 'temp'}]"
                                       dictCode="ol_form_biz_type"
                                       placeholder="请选择"
                    ></j-dict-select-tag>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item style="width: 100%"
                               :labelCol="threeCol.label"
                               :wrapperCol="threeCol.wrapper"
                               label="主键策略">
                    <a-select v-decorator="[ 'idType', {initialValue: 'UUID'}]" @change="handleChangeInIdType">
                      <a-select-option value="UUID">ID_WORKER(分布式自增)</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>

                <a-col :span="8">
                  <a-form-item style="width: 100%"
                               :labelCol="threeCol.label"
                               :wrapperCol="threeCol.wrapper"
                               label="显示复选框">
                    <a-select v-decorator="[ 'isCheckbox', {initialValue: 'Y'}]" @change="handleChangeInIdType">
                      <a-select-option value="Y">是</a-select-option>
                      <a-select-option value="N">否</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>

              </a-row>


              <a-row style="width: 100%" :gutter="gutter" v-show="false">
                <a-col :span="8">
                  <a-form-item style="width: 100%"
                               :labelCol="threeCol.label"
                               :wrapperCol="threeCol.wrapper"
                               label="主题模板">
                    <a-select v-decorator="[ 'themeTemplate',validatorRules.themeTemplate,]" placeholder="请选择主题模板">
                      <a-select-option value="normal">默认主题</a-select-option>
                      <a-select-option value="erp">ERP主题(一对多)</a-select-option>
                      <a-select-option value="innerTable">内嵌子表主题(一对多)</a-select-option>
                      <a-select-option value="tab">TAB主题(一对多)</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item style="width: 100%"
                               :labelCol="threeCol.label"
                               :wrapperCol="threeCol.wrapper"
                               label="表单风格">
                    <a-select v-decorator="[ 'formTemplate',{initialValue:'1'}]" pleceholder="请选择PC表单风格">
                      <a-select-option value="1">一列</a-select-option>
                      <a-select-option value="2">两列</a-select-option>
                      <a-select-option value="3">三列</a-select-option>
                      <a-select-option value="4">四列</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item style="width: 100%"
                               :labelCol="threeCol.label"
                               :wrapperCol="threeCol.wrapper"
                               label="滚动条">
                    <a-select v-decorator="[ 'scroll', {initialValue: 1}]" >
                      <a-select-option :value="1">有</a-select-option>
                      <a-select-option :value="0">无</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>

              </a-row>


              <a-row style="width: 100%" :gutter="gutter" v-show="false">
                <a-col :span="8">
                  <a-form-item style="width: 100%"
                               :labelCol="threeCol.label"
                               :wrapperCol="threeCol.wrapper"
                               label="是否分页">
                    <a-select v-decorator="[ 'isPage', {initialValue: 'Y'}]" placeholder="请选择主题模板">
                      <a-select-option value="Y">是</a-select-option>
                      <a-select-option value="N">否</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item style="width: 100%"
                               :labelCol="threeCol.label"
                               :wrapperCol="threeCol.wrapper"
                               label="是否树">
                    <a-select v-decorator="[ 'isTree', {initialValue: 'N'}]" @change="handleChangeInIsTree">
                      <a-select-option value="Y">是</a-select-option>
                      <a-select-option value="N">否</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>


              </a-row>


            </a-col>
          </a-row>
        </a-list-item>


      </a-list>

      <a-tabs defaultActiveKey="1" @change="handleChangeInTabs" v-model="activeKey">
        <a-tab-pane tab="稽核属性" key="1" :forceRender="true">
          <db-attribute-table
            ref="table1"
            @added="handleAdded"
            @deleted="handleDeleted"
            @dragged="handleDragged"
            @inserted="handleInserted"
            @syncDbType="handleSyncDbType"
          ></db-attribute-table>
        </a-tab-pane>
        <a-tab-pane tab="页面属性" key="2" :forceRender="true">
          <page-attribute-table ref="table2"></page-attribute-table>
        </a-tab-pane>
        <a-tab-pane tab="校验字段" key="3" :forceRender="true">
          <check-dict-table ref="table3"></check-dict-table>
        </a-tab-pane>
        <a-tab-pane tab="外键" key="4" :forceRender="true">
          <foreign-key-table ref="table4"></foreign-key-table>
        </a-tab-pane>
        <a-tab-pane tab="索引" key="5" :forceRender="true">
          <index-table ref="table5"></index-table>
        </a-tab-pane>
        <a-tab-pane tab="查询配置" key="6" :forceRender="true">
          <query-table ref="table6"></query-table>
        </a-tab-pane>
        <a-tab-pane tab="分组配置" key="7" :forceRender="true">
          <filed-group-table
            ref="table7"
            @added="handleGroupAdded"
            @deleted="handleGroupDeleted"
          ></filed-group-table>
        </a-tab-pane>
      </a-tabs>

    </a-form>
  </j-modal>
</template>



<script>

import {randomUUID, simpleDebounce} from '@/utils/util'
import { httpAction,getAction } from '@api/manage'

import DbAttributeTable from "@views/codegen/form/tables/DbAttributeTable";
import PageAttributeTable from "@views/codegen/form/tables/PageAttributeTable";
import CheckDictTable from "@views/codegen/form/tables/CheckDictTable";
import ForeignKeyTable from "@views/codegen/form/tables/ForeignKeyTable";
import IndexTable from "@views/codegen/form/tables/IndexTable";
import QueryTable from "@views/codegen/form/tables/QueryTable";
import FiledGroupTable from "@views/codegen/form/tables/FiledGroupTable";
import {getMasterTableInitialData,setDataSource} from "@views/codegen/form/util/TableUtils";

export default {
  name: 'FormHeadModal',
  components: {
    DbAttributeTable: DbAttributeTable,
    PageAttributeTable: PageAttributeTable,
    CheckDictTable: CheckDictTable,
    ForeignKeyTable: ForeignKeyTable,
    IndexTable: IndexTable,
    QueryTable: QueryTable,
    FiledGroupTable: FiledGroupTable,
  },
  provide: function () {
    return {
      getAllTable: this.getAllTable
    }
  },
  data () {
    let self = this;
    return {
      description: '添加页面',
      title: '',
      width: 960,
      visible: false,
      activeKey: "1",
      disableSubmit: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      model:{
      },
      gutter: 8,
      oneCol: {
        label: {span: 2},
        wrapper: {span: 22}
      },
      threeCol: {
        label: {span: 6},
        wrapper: {span: 18}
      },
      syncAllTableNowDebounce: simpleDebounce(() =>{
        self.syncAllTableNowPromise()
      }, 150),
      editPageFlag: false,
      validatorRules : {
        tableName : {
          rules : [{
            required : true,
            message : "请输入表名!"
          }, {
            validator : this.validateTableName
          }]
        },
        tableTxt : {
          rules : [{
            required : true,
            message : "请输入表说明!"
          }]
        },
        idSequence : {
          rules : [{
            required : true,
            message : "请输入序号名称!"
          }]
        },
        treeParentIdField : {
          rules : [{
            required : true,
            message : "请输入树表单父ID!"
          }]
        },
        treeFieldname : {
          rules : [{
            required : true,
            message : "请输入树开表单列!"
          }]
        },
        treeIdField : {
          rules : [{
            required : true,
            message : "请输入是否有子节点字段名!"
          }]
        },
        tabOrderNum : {
          initialValue : 1,
          rules : [{
            required : true,
            message : "请输入序号！"
          }]
        },
        themeTemplate : {
          initialValue : "normal",
          rules : [{
            validator : this.validateThemeTemplate
          }]
        }
      },
      url : {
        add : "/online/form/head/add",
        edit : "/online/form/head/edit",
        addAll : "/online/form/api/addAll",
        editAll : "/online/form/api/editAll",
        queryField : "/online/form/field/listByHeadId",
        queryIndex : "/online/form/index/listByHeadId",
        checkOnlyTable : "/online/form/api/checkOnlyTable"
      },
    }
  },
  created () {
    // 备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model));
  },
  methods: {
    /**
     * 通过 ref 引用获取 Promise 对象
     * @param refKey 名称
     * @returns Promise 对象
     */
    getRefPromise(refKey) {
      let _self = this;
      return new Promise((resolve) => {
        (function next() {
          let table = _self.$refs[refKey];
          if (table) {
            resolve(table)
          } else {
            setTimeout(() => next(), 10);
          }
        })()
      })
    },
    /**
     * 获取所有表格引用 Promise对象
     * @returns Promise
     */
    getAllTable() {
      return Promise.all([
        this.getRefPromise("table1"),
        this.getRefPromise("table2"),
        this.getRefPromise("table3"),
        this.getRefPromise("table4"),
        this.getRefPromise("table5"),
        this.getRefPromise("table6"),
      ])
    },
    /**
     * 初始化所有表格
     */
    initialAllTable() {
      this.getAllTable().then((tables) => {
        tables.forEach((table) => {
          table.$refs.editableTable.initialize()
        })
      })
    },
    handleOk () {
      this.submitForm();
    },
    handleCancel () {
      this.visible = false;
    },
    add () {
      // this.edit(this.modelDefault);
      let self = this;
      this.treeFieldAdded = false
      this.editPageFlag = false

      this.getAllTable().then(tables => {
        let table1 = tables[0];
        let table2 = tables[1];
        let table3 = tables[2];
        let table4 = tables[3];
        let table6 = tables[5];

        let master = getMasterTableInitialData();
        // 设置表id
        let fieldTempIds = [];
        master.forEach((item, index) => {
          item.id = randomUUID();
          fieldTempIds.push(item.id);
        })
        self.fieldTempIds = fieldTempIds

        setTimeout((function () {
          setTimeout((function () {
            setDataSource(table2, master);
            setDataSource(table3, master);
            setDataSource(table4, master);
            setDataSource(table6, master);
          }), 1)
          setDataSource(table1, master);
        }), 1)
      }).catch(error => {
        console.log(error);
      })

      this.edit({}, "add")
    },
    edit (record) {
      this.model = Object.assign({}, record);
      this.visible = true;

      let self = this;
      let action = "";
      if (arguments.length > 1 && void 0 !== arguments[1]) {
        action = arguments[1];
      }
      this.metaTableName = ""
      this.visible = true
      this.initialAllTable()
      this.activeKey = "1"
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.treeFieldAdded = "Y" === record.isTree;

      // 获取model 中的指定字段
      let filterModel = this.$Jpick(this.model,
        "tableName","tableTxt"
        // "themeTemplate", "tableName", "scroll",
        // "tableType", "tableVersion", "tableTxt",
        // "isCheckbox", "isDbSynch", "isPage", "isTree",
        // "idSequence", "idType", "queryMode",
        // "relationType", "subTableStr", "tabOrderNum",
        // "treeParentIdField", "treeIdField",
        // "treeFieldname", "formCategory", "formTemplate",
        // "formTemplateMobile", "isDesForm", "desFormCode",
        // "extConfigJson"
      );
      // this.tableJsonGetHelper(filterModel)
      // this.initialAllShowItem(filterModel)
      this.$nextTick(function () {
        self.form.setFieldsValue(filterModel)
        self.metaTableName = filterModel["tableName"]
      })

      if ("add" !== action) {
        this.tableLoading = true
        this.editPageFlag = this.model.tableVersion !== 1

        Promise.all([
          getAction(this.url.queryField, {headId: this.model.id}),
          this.getRefPromise('table1'),
          this.getRefPromise('table2'),
          this.getRefPromise('table3'),
          this.getRefPromise('table4'),
          this.getRefPromise('table6'),
        ]).then(value => {
          let fieldList = value[0].resultList;
          let table1 = value[1];
          let table2 = value[2];
          let table3 = value[3];
          let table4 = value[4];
          let table6 = value[5];

          // self.fieldsJsonGetHelper();
          table1.deleteIds = [];
          table1.selectedRowKeys = [];
          setDataSource(table1, fieldList, true);
          setTimeout(()=> {
            setDataSource(table2, fieldList);
            setDataSource(table3, fieldList);
            setDataSource(table4, fieldList);
            setDataSource(table6, fieldList);
          },100);
        }).catch(reason => {

        }).then(() => {
          self.tableLoading = false;
        });

        Promise.all([
          getAction(this.url.queryIndex,{headId : this.model.id}),
          this.getRefPromise('table5'),
        ]).then(value => {
          let indexList = value[0].result;
          let table5 = value[1];
          setDataSource(table5, indexList);
        }).catch(reason => {

        });


      }

    },
    /**
     * tab 切换事件
     * @param key
     */
    handleChangeInTabs(key) {
      // 切换至 2,3,4,5,6 时执行同步
      if (["2", "3", "4", "5", "6"].indexOf(key) !== -1) {
        // 并行执行多个异步操作，所有异步操作执行成功后才执行回调
        let syncTables = [this.getRefPromise("table1"), this.getRefPromise("table".concat(key))];
        Promise.all(syncTables)
          .then(tables => {
            // tables 即Promise.all 传入的参数
            let dbTable = tables[0]
            let target = tables[1]
            dbTable.$refs.editableTable.resetScrollTop()
            target.syncTable(dbTable)
          })
      }
      // 同步分组
      if (["2"].indexOf(key) !== -1) {
        this.getRefPromise("table7").then(table => {
          return table.getGroupList();
        }).then(groupList => {
          this.getRefPromise("table2").then((table) => {
            table.changeGroupOption(groupList);
          });
        });
      }
    },
    /**
     * 同步所有表立即执行并返回Promise 对象
     *
     * @returns 返回Promise 对象
     */
    syncAllTableNowPromise() {
      return this.getAllTable()
        .then((tables) => {
          return new Promise(() => {
            let table1 = tables[0];
            let table2 = tables[1];
            let table3 = tables[2];
            let table4 = tables[3];
            let table5 = tables[4];
            let table6 = tables[5];
            table2.syncTable(table1);
            table3.syncTable(table1);
            table4.syncTable(table1);
            table6.syncTable(table1);
          })
        })
    },
    syncAllTableNow() {
      this.syncAllTableNowDebounce()
    },
    handleAdded() {
      this.syncAllTableNow()
    },
    handleDeleted() {
      this.syncAllTableNow()
    },
    handleDragged(item) {
      this.syncAllOrderNumNow(item.oldIndex, item.newIndex)
    },
    handleInserted: function (item) {
      let self = this;
      let newIndex = item.insertIndex;
      let target = item.target;
      let rows = item.rows;
      this.syncAllTableNowPromise()
        .then((function (e) {
          for (let row of rows) {
            let oldIndex = target.$refs.editableTable.rows.length - 1;
            self.syncAllOrderNumNow(oldIndex, newIndex);
          }
        }))
    },
    syncAllOrderNumNow(oldIndex, newIndex) {
      this.getAllTable().then(tables => {
        tables.forEach((table, index) => {
          // 1,2,3,5 是页面属性，校验字段，外键，查询配置等
          if ([1, 2, 3, 5].includes(index) ) {
            table.$refs.editableTable.rowResort(oldIndex, newIndex)
          }
        })
      })
    },
    handleSyncDbType(data) {
      this.getRefPromise("table2").then((table) => {
        table.syncFieldShowType(data.row)
      })
    },
    initialAllShowItem(data) {
      this.handleChangeInTableType(data.tableType || 1);
      this.handleChangeInIsTree(data.isTree || "N");
      this.handleChangeInIdType(data.idType || "UUID");
      this.showSubTable = 2 === (data.tableType || 1);
      this.extConfigJson = {
        reportPrintShow : 0,
        reportPrintUrl : "",
        joinQuery : 0,
        modelFullscreen : 0,
        modalMinWidth : ""
      };
      let t = {};
      if (data.extConfigJson) {
        try {
          t = JSON.parse(data.extConfigJson);
        } catch (n) {
        }
      }
      this.extConfigJson = Object.assign({}, this.extConfigJson, t, {
        isDesForm : data.isDesForm || "N",
        desFormCode : data.desFormCode || ""
      });
    },
    handleChangeInTableType (type) {
      if (type === 1) {
        this.templateFlag = true
        this.form.setFieldsValue({themeTemplate: "normal"})
      } else {
        this.templateFlag = false
      }
      this.showRelationType = type === 3
      this.getRefPromise("table2").then((function (t) {
        t.changePageType(type === 3)
      }))
    },
    handleChangeInIsTree : function(obj) {
      this.showTreeParentIdField = "Y" === obj;
      if ("Y" === obj) {
        this.addTreeNeedField();
      } else {
        this.deleteTreeNeedField();
      }
    },
    handleChangeInIdType : function(obj) {
      this.showIdSequence = "SEQUENCE" === obj;
    },
    handleGroupAdded() {
      this.getRefPromise("table7").then((table) => {
        // console.log('table7',table.getGroupList())
      })
    },
    handleGroupDeleted() {
      this.getRefPromise("table7").then((table) => {
        // console.log('table7',table.getGroupList())
      })
    },
  }
}

</script>

<style scoped>

</style>