<template>
  <div class="app-container">
    <el-card shadow="never" body-class="search-card">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
                    <el-form-item label="数据源名称" prop="dsName">
                      <el-input
                          v-model="queryParams.dsName"
                          placeholder="请输入数据源名称"
                          clearable
                          @keyup.enter="handleQuery"
                      />
                    </el-form-item>
                    <el-form-item label="数据库名称" prop="dbName">
                      <el-input
                          v-model="queryParams.dbName"
                          placeholder="请输入数据库名称"
                          clearable
                          @keyup.enter="handleQuery"
                      />
                    </el-form-item>
                    <el-form-item label="数据库主机" prop="dbHost">
                      <el-input
                          v-model="queryParams.dbHost"
                          placeholder="请输入数据库主机"
                          clearable
                          @keyup.enter="handleQuery"
                      />
                    </el-form-item>
                    <el-form-item label="数据库端口" prop="dbPort">
                      <el-input
                          v-model="queryParams.dbPort"
                          placeholder="请输入数据库端口"
                          clearable
                          @keyup.enter="handleQuery"
                      />
                    </el-form-item>
                    <el-form-item label="用户名" prop="username">
                      <el-input
                          v-model="queryParams.username"
                          placeholder="请输入用户名"
                          clearable
                          @keyup.enter="handleQuery"
                      />
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                      <el-input
                          v-model="queryParams.password"
                          placeholder="请输入密码"
                          clearable
                          @keyup.enter="handleQuery"
                      />
                    </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never" class="mt10">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasPermi="['system:datasourceConfig:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              v-hasPermi="['system:datasourceConfig:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="datasourceConfigList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="主键ID" align="center" prop="id" />
                <el-table-column label="数据源名称" align="center" prop="dsName" />
                <el-table-column label="数据库名称" align="center" prop="dbName" />
                <el-table-column label="数据库主机" align="center" prop="dbHost" />
                <el-table-column label="数据库端口" align="center" prop="dbPort" />
                <el-table-column label="用户名" align="center" prop="username" />
                <el-table-column label="密码" align="center" prop="password" />
                <el-table-column label="数据库类型" align="center" prop="dbType" />
                <el-table-column label="状态" align="center" prop="status" />
                <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="View" @click="handleDetail(scope.row)" v-hasPermi="['system:datasourceConfig:query']">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>

    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="datasourceConfigRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
                                              <el-col :span="12">
                            <el-form-item label="数据源名称" prop="dsName">
                                  <el-input v-model="form.dsName" placeholder="请输入数据源名称" />
                            </el-form-item>
                      </el-col>
                                              <el-col :span="12">
                            <el-form-item label="数据库名称" prop="dbName">
                                  <el-input v-model="form.dbName" placeholder="请输入数据库名称" />
                            </el-form-item>
                      </el-col>
                                              <el-col :span="12">
                            <el-form-item label="数据库主机" prop="dbHost">
                                  <el-input v-model="form.dbHost" placeholder="请输入数据库主机" />
                            </el-form-item>
                      </el-col>
                                              <el-col :span="12">
                            <el-form-item label="数据库端口" prop="dbPort">
                                  <el-input v-model="form.dbPort" placeholder="请输入数据库端口" />
                            </el-form-item>
                      </el-col>
                                              <el-col :span="12">
                            <el-form-item label="用户名" prop="username">
                                  <el-input v-model="form.username" placeholder="请输入用户名" />
                            </el-form-item>
                      </el-col>
                                              <el-col :span="12">
                            <el-form-item label="密码" prop="password">
                                  <el-input v-model="form.password" placeholder="请输入密码" />
                            </el-form-item>
                      </el-col>
                                              <el-col :span="12">
                      </el-col>
                                              <el-col :span="12">
                      </el-col>
                                              <el-col :span="24">
                            <el-form-item label="备注" prop="remark">
                              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
                            </el-form-item>
                      </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-drawer :title="isEditMode ? '修改数据源管理' : '数据源管理详情'" v-model="openDetail" size="60%">

      <div v-show="!isEditMode">
        <el-descriptions :column="2" border>
                  <el-descriptions-item label="数据源名称">
                        {{ detailForm.dsName }}
                  </el-descriptions-item>
                  <el-descriptions-item label="数据库名称">
                        {{ detailForm.dbName }}
                  </el-descriptions-item>
                  <el-descriptions-item label="数据库主机">
                        {{ detailForm.dbHost }}
                  </el-descriptions-item>
                  <el-descriptions-item label="数据库端口">
                        {{ detailForm.dbPort }}
                  </el-descriptions-item>
                  <el-descriptions-item label="用户名">
                        {{ detailForm.username }}
                  </el-descriptions-item>
                  <el-descriptions-item label="密码">
                        {{ detailForm.password }}
                  </el-descriptions-item>
                  <el-descriptions-item label="数据库类型">
                        {{ detailForm.dbType }}
                  </el-descriptions-item>
                  <el-descriptions-item label="状态">
                        {{ detailForm.status }}
                  </el-descriptions-item>
                  <el-descriptions-item label="备注">
                        {{ detailForm.remark }}
                  </el-descriptions-item>
                  <el-descriptions-item label="创建者">
                        {{ detailForm.createBy }}
                  </el-descriptions-item>
                  <el-descriptions-item label="创建时间">
                        <span>{{ parseTime(detailForm.createTime, '{y}-{m}-{d}') }}</span>
                  </el-descriptions-item>
                  <el-descriptions-item label="更新者">
                        {{ detailForm.updateBy }}
                  </el-descriptions-item>
                  <el-descriptions-item label="更新时间">
                        <span>{{ parseTime(detailForm.updateTime, '{y}-{m}-{d}') }}</span>
                  </el-descriptions-item>
        </el-descriptions>
      </div>

      <div v-show="isEditMode">
        <el-form ref="datasourceConfigDrawerRef" :model="form" :rules="rules" label-width="100px">
          <el-row :gutter="24">

                          
                        <el-col :span="12">
                              <el-form-item label="数据源名称" prop="dsName">
                                    <el-input v-model="form.dsName" placeholder="请输入数据源名称" style="width: 100%"/>
                              </el-form-item>
                        </el-col>

                          
                        <el-col :span="12">
                              <el-form-item label="数据库名称" prop="dbName">
                                    <el-input v-model="form.dbName" placeholder="请输入数据库名称" style="width: 100%"/>
                              </el-form-item>
                        </el-col>

                          
                        <el-col :span="12">
                              <el-form-item label="数据库主机" prop="dbHost">
                                    <el-input v-model="form.dbHost" placeholder="请输入数据库主机" style="width: 100%"/>
                              </el-form-item>
                        </el-col>

                          
                        <el-col :span="12">
                              <el-form-item label="数据库端口" prop="dbPort">
                                    <el-input v-model="form.dbPort" placeholder="请输入数据库端口" style="width: 100%"/>
                              </el-form-item>
                        </el-col>

                          
                        <el-col :span="12">
                              <el-form-item label="用户名" prop="username">
                                    <el-input v-model="form.username" placeholder="请输入用户名" style="width: 100%"/>
                              </el-form-item>
                        </el-col>

                          
                        <el-col :span="12">
                              <el-form-item label="密码" prop="password">
                                    <el-input v-model="form.password" placeholder="请输入密码" style="width: 100%"/>
                              </el-form-item>
                        </el-col>

                          
                        <el-col :span="12">
                        </el-col>

                          
                        <el-col :span="12">
                        </el-col>

                          
                        <el-col :span="24">
                              <el-form-item label="备注" prop="remark">
                                <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
                              </el-form-item>
                        </el-col>
          </el-row>
        </el-form>
      </div>

      <template #footer>
        <div class="drawer-footer" style="display: flex; justify-content: flex-end; gap: 10px;">
          <div v-if="!isEditMode">
            <el-button
                type="primary"
                plain
                icon="Edit"
                @click="handleEnterEditMode"
                v-hasPermi="['system:datasourceConfig:edit']"
            >修改资料</el-button>
            <el-button
                type="danger"
                plain
                icon="Delete"
                @click="handleDeleteFromDetail"
                v-hasPermi="['system:datasourceConfig:remove']"
            >删除记录</el-button>
            <el-button @click="openDetail = false">关 闭</el-button>
          </div>

          <div v-else>
            <el-button type="primary" @click="submitDrawerForm">保存提交</el-button>
            <el-button @click="isEditMode = false">取消修改</el-button>
          </div>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup name="DatasourceConfig">
  import { listDatasourceConfig, getDatasourceConfig, delDatasourceConfig, addDatasourceConfig, updateDatasourceConfig } from "@/api/system/datasourceConfig";
  const { proxy } = getCurrentInstance();

  const datasourceConfigList = ref([]);
  const open = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const title = ref("");

  // 详情与编辑相关变量
  const openDetail = ref(false);
  const isEditMode = ref(false); // 控制查看/编辑模式
  const detailForm = ref({});


  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
                    dsName: null,
                    dbName: null,
                    dbHost: null,
                    dbPort: null,
                    username: null,
                    password: null,
                    dbType: null,
                    status: null,
    },
    rules: {
                    dsName: [
                { required: true, message: "数据源名称不能为空", trigger: "blur" }
              ],
                    dbName: [
                { required: true, message: "数据库名称不能为空", trigger: "blur" }
              ],
                    dbHost: [
                { required: true, message: "数据库主机不能为空", trigger: "blur" }
              ],
                    dbPort: [
                { required: true, message: "数据库端口不能为空", trigger: "blur" }
              ],
                    username: [
                { required: true, message: "用户名不能为空", trigger: "blur" }
              ],
                    password: [
                { required: true, message: "密码不能为空", trigger: "blur" }
              ],
                    dbType: [
                { required: true, message: "数据库类型不能为空", trigger: "change" }
              ],
                    status: [
                { required: true, message: "状态不能为空", trigger: "change" }
              ],
                    createBy: [
                { required: true, message: "创建者不能为空", trigger: "blur" }
              ],
                    createTime: [
                { required: true, message: "创建时间不能为空", trigger: "blur" }
              ],
                    updateBy: [
                { required: true, message: "更新者不能为空", trigger: "blur" }
              ],
                    updateTime: [
                { required: true, message: "更新时间不能为空", trigger: "blur" }
              ]
    }
  });

  const { queryParams, form, rules } = toRefs(data);

  /** 查询列表 */
  function getList() {
    loading.value = true;
    listDatasourceConfig(queryParams.value).then(response => {
            datasourceConfigList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    });
  }

  // 取消按钮
  function cancel() {
    open.value = false;
    reset();
  }

  // 表单重置
  function reset() {
    form.value = {
                    id: null,
                    dsName: null,
                    dbName: null,
                    dbHost: null,
                    dbPort: null,
                    username: null,
                    password: null,
                    dbType: null,
                    status: null,
                    remark: null,
                    createBy: null,
                    createTime: null,
                    updateBy: null,
                    updateTime: null
    };
    proxy.resetForm("datasourceConfigRef");
    proxy.resetForm("datasourceConfigDrawerRef");
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }

  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
  }

  // 多选框选中数据
  function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }

  /** 新增按钮操作 */
  function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加数据源管理";
  }

  /** 修改按钮操作 (仅用于弹窗) */
  function handleUpdate(row) {
    reset();
    const _id = row.id || ids.value;
    getDatasourceConfig(_id).then(response => {
      form.value = response.data;
      open.value = true;
      title.value = "修改数据源管理";
    });
  }

  /** 详情按钮操作 */
  function handleDetail(row) {
    reset();
    // 详情前重置表单状态
    isEditMode.value = false; // 默认进入查看模式
    const _id = row.id;
    getDatasourceConfig(_id).then(response => {
      detailForm.value = response.data;
      openDetail.value = true;
    });
  }

  /** 进入编辑模式 */
  function handleEnterEditMode() {
    // 从 detailForm 同步数据到 form，准备编辑
    const row = detailForm.value;
    const _id = row.id;

    // 重新获取最新数据以填充表单，保证格式（如checkbox数组）正确
    getDatasourceConfig(_id).then(response => {
      form.value = response.data;
      isEditMode.value = true; // 切换到编辑视图
    });
  }

  /** 抽屉内表单提交 */
  function submitDrawerForm() {
    proxy.$refs["datasourceConfigDrawerRef"].validate(valid => {
      if (valid) {
        if (form.value.id != null) {
          updateDatasourceConfig(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            // 修改成功后，刷新详情数据并切回查看模式
            detailForm.value = JSON.parse(JSON.stringify(form.value));
            // 注意：如果form数据和详情展示格式有较大差异（如split前后），最好重新调用get详情
            handleDetail(form.value);
            getList();
          });
        }
      }
    });
  }

  /** 详情内删除按钮 */
  function handleDeleteFromDetail() {
    const row = detailForm.value;
    handleDelete(row).then(() => {
      openDetail.value = false;
    });
  }

  /** 常规弹窗提交按钮 */
  function submitForm() {
    proxy.$refs["datasourceConfigRef"].validate(valid => {
      if (valid) {
        if (form.value.id != null) {
          updateDatasourceConfig(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          });
        } else {
          addDatasourceConfig(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          });
        }
      }
    });
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const _ids = row.id || ids.value;
    return proxy.$modal.confirm('是否确认删除数据源管理编号为"' + _ids + '"的数据项？').then(function() {
      return delDatasourceConfig(_ids);
    }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {});
  }


  /** 导出按钮操作 */
  function handleExport() {
    proxy.download('system/datasourceConfig/export', {
      ...queryParams.value
    }, `datasourceConfig_${new Date().getTime()}.xlsx`)
  }

  getList();
</script>