<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog
      v-dialogDrag
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="90%"
      append-to-body
    >
      <el-row>
        <el-form
          ref="formRef"
          v-loading="formLoading"
          :model="formData"
          :rules="formRules"
          label-width="130px"
        >
          <el-col :span="8">
            <el-form-item label="查询编码" prop="code">
              <el-input
                v-model="formData.code"
                placeholder="请输入查询编码"
              /> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="查询名称" prop="name">
              <el-input
                v-model="formData.name"
                placeholder="请输入查询名称"
              /> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="父查询名称" prop="parentName">
              <el-input
                v-model="formData.parentName"
                disabled
                placeholder="请输入父查询"
              /> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="显示顺序" prop="sort">
              <el-input
                v-model="formData.sort"
                placeholder="请输入显示顺序"
              /> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="查询状态" prop="status">
              <DictSelect
                v-model="formData.status"
                placeholder="请选择查询状态"
                dict-type="COMMON_STATUS"
              /> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="数据源配置的编号" prop="dataSourceConfigId">
              <el-select
                v-model="formData.dataSourceConfigId"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in dataSourceList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="字段sql" prop="sqlStatement">
              <el-input
                v-model="formData.sqlStatement"
                type="textarea"
                placeholder="请输入字段sql"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="条件sql" prop="commonSql">
              <el-input
                v-model="formData.commonSql"
                type="textarea"
                placeholder="请输入条件sql"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排序sql" prop="sortSql">
              <el-input
                v-model="formData.sortSql"
                type="textarea"
                placeholder="请输入排序sql"
              />
              <el-button
                type="primary"
                size="mini"
                @click="parceSql(formData.sqlStatement)"
                >解析</el-button
              >
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <!-- 子表的表单 -->
      <el-tabs v-model="subTabsName">
        <el-tab-pane label="查询字段" name="queryManageColumn">
          <QueryManageColumnForm
            ref="queryManageColumnFormRef"
            :master-id="formData.id"
          />
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="formLoading" @click="submitForm"
          >确 定</el-button
        >
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as QueryManageApi from "@/api/mes/queryManage/index";
import QueryManageColumnForm from "./components/QueryManageColumnForm.vue";
import { getDicts } from "@/api/system/dict/data.js";
export default {
  name: "QueryManageForm",
  components: {
    QueryManageColumnForm,
  },
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      formData: {
        id: undefined,
        code: undefined,
        name: undefined,
        parentId: "",
        parentName: "",
        sort: undefined,
        status: undefined,
        dataSourceConfigId: undefined,
        sqlStatement: undefined,
      },
      // 表单校验
      formRules: {
        code: [
          { required: true, message: "查询编码不能为空", trigger: "blur" },
        ],
        name: [
          { required: true, message: "查询名称不能为空", trigger: "blur" },
        ],
        // parentId: [
        //   { required: true, message: "父查询id不能为空", trigger: "blur" },
        // ],
        sort: [
          { required: true, message: "显示顺序不能为空", trigger: "blur" },
        ],
        status: [
          {
            required: true,
            message: "查询状态不能为空",
            trigger: "blur",
          },
        ],
      },
      /** 子表的表单 */
      subTabsName: "queryManageColumn",
      dataSourceList: [], // 数据源下拉列表
    };
  },
  watch: {
    dialogVisible(nVal) {
      if (!nVal) {
        this.reset();
      }
    },
  },
  methods: {
    // 解析sql语句
    parceSql(sql) {
      QueryManageApi.getSqlColumn(sql).then((res) => {
        const list = res.data.map((item) => {
          return {
            dataType: "ym_string_query_type",
            listOperationResult: true,
            htmlType: "input",
            masterId: this.formData.id,
            ...item,
          };
        });
        this.$refs.queryManageColumnFormRef.formData = [...list];
      });
    },
    // 获取配置数据源列表
    getSourceList() {
      getDicts("ym_data_source").then(({ data }) => {
        this.dataSourceList = data?.list ?? [];
      });
    },
    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;
      this.getSourceList();
      // 修改时，设置数据
      if (id) {
        this.formLoading = true;
        try {
          const res = await QueryManageApi.getQueryManage(id);
          this.formData = res.data;
          this.title = "修改查询管理";
        } finally {
          this.formLoading = false;
        }
      }
      this.title = "新增查询管理";
    },
    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      // 校验子表
      try {
        await this.$refs["queryManageColumnFormRef"].validate();
      } catch (e) {
        this.subTabsName = "queryManageColumn";
        return;
      }
      this.formLoading = true;
      try {
        const data = this.formData;
        // 拼接子表的数据
        data.queryManageColumns =
          this.$refs["queryManageColumnFormRef"].getData();

        // 修改的提交
        if (data.id) {
          await QueryManageApi.updateQueryManage(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit("success");
          return;
        }
        // 添加的提交
        await QueryManageApi.createQueryManage(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit("success");
      } finally {
        this.formLoading = false;
      }
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        code: undefined,
        name: undefined,
        parentId: undefined,
        parentName: undefined,
        sort: undefined,
        status: undefined,
        dataSourceConfigId: undefined,
        sqlStatement: undefined,
      };
      this.resetForm("formRef");
    },
  },
};
</script>
