<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label-width="100px" label="动态组名称" prop="fGName">
        <el-input
          v-model="queryParams.fGName"
          placeholder="请输入动态组名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="当前表单组中所绑定的表单" prop="formKeys">
        <el-input
          v-model="queryParams.formKeys"
          placeholder="请输入当前表单组中所绑定的表单"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="主表名称" prop="mainTable">
        <el-input
          v-model="queryParams.mainTable"
          placeholder="请输入表单组主表名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="更新人编号" prop="updateById">
        <el-input
          v-model="queryParams.updateById"
          placeholder="请输入更新人编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="创建人编号" prop="createById">
        <el-input
          v-model="queryParams.createById"
          placeholder="请输入创建人编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="addHandler"
          v-hasPermi="['system:formGroup:add']"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:formGroup:edit']"
          >修改</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:formGroup:remove']"
          >删除</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:formGroup:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="formGroupList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="动态组名称" align="center" prop="fGName" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="当前表单组中所绑定的表单"
        align="center"
        prop="formKeys"
      />
      <el-table-column label="表单组主表名称" align="center" prop="mainTable" />
      <!-- <el-table-column
        label="各个表单之间的关系"
        align="center"
        prop="relationJson"
      /> -->
      <!-- <el-table-column label="回显数据sql" align="center" prop="showDataSql" />
      <el-table-column label="更新人编号" align="center" prop="updateById" />
      <el-table-column label="创建人编号" align="center" prop="createById" /> -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-dropdown>
            <el-button type="warning" plain size="small">
              处理<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                ><el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  >修改
                </el-button></el-dropdown-item
              >
              <el-dropdown-item
                ><el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handlePosition(scope.row)"
                  >设置布局
                </el-button></el-dropdown-item
              >
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  >删除
                </el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:formGroup:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:formGroup:remove']"
            >删除</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 表格组新增或编辑弹窗 -->
    <el-dialog
      :title="isEdit ? '修改表单组' : '新增表单组'"
      :visible.sync="isShow"
    >
      <el-form
        :model="groupForm"
        ref="groupFormRef"
        :rules="rules"
        label-width="80px"
        :inline="true"
        size="normal"
      >
        <el-form-item prop="fGName" label="组名称:">
          <el-input v-model="groupForm.fGName"></el-input>
        </el-form-item>
        <el-form-item prop="groupDesc" label="组描述:">
          <el-input v-model="groupForm.groupDesc"></el-input>
        </el-form-item>
        <el-form-item prop="mainFormName" label="主表单:">
          <el-select
            v-model="groupForm.mainFormName"
            placeholder="请选择主表单"
            clearable
            filterable
            @change="mainFormChange"
          >
            <el-option
              v-for="(item, index) in formOptionList"
              :key="index"
              :label="item.dfNickname"
              :value="item.formKey"
            >
              <span class="discribe" style="float: left">{{
                item.dfNickname
              }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                item.dfName
              }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label-width="100px" prop="mainFormItem" label="表单主键:">
          <el-select
            v-model="groupForm.mainFormItem"
            placeholder="请选择表单主键"
            clearable
            filterable
          >
            <el-option
              v-for="item in groupForm.mainFormItemOptions"
              :key="item.model"
              :label="item.label"
              :value="item.tableName + '.' + item.model"
            >
              <span class="discribe" style="float: left">{{ item.label }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                item.tableName + "." + item.model
              }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否显示" prop="isShow" size="normal">
          <el-switch
            v-model="groupForm.isShow"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text="是"
            inactive-text="否"
          >
          </el-switch>
        </el-form-item>
      </el-form>
      <el-divider content-position="center">从表单数据</el-divider>
      <el-table :data="subFormList" border stripe>
        <el-table-column type="index" width="50" />
        <el-table-column prop="formKey" label="从表单">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.formKey"
              placeholder="请选择表单"
              clearable
              filterable
              @change="subFormChangeHandler(scope.row)"
            >
              <el-option
                v-for="(item, index) in formOptionList"
                :key="index"
                :label="item.dfNickname"
                :value="item.formKey"
              >
                <span class="discribe" style="float: left">{{
                  item.dfNickname
                }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{
                  item.dfName
                }}</span>
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="formItem" label="子表单键">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.formItem"
              placeholder="请选择子表单键"
              clearable
              filterable
              @change="subFormItemChangeHandler(scope.row)"
            >
              <el-option
                v-for="item in scope.row.formItemList"
                :key="item.model"
                :label="item.label"
                :value="item.tableName + '.' + item.model"
              >
                <span class="discribe" style="float: left">{{
                  item.label
                }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{
                  item.tableName + "." + item.model
                }}</span>
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="mainFormItem" label="依赖的主表单键">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.relateMainItem"
              placeholder="请选择表单主键"
              clearable
              filterable
            >
              <el-option
                v-for="item in groupForm.mainFormItemOptions"
                :key="item.model"
                :label="item.label"
                :value="item.tableName + '.' + item.model"
              >
                <span class="discribe" style="float: left">{{
                  item.label
                }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{
                  item.tableName + "." + item.model
                }}</span>
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="isShow" label="是否展示">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.isShow"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="是"
              inactive-text="否"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="queryMap" label="查询条件">
          <template slot-scope="scope">
            <el-button
              type="info"
              size="small"
              @click="editHandler(scope.row, 'query', scope.$index)"
            >
              编辑条件
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="queryMap" label="插入条件">
          <template slot-scope="scope">
            <el-button
              type="info"
              size="small"
              @click="editHandler(scope.row, 'insert', scope.$index)"
            >
              编辑条件
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="small"
              @click="handleRemove(scope.$index, scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button
        class="mt10"
        icon="el-icon-plus"
        type="success"
        size="mini"
        @click="addOne"
      >
        新增
      </el-button>

      <template #footer>
        <span>
          <el-button @click="cancelHandler">取消</el-button>
          <el-button type="primary" @click="confirmHandler">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 条件弹窗 -->
    <el-dialog :title="conditionTitle" :visible.sync="queryShow">
      <el-table
        v-if="conditionTableShow"
        :data="conditionTableData"
        border
        stripe
      >
        <el-table-column type="index" width="50" />
        <el-table-column prop="fieldName" label="子表单键">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.fieldName"
              placeholder="请选择子表单键"
              clearable
              filterable
            >
              <el-option
                v-for="item in fieldOptions"
                :key="item.model"
                :label="item.label"
                :value="item.tableName + '.' + item.model"
              >
                <span class="discribe" style="float: left">{{
                  item.label
                }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{
                  item.tableName + "." + item.model
                }}</span>
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.type"
              placeholder="请选择类型"
              filterable
              @change="changeType(scope.row)"
            >
              <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="tableName" label="依赖表单">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.formKey"
              placeholder="请选择依赖表单"
              clearable
              filterable
              @change="changeTableName(scope.row)"
              :disabled="scope.row.type === 'defaultValue'"
            >
              <el-option
                v-for="item in relaTableOptions"
                :key="item.dfTableName"
                :label="item.dfName"
                :value="item.formKey"
              >
                <span class="discribe" style="float: left">{{
                  item.dfName
                }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{
                  item.dfTableName
                }}</span>
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="relaField" label="依赖字段">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.relaField"
              placeholder="请选择依赖字段"
              clearable
              filterable
              :disabled="scope.row.type === 'defaultValue'"
            >
              <el-option
                v-for="item in scope.row.mainFormItemList"
                :key="item.model"
                :label="item.label"
                :value="item.tableName + '.' + item.model"
              >
                <span class="discribe" style="float: left">{{
                  item.label
                }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{
                  item.tableName + "." + item.model
                }}</span>
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="refValue" label="默认值">
          <template slot-scope="scope">
            <el-input
              :disabled="scope.row.type === 'relateValue'"
              v-model="scope.row.refValue"
              placeholder="请输入默认值"
              clearable
            />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="danger"
              size="mini"
              @click="handleRemove(scope.$index, scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="btn-wrap">
        <el-button type="primary" size="mini" @click="addCondition">
          新增条件
        </el-button>
      </div>
      <template #footer>
        <span>
          <el-button @click="queryShow = false">取消</el-button>
          <el-button type="primary" @click="conditionConfirmHandler"
            >确认</el-button
          >
        </span>
      </template>
    </el-dialog>
    <!-- 布局弹窗 -->
    <el-dialog title="布局" :visible.sync="layoutShow" fullscreen>
      <DragPosition></DragPosition>
    </el-dialog>
  </div>
