<template>
  <div class="app-container">
    <!-- 主表 Dialog -->
    <el-dialog
      v-dialogDrag
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="90%"
      append-to-body
      @close="reset"
    >
      <el-form
        ref="formRef"
        v-loading="formLoading"
        :model="formData"
        :rules="formRules"
        label-width="130px"
      >
        <el-row>
          <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.id"
                  :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-row>
      </el-form>

      <!-- 子表 -->
      <el-tabs v-model="subTabsName">
        <el-tab-pane label="查询字段" name="queryManageColumn">
          <QueryManageColumnForm
            ref="queryManageColumnFormRef"
            :master-id="formData.id"
          />
        </el-tab-pane>

        <el-tab-pane
          label="操作按钮"
          name="operationButton"
          :disabled="formData.parentId === 0 || !formData.id"
          lazy
        >
          <OperatingButton
            ref="operatingButtonRef"
            :column-list="columnSelectList"
            :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 { getDicts } from "@/api/system/dict/data";
import QueryManageColumnForm from "./components/QueryManageColumnForm.vue";
import OperatingButton from "./components/OperatingButton.vue";

export default {
  name: "QueryManageMergeDialog",
  components: { QueryManageColumnForm, OperatingButton },
  data() {
    return {
      dialogTitle: "",
      dialogVisible: false,
      formLoading: false,
      subTabsName: "queryManageColumn",
      dataSourceList: [], // 数据源下拉
      columnSelectList: [], // 供操作按钮页使用的字段列表
      formData: {
        id: undefined,
        code: undefined,
        name: undefined,
        parentId: 0,
        parentName: "",
        sort: undefined,
        status: undefined,
        dataSourceConfigId: undefined,
        sqlStatement: undefined,
        commonSql: undefined,
        sortSql: undefined,
      },
      formRules: {
        code: [
          { required: true, message: "查询编码不能为空", trigger: "blur" },
        ],
        name: [
          { required: true, message: "查询名称不能为空", trigger: "blur" },
        ],
        sort: [
          { required: true, message: "显示顺序不能为空", trigger: "blur" },
        ],
        status: [
          { required: true, message: "查询状态不能为空", trigger: "change" },
        ],
      },
    };
  },
  watch: {
    dialogVisible(n) {
      if (!n) this.reset();
    },
  },
  methods: {
    /* 外部唯一入口 */
    async open(id) {
      this.dialogVisible = true;
      this.getSourceList();
      if (id) {
        // 修改
        this.formLoading = true;
        try {
          const { data } = await QueryManageApi.getQueryManage(id);
          this.formData = { ...this.formData, ...data };
          this.dialogTitle = "修改查询管理";
          await this.loadColumnList();
        } finally {
          this.formLoading = false;
        }
      } else {
        // 新增
        this.dialogTitle = "新增查询管理";
      }
    },

    /* 获取数据源下拉 */
    getSourceList() {
      // getDicts("ym_data_source").then(({ data }) => {
      //   this.dataSourceList = data?.list ?? [];
      // });
    },

    /* 解析 SQL */
    parceSql(sql) {
      QueryManageApi.getSqlColumn(sql).then(({ data }) => {
        const list = data.map((item) => ({
          dataType: "ym_string_query_type",
          listOperationResult: true,
          htmlType: "input",
          masterId: this.formData.id,
          index: item.ordinalPosition + 1,
          ...item,
          listOperationCondition: false, // 确保在...item之后设置，避免被覆盖，使用布尔值
        }));
        this.$refs.queryManageColumnFormRef.formData = [...list];
      });
    },

    /* 加载子表字段列表（供操作按钮页使用） */
    async loadColumnList() {
      if (!this.formData.id) return;
      try {
        const { data } =
          await QueryManageApi.getQueryManageColumnListByMasterId(
            this.formData.id
          );
        this.columnSelectList = data || [];
      } catch (error) {
        console.error("加载字段列表失败:", error);
        this.columnSelectList = [];
      }
    },

    /* 提交 */
    async submitForm() {
      // 主表校验
      const validMain = await this.$refs.formRef.validate().catch(() => false);
      console.log("主表校验完成" + validMain);
      if (!validMain) return;
      // 子表校验（先判空再调）
      console.log("开始校验");
      const columnRef = this.$refs.queryManageColumnFormRef;
      console.log("开始校验1");
      console.log("columnRef:", this.$refs.queryManageColumnFormRef);
      if (!columnRef || typeof columnRef.validate !== "function") {
        this.$message.warning("字段列表尚未加载，请切换到“查询字段”页后再试");
        return;
      }
      console.log("开始校验2");
      const validSub = await this.$refs.queryManageColumnFormRef
        .validate()
        .catch((err) => {
          console.error("子组件校验失败", err);
          return false;
        });
      console.log("子组件校验结果", validSub);
      if (!validSub) {
        this.subTabsName = "queryManageColumn";
        return;
      }
      console.log("子表校验完成");
      this.formLoading = true;
      try {
        // 获取子组件数据
        const subData = this.$refs.queryManageColumnFormRef.getData();
        console.log("从子组件获取的数据:", subData);

        // 强制转换queryManageColumns中的listOperationCondition为字符串"1"或"0"
        const processedColumns = subData.map((item) => ({
          ...item,
          listOperationCondition: item.listOperationCondition ? "1" : "0",
        }));

        const data = {
          ...this.formData,
          queryManageColumns: processedColumns,
        };

        console.log("最终提交的数据:", data);

        if (data.id) {
          // 修改
          console.log("调用修改接口");
          await QueryManageApi.updateQueryManage(data);
          this.$modal.msgSuccess("修改成功");
        } else {
          // 新增
          await QueryManageApi.createQueryManage(data);
          this.$modal.msgSuccess("新增成功");
        }
        this.dialogVisible = false;
        this.$emit("success"); // 父组件可监听刷新列表
      } finally {
        this.formLoading = false;
      }
    },

    /* 重置 */
    reset() {
      this.formData = this.$options.data().formData;
      this.columnSelectList = [];
      this.resetForm("formRef");
    },
  },
};
</script>
