<template>
  <div class="app-container">
    <!-- 新增行按钮 -->
    <div class="mb-10px">
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd"
        >新增行</el-button
      >
    </div>
    <el-form
      ref="formRef"
      :model="{ formData }"
      :rules="formRules"
      label-width="0px"
      :inline-message="true"
    >
      <el-table
        v-loading="formLoading"
        :data="formData"
        class="-mt-10px"
        border
      >
        <el-table-column label="序号" type="index" width="50" align="center" />
        <el-table-column label="字段名" min-width="100" align="center">
          <template v-slot="{ row, $index }">
            <el-form-item
              :prop="`formData.${$index}.columnName`"
              :rules="formRules.columnName"
              class="mb-0px!"
            >
              <el-input v-model="row.columnName" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="字段描述" min-width="100" align="center">
          <template v-slot="{ row, $index }">
            <el-form-item
              :prop="`formData.${$index}.columnComment`"
              :rules="formRules.columnComment"
              class="mb-0px!"
            >
              <el-input
                v-model="row.columnComment"
                placeholder="请输入字段描述"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="字段类型" min-width="100" align="center">
          <template v-slot="{ row, $index }">
            <el-form-item
              :prop="`formData.${$index}.dataType`"
              :rules="formRules.dataType"
              class="mb-0px!"
            >
              <DictSelect
                v-model="row.dataType"
                size="mini"
                placeholder="请选择字段类型"
                dict-type="YM_DATA_TYPE"
                label="label"
                value="value"
                @change="dataTypeChange($event, row, $index)"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="排序" min-width="100" align="center">
          <template v-slot="{ row, $index }">
            <el-form-item
              :prop="`formData.${$index}.ordinalPosition`"
              :rules="formRules.ordinalPosition"
              class="mb-0px!"
            >
              <el-input
                v-model="row.ordinalPosition"
                placeholder="请输入排序"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="Java类型" min-width="100" align="center">
          <template v-slot="{ row, $index }">
            <el-form-item
              :prop="`formData.${$index}.javaType`"
              :rules="formRules.javaType"
              class="mb-0px!"
            >
              <el-select v-model="row.javaType">
                <el-option label="Long" value="Long" />
                <el-option label="String" value="String" />
                <el-option label="Integer" value="Integer" />
                <el-option label="Double" value="Double" />
                <el-option label="BigDecimal" value="BigDecimal" />
                <el-option label="LocalDateTime" value="LocalDateTime" />
                <el-option label="Boolean" value="Boolean" />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="列表宽度" min-width="100" align="center">
          <template v-slot="{ row, $index }">
            <el-form-item
              :prop="`formData.${$index}.javaField`"
              :rules="formRules.javaField"
              class="mb-0px!"
            >
              <el-input
                v-model.number="row.javaField"
                placeholder="请输入列表宽度"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="字典类型" min-width="100" align="center">
          <template v-slot="{ row, $index }">
            <el-form-item
              :prop="`formData.${$index}.dictType`"
              :rules="formRules.dictType"
              class="mb-0px!"
            >
              <el-select
                v-model="row.dictType"
                clearable
                filterable
                placeholder="请选择"
              >
                <el-option
                  v-for="dict in dictOptions"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.type"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="路由/控制" min-width="100" align="center">
          <template v-slot="{ row, $index }">
            <el-form-item
              :prop="`formData.${$index}.example`"
              :rules="formRules.example"
              class="mb-0px!"
            >
              <el-input v-model="row.example" placeholder="请输入数据示例" />
            </el-form-item>
          </template>
        </el-table-column>
        <!-- <el-table-column label="查询方式" min-width="100" align="center">
          <template v-slot="{ row, $index }">
            <el-form-item
              :prop="`formData.${$index}.listOperationCondition`"
              class="mb-0px!"
            >
              <el-select
                v-model="row.listOperationCondition"
                :rules="formRules.listOperationCondition"
              >
                <el-option label="=" value="=" />
                <el-option label="!=" value="!=" />
                <el-option label=">" value=">" />
                <el-option label=">=" value=">=" />
                <el-option label="<" value="<>" />
                <el-option label="<=" value="<=" />
                <el-option label="LIKE" value="LIKE" />
                <el-option label="BETWEEN" value="BETWEEN" />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column> -->
        <el-table-column label="多选" min-width="100" align="center">
          <template v-slot="{ row, $index }">
            <el-form-item
              :prop="`formData.${$index}.listOperationCondition`"
              :rules="formRules.listOperationCondition"
              class="mb-0px!"
            >
              <el-checkbox
                v-model="row.listOperationCondition"
                true-value="1"
                false-value="0"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="隐藏" min-width="50" align="center">
          <template v-slot="{ row, $index }">
            <el-form-item
              :prop="`formData.${$index}.ifHide`"
              :rules="formRules.ifHide"
              class="mb-0px!"
            >
              <el-checkbox
                v-model="row.ifHide"
                :true-value="true"
                :false-value="false"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="查询" min-width="50" align="center">
          <template v-slot="{ row, $index }">
            <el-form-item
              :prop="`formData.${$index}.listOperationResult`"
              :rules="formRules.listOperationResult"
              class="mb-0px!"
            >
              <el-checkbox
                v-model="row.listOperationResult"
                :true-value="true"
                :false-value="false"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="排序" min-width="50" align="center">
          <template v-slot="{ row, $index }">
            <el-form-item
              :prop="`formData.${$index}.ifSort`"
              :rules="formRules.ifSort"
              class="mb-0px!"
            >
              <el-checkbox
                v-model="row.ifSort"
                :true-value="true"
                :false-value="false"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="显示类型" min-width="100" align="center">
          <template v-slot="{ row, $index }">
            <el-form-item
              :prop="`formData.${$index}.htmlType`"
              :rules="formRules.htmlType"
              class="mb-0px!"
            >
              <el-select v-model="row.htmlType">
                <el-option label="文本框" value="input" />
                <el-option label="文本域" value="textarea" />
                <el-option label="下拉框" value="select" />
                <el-option label="单选框" value="radio" />
                <el-option label="日期控件" value="datetime" />
                <el-option label="日期范围" value="daterange" />
                <!-- <el-option label="隐藏" value="hidden" /> -->
                <!-- <el-option label="复选框" value="checkbox" /> -->
                <!-- <el-option label="图片上传" value="imageUpload" />
                <el-option label="文件上传" value="fileUpload" />
                <el-option label="富文本控件" value="editor" /> -->
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
  </div>