</template>

<script>
import { listForm } from "@/api/dragform/form";
import { getFormItems } from "@packages/bo-utils/getFormItems";
import {
  listFormGroup,
  getFormGroup,
  delFormGroup,
  addFormGroup,
  updateFormGroup,
} from "@/api/system/formGroup";
import { v4 as uuidv4 } from "uuid";
import { mapState } from "vuex";
import {
  getFormName,
  getListName,
  dragTablePreview,
} from "@/api/dragform/form.js";
import DragPosition from "./component/DragPosition.vue";

export default {
  name: "formRelateMange",
  props: [],
  components: { DragPosition },
  data() {
    return {
      // 弹窗相关数据
      isEdit: false, // 是否编辑
      isShow: false,
      editRow: {}, //当前编辑的行数据
      groupForm: {
        fGName: "", //组名称
        groupDesc: "", //组描述
        mainFormName: "", //主表单
        mainFormItem: "", //主表单主键
        mainFormTable: "", //主表单对应表格
        mainFormItemOptions: [], //主表单键选项
        groupKey: "", //组key
        isShow: true,
      },
      subFormList: [
        // {
        //   formKey: "", //从表单
        //   dfTableName: "", //从表名
        //   formItemList: [], //从表单键列表
        //   formItem: "", //从表单键
        //   relateMainItem: "", //依赖的主表单键
        // },
      ],
      formOptionList: [],

      // 模板参数
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 动态表单组表格数据
      formGroupList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fGName: null,
        formKeys: null,
        mainTable: null,
        relationJson: null,
        showDataSql: null,
        updateById: null,
        createById: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        fGName: [{ required: true, message: "请输入组名称", trigger: "blur" }],
        groupDesc: [
          { required: true, message: "请输入组描述", trigger: "blur" },
        ],
        mainFormName: [
          { required: true, message: "请选择主表表单", trigger: "change" },
        ],
        mainFormItem: [
          { required: true, message: "请选择表单主键", trigger: "change" },
        ],
      },
      //  查询条件数据
      // start
      flag: "", //query:查询条件  insert:插入条件
      editIndex: "",
      queryMap: {},
      queryShow: false,
      conditionTableData: [],
      conditionTitle: "",
      fieldOptions: [],
      relaTableOptions: [], //依赖
      typeOptions: [
        {
          label: "自定义值",
          value: "defaultValue",
        },
        {
          label: "依赖值",
          value: "relateValue",
        },
      ],
      conditionTableShow: true,
      // end
      // 布局数据  start
      layoutShow: false,
      // 布局数据  end
    };
  },
  computed: {
    ...mapState({
      databaseName: (state) => state.user.dataSource.databaseName,
      databaseType: (state) => state.user.dataSource.databaseType,
      username: (state) => state.user.dataSource.username,
      tenantId: (state) => state.user.tenant.tenantId,
    }),
  },
  mounted() {
    this.getList();
  },
  methods: {
    // 布局回调
    handlePosition(row) {
      this.layoutShow = true;
    },
    //条件编辑确认回调
    conditionConfirmHandler() {
      if (this.flag == "query") {
        this.subFormList[this.editIndex].queryMap = this.conditionTableData;
      } else if (this.flag == "insert") {
        this.subFormList[this.editIndex].insertMap = this.conditionTableData;
      }
      this.queryShow = false;
    },
    // 条件类型改变回调
    changeType(row) {
      // if(){}
      if (row.type == "defaultValue") {
        row.tableName = "";
        row.relaField = "";
      } else {
        row.refValue = "";
      }
    },
    // 根据formKey获取表单绑定的表名
    getTableNameByFormKey(formKey) {
      let temp = this.formOptionList.find((item) => item.formKey == formKey);
      return temp?.dfTableName || "";
    },
    // 依赖的主表单变化回调
    async changeTableName(row) {
      if (row.formKey) {
        let tableName = this.getTableNameByFormKey(row.formKey);
        row.tableName = tableName;
        let data = {
          databaseName: this.databaseName,
          databaseType: this.databaseType,
          tableName,
        };
        try {
          let res = await getListName(data);
          row.mainFormItemList = res.map((item) => {
            return {
              model: item.fieldName,
              label: item.fieldDescription,
              tableName,
            };
          });
          this.conditionTableShow = false;
          this.$nextTick(() => {
            this.conditionTableShow = true;
          });
        } catch (error) {
          console.error(error);
        }
      }
    },
    // 新增条件
    addCondition() {
      this.conditionTableData.push({
        fieldName: "", //字段
        type: "", //类型
        formKey: "", //字段
        tableName: "", //依赖表单
        relaField: "", //依赖字段
        refValue: "", //默认值
        mainFormItemList: [], //表单键列表
      });
    },
    // 删除条件
    handleRemove(index, row) {
      this.conditionTableData.splice(index, 1);
    },
    // 条件编辑回调
    editHandler(row, flag, index) {
      console.log(row);
      this.flag = flag;
      this.editIndex = index;
      if (flag == "query") {
        //编辑查询条件
        this.conditionTitle = "查询条件编辑";
        this.conditionTableData = row.queryMap
          ? JSON.parse(JSON.stringify(row.queryMap))
          : [];
      } else {
        //编辑插入条件
        this.conditionTitle = "插入条件编辑";
        this.conditionTableData = row.insertMap
          ? JSON.parse(JSON.stringify(row.insertMap))
          : [];
      }
      console.log(this.conditionTableData);
      this.fieldOptions = row.formItemList || [];
      // 可选表单范围  主表单和当前表单上面的子表单
      let formKeys = this.subFormList
        .map((item) => item.formKey)
        .slice(0, index);
      formKeys.unshift(this.groupForm.mainFormName);
      this.relaTableOptions = this.formOptionList.filter((item) =>
        formKeys.includes(item.formKey)
      ); //可依赖表单选项
      console.log(this.relaTableOptions);
      this.queryShow = true;
    },
    // 子表单键改变回调
    subFormItemChangeHandler(row) {
      row.dfTableName = row.formItem.split(".")[0];
      console.log(row.dfTableName);
    },
    // 新增表单组回调
    async addHandler() {
      this.resetDialogForm();
      await this.getFormList();
      this.isEdit = false;
      this.isShow = true;
    },
    // 重置弹窗的表单数据
    resetDialogForm() {
      Object.assign(this.groupForm, {
        fGName: "", //组名称
        groupDesc: "", //组描述
        mainFormName: "", //主表单
        mainFormItem: "", //主表单键
        mainFormTable: "", //主表单对应表格
        mainFormItemOptions: [], //主表单键选项
        groupKey: "", //组key
      });
      this.subFormList = [];
    },
    // 取消回调
    cancelHandler() {
      this.isShow = false;
    },
    // 确认回调
    confirmHandler() {
      this.$refs.groupFormRef.validate(async (valid) => {
        if (valid) {
          let {
            fGName,
            groupDesc,
            mainFormName,

            mainFormItem,
            mainFormTable,
            groupKey,
          } = this.groupForm;
          let mainTable = mainFormTable + ":" + mainFormName;
          let tempFormKeys = this.subFormList.map((item) => item.formKey);
          // 去掉多余数据 start
          this.subFormList.forEach((item) => {
            if (item.queryMap) {
              item.queryMap.forEach((i) => {
                delete i.mainFormItemList;
              });
            }

            if (item.insertMap) {
              item.insertMap.forEach((i) => {
                delete i.mainFormItemList;
              });
            }
          });
          // 去掉多余数据 end
          tempFormKeys.push(mainFormName);
          let formKeys = JSON.stringify(tempFormKeys);
          let relationJson = JSON.stringify({
            mainForm: { ...this.groupForm, formKey: mainFormName },
            subFormList: this.subFormList,
          });
          let payLoad = {
            fGName,
            remark: groupDesc,
            formKeys,
            mainTable,
            relationJson,
            showDataSql: "",
            groupKey,
          };
          let res;
          try {
            if (this.isEdit) {
              //修改
              payLoad.id = this.editRow.id;
              res = await updateFormGroup(payLoad);
              if (res.code == 200) {
                this.$message.success("修改成功");
                this.isShow = false;
                this.getList();
              } else {
                this.$message.error("修改失败");
              }
            } else {
              //新增
              payLoad.groupKey = uuidv4();
              res = await addFormGroup(payLoad);
              if (res.code == 200) {
                this.$message.success("新增成功");
                this.isShow = false;
                this.getList();
              } else {
                this.$message.error("新增失败");
              }
            }
          } catch (error) {
            console.log(error);
            this.$message.error("网络异常,请稍后再试");
          }
        }
      });
    },
    // 获取所有表单数据
    async getFormList() {
      let queryParams = { isEnablePaging: false };
      try {
        let res = await listForm(queryParams);
        if (res.code == 200) {
          this.formOptionList = res.rows;
          console.log(this.formOptionList);
        } else {
          throw Error("获取表单列表失败");
        }
      } catch (error) {
        this.$message.error("网络异常,获取表单列表失败");
      }
    },
    // 主表单变化回调
    async mainFormChange(mainFormName) {
      // let targetForm = this.getFormJson(formKey);
      // console.log("targetForm", targetForm);
      // if (targetForm) {
      //   this.groupForm.mainFormItemOptions = getFormItems(
      //     targetForm.dfVueTemplate
      //   );
      //   this.groupForm.mainFormTable = targetForm.dfTableName;
      // }
      let dfTableName = this.getTableNameByFormKey(mainFormName);
      let data = {
        databaseName: this.databaseName,
        databaseType: this.databaseType,
        tableName: dfTableName,
      };
      try {
        let res = await getListName(data);
        this.groupForm.mainFormItemOptions = res.map((item) => {
          return {
            model: item.fieldName,
            label: item.fieldDescription,
            tableName: dfTableName,
          };
        });
        this.groupForm.mainFormTable = dfTableName;
        // this.conditionTableShow = false;
        // this.$nextTick(() => {
        //   this.conditionTableShow = true;
        // });
      } catch (error) {
        console.error(error);
      }
    },
    // 获取fId对应的表单JSON数据
    getFormJson(formKey) {
      if (!formKey) return false;
      return this.formOptionList.find((item) => item.formKey === formKey);
    },
    // 字表单变化回调
    async subFormChangeHandler(row) {
      // if (!row.formKey) {
      //   Object.assign(row, {
      //     dfTableName: "",
      //     formItemList: [],
      //     formItem: "",
      //   });
      // } else {
      //   let targetForm = this.getFormJson(row.formKey);
      //   if (targetForm) {
      //     row.formItemList = getFormItems(targetForm.dfVueTemplate);
      //   }
      // }
      if (!row.formKey) {
        Object.assign(row, {
          dfTableName: "",
          formItemList: [],
          formItem: "",
        });
      } else {
        let tableName = this.getTableNameByFormKey(row.formKey);
        let data = {
          databaseName: this.databaseName,
          databaseType: this.databaseType,
          tableName: tableName,
        };
        try {
          let res = await getListName(data);
          row.formItemList = res.map((item) => {
            return {
              model: item.fieldName,
              label: item.fieldDescription,
              tableName: tableName,
            };
          });
        } catch (error) {
          console.error(error);
        }
      }
    },
    //删除从表单
    handleRemove(index) {
      this.subFormList.splice(index, 1);
    },
    // 新增从表单
    addOne() {
      this.subFormList.push({
        formKey: "", //从表单
        dfTableName: "", //从表名
        formItemList: [], //从表单项列表
        formItem: "", //从表单键
        relateMainItem: "", //依赖的主表单键
        isShow: true, //是否显示该表单
        insertMap: [],
        queryMap: [],
      });
    },

    //模板方法
    /** 查询动态表单组列表 */
    getList() {
      this.loading = true;
      listFormGroup(this.queryParams).then((response) => {
        this.formGroupList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        fGName: null,
        remark: null,
        formKeys: null,
        mainTable: null,
        relationJson: null,
        showDataSql: null,
        updateTime: null,
        updateBy: null,
        updateById: null,
        createTime: null,
        createById: null,
        createBy: null,
        delFlag: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加动态表单组";
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      if (row.id) {
        await this.getFormList();
        this.isEdit = true;
        this.editRow = JSON.parse(JSON.stringify(row));
        getFormGroup(row.id).then((response) => {
          console.log("回显数据", response);
          let { fGName, remark, relationJson } = response.data;
          // this.groupForm.fGName = fGName;
          // this.groupForm.groupDesc = remark;
          let { mainForm, subFormList } = JSON.parse(relationJson);
          mainForm.groupKey = response.data.groupKey;
          Object.assign(this.groupForm, mainForm);
          if (subFormList && subFormList.length > 0) {
            this.subFormList = subFormList;
          } else {
            this.subFormList = [];
          }
          this.isShow = true;
        });
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateFormGroup(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFormGroup(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除动态表单组编号为"' + ids + '"的数据项？')
        .then(function () {
          return delFormGroup(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/formGroup/export",
        {
          ...this.queryParams,
        },
        `formGroup_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-dialog__body {
  box-sizing: border-box;
  height: calc(100% - 60px) !important;
}
</style>
