<template>
  <div class="app-container">
    <div ref="topContainerRef">
        <TableSearch
            :queryParams="queryParams"
            :showSearch="showSearch"
            label-width="90px"
            queryRef="queryRef"
            @refresh="resetQuery"
            @search="handleQuery"
        >
            <template #one>
                <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24" :xxl="6">
                    <el-form-item label="用例编码" prop="caseCode">
                        <el-input
                        v-model="queryParams.caseCode"
                        placeholder="请输入用例编码"
                        clearable
                        style="width: 240px"
                        @keyup.enter="handleQuery"
                        />
                    </el-form-item>
                </el-col>
                <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24" :xxl="6">
                    <el-form-item label="测试步骤" prop="testSteps">
                        <el-input
                        v-model="queryParams.testSteps"
                        placeholder="请输入测试步骤"
                        clearable
                        style="width: 240px"
                        @keyup.enter="handleQuery"
                        />
                    </el-form-item>
                </el-col>
            </template>
        </TableSearch>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                type="primary"
                plain
                icon="Plus"
                @click="handleAdd"
                >新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                type="success"
                plain
                icon="Edit"
                :disabled="single"
                @click="handleUpdate"
                >修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                type="danger"
                plain
                icon="Delete"
                :disabled="multiple"
                @click="handleDelete"
                >删除</el-button>
            </el-col>

        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </div>

    <div :style="containerHeight">
      <!-- 表格数据 -->
      <el-table height="100%" v-loading="loading" :data="tableDataList" @selection-change="handleSelectionChange">
         <el-table-column type="selection" width="55" align="center" />
         <el-table-column label="用例名称" prop="caseName" />
         <el-table-column label="预期结果" prop="expectedResult" :show-overflow-tooltip="true" width="200" />
         <el-table-column label="前置条件" prop="precondition" show-overflow-tooltip="true" width="200" />
         <el-table-column label="测试步骤" align="center" prop="testSteps" show-overflow-tooltip="true" width="200"/>
         <el-table-column label="测试描述" align="center" prop="testDescription" show-overflow-tooltip="true" width="200" />
         <el-table-column label="状态" align="center" width="100">
            <template #default="scope">
               <el-switch
                  v-model="scope.row.enabled"
                  active-value="0"
                  inactive-value="1"
                  @change="handleStatusChange(scope.row)"
               ></el-switch>
            </template>
         </el-table-column>
         <el-table-column align="center" label="配置状态" prop="configStatus">
          <template #default="scope">
            <TableTags
              :options="[
                {
                  label: '已配置',
                  value: '0',
                  type: 'success',
                },
                {
                  label: '未配置',
                  value: '1',
                  type: 'warning',
                },
              ]"
              :value="scope.row.configStatus"
            ></TableTags>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-tooltip content="修改" placement="top">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
              </el-tooltip>
              <el-button
                icon="Cpu"
                link
                type="primary"
                @click="handleDeploy(scope.row)"
                >配置
            </el-button>
              <el-tooltip content="删除" placement="top">
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
              </el-tooltip>
            </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"
      />

    </div>

      <!-- 添加或修改配置对话框 -->
      <el-dialog :title="title" v-model="open" width="500px" append-to-body>
         <el-form ref="testCaseRef" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="用例名称" prop="caseName">
               <el-input v-model="form.caseName" placeholder="请输入用例名称" />
            </el-form-item>
            <el-form-item label="预期结果" prop="expectedResult">
               <el-input type="textarea" v-model="form.expectedResult" placeholder="请输入预期结果" />
            </el-form-item>
            <el-form-item label="前置条件" prop="precondition">
                <el-input type="textarea" v-model="form.precondition" placeholder="请输入前置条件" />
            </el-form-item>
            <el-form-item label="测试步骤" prop="testSteps">
               <el-input type="textarea" v-model="form.testSteps" placeholder="请输入测试步骤" />
            </el-form-item>
            <el-form-item label="测试描述" prop="testDescription">
               <el-input type="textarea" v-model="form.testDescription" />
            </el-form-item>
         </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>

   </div>
</template>

<script setup name="Role">
import TableSearch from "@/components/TableSearch/index.vue";
import { useContainerHeight } from "@/hooks/tableHeight";
import { addTestCase, getTestCaseList, updateTestCase, deleteTestCase } from "@/api/intelligenceTest/testCase.js"
import { ElMessage, ElMessageBox } from 'element-plus'
import { appendParamsToPath } from "@/utils/fn.js";
import TableTags from "@/components/TableTags/index.vue";

const topContainerRef = ref();
const containerHeight = useContainerHeight(topContainerRef);

const tableDataList = 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 data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    caseName: undefined,
    testSteps: undefined
  },
  rules: {
    caseName: [{ required: true, message: "用例名称不能为空", trigger: "blur" }],
    expectedResult: [{ required: true, message: "预期结果不能为空", trigger: "blur" }],
    testSteps: [{ required: true, message: "测试步骤为空", trigger: "blur" }],
    testDescription: [{ required: true, message: "测试描述不能为空", trigger: "blur" }]
  },
});

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

/** 查询列表 */
const getList = async () =>  {
  loading.value = true;
  const res = await getTestCaseList(queryParams.value)
  if (res.code === 200) {
    tableDataList.value = res.rows;
    total.value = res.total;
  }
  loading.value = false;
}

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

/** 重置按钮操作 */
function resetQuery() {
  handleQuery();
}

/** 删除按钮操作 */
function handleDelete(row) {
  const deleteIds = row.id || ids.value;
    ElMessageBox.confirm(`确定要删除编号为${deleteIds}的测试用例吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        deleteTestCase(deleteIds).then(() => {
            ElMessage.success("删除成功");
            getList();
        });
     });
}


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

/** 状态修改 */
function handleStatusChange(row) {
  let text = row.enabled === "0" ? "启用" : "停用";
  ElMessageBox.confirm('确认要"' + text + '""' + row.caseName + '"测试用例吗?', "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
  }).then(() => {
      updateTestCase({
          ...row,
      }).then(() => {
          ElMessage.success(text + "成功");
          getList();
      });
  }).catch(() => {
      row.enabled = row.enabled === "0" ? "1" : "0";
  })
}

const reset = () => {
  testCaseRef.value.resetFields()
};

const testCaseRef = ref()
const isNew = ref(true)

/** 添加 */
function handleAdd() {
  open.value = true;
  isNew.value = true
  title.value = "添加";
}

/** 修改 */
function handleUpdate(row) {
  form.value = { ...row };
  open.value = true;
  isNew.value = false
  title.value = "修改";
}

/** 提交按钮 */
function submitForm() {
  testCaseRef.value.validate((valid) => {
    if (valid) {
      if (isNew.value) {
        addTestCase(form.value).then(() => {
          ElMessage.success("添加成功");
          getList();
          open.value = false;
          reset();
        });
      } else {
        updateTestCase(form.value).then(() => {
          ElMessage.success("修改成功");
          getList();
          open.value = false;
          reset();
        });
      }
    }
  }); 
}

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

/** 配置按钮操作 */
function handleDeploy(row) {
  const params = { itemId: row.detectItemId, name: row.caseName, state: row.status };
  const fullPath = appendParamsToPath("/flow", params);
  const p = window.open(fullPath, "_blank");
}

getList();
</script>