</template>

<script>
import * as QueryManageApi from "@/api/mes/queryManage";
import { listAllSimple as listAllSimpleDictType } from "@/api/system/dict/type";
export default {
  name: "QueryManageColumnForm",
  components: {},
  props: ["masterId"], // 主表id（主表的关联字段）
  data() {
    return {
      // 字典信息
      dictOptions: [],
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      formData: [],
      // 表单校验
      formRules: {
        // masterId: [
        //   { required: true, message: "主表id不能为空", trigger: "blur" },
        // ],
        // columnName: [
        //   { required: true, message: "字段名不能为空", trigger: "blur" },
        // ],
        columnComment: [
          { required: true, message: "字段描述不能为空", trigger: "blur" },
        ],
        // dataType: [
        //   { required: true, message: "字段类型不能为空", trigger: "change" },
        // ],
        listOperationCondition: [
          {
            required: true,
            message: "List 查询操作的条件类型不能为空",
            trigger: "blur",
          },
        ],
        // listOperationResult: [
        //   {
        //     required: true,
        //     message: "是否为查询操作的字段不能为空",
        //     trigger: "blur",
        //   },
        // ],
        htmlType: [
          { required: true, message: "显示类型不能为空", trigger: "change" },
        ],
      },
    };
  },
  watch: {
    /** 监听主表的关联字段的变化，加载对应的子表数据 */
    masterId: {
      handler(val) {
        // 1. 重置表单
        this.formData = [];
        // 2. val 非空，则加载数据
        if (!val) {
          return;
        }
        try {
          this.formLoading = true;
          // 这里还是需要获取一下 this 的不然取不到 formData
          const that = this;
          QueryManageApi.getQueryManageColumnListByMasterId(val).then(function (
            res
          ) {
            // 将后端返回的字符串"1"/"0"转换为布尔值true/false
            const processedData = res.data.map((item) => ({
              ...item,
              listOperationCondition: item.listOperationCondition === "1",
            }));
            that.formData = processedData;
          });
        } finally {
          this.formLoading = false;
        }
      },
      immediate: true,
    },
  },
  created() {
    /** 查询字典下拉列表 */
    listAllSimpleDictType().then((response) => {
      this.dictOptions = response.data;
    });
  },
  methods: {
    dataTypeChange(val, row, idx) {
      if (val === "ym_date_query_type") {
        this.formData[idx].javaType = "LocalDateTime";
        this.formData[idx].htmlType = "datetime";
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      const row = {
        id: undefined,
        masterId: undefined,
        columnName: undefined,
        columnComment: undefined,
        dataType: "",
        ordinalPosition: undefined,
        javaType: undefined,
        javaField: undefined,
        dictType: undefined,
        example: undefined,
        listOperationCondition: false,
        listOperationResult: "false",
        ifHide: "false",
        htmlType: "input",
        multiSelect: 0,
      };
      row.masterId = this.masterId;
      this.formData.push(row);
    },
    /** 删除按钮操作 */
    handleDelete(index) {
      this.formData.splice(index, 1);
    },
    /** 表单校验 */
    validate() {
      return new Promise((resolve) => {
        this.$nextTick(() => {
          if (!this.$refs.formRef) {
            console.warn("子组件 formRef 未挂载");
            resolve(false);
            return;
          }
          this.$refs.formRef.validate((valid) => {
            console.log("子组件校验结果:", valid);
            resolve(valid);
          });
        });
      });
    },
    /** 表单值 */
    getData() {
      console.log("子组件getData返回的数据:", this.formData);
      return this.formData;
    },
  },
};
</script>
