<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="detectName">
              <el-input
                v-model="queryParams.detectName"
                clearable
                placeholder="请输入检测项名称"
                style="width: 100%"
                @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="detectDesc">
              <el-input
                v-model="queryParams.detectDesc"
                clearable
                placeholder="请输入检测项描述"
                style="width: 100%"
                @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="sceneCode">
              <el-select v-model="queryParams.sceneCode" clearable placeholder="请选择场景类型">
                <el-option v-for="item in sceneList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </template>
      </TableSearch>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['test:detect:add']"
            icon="Plus"
            plain
            type="primary"
            @click="handleAdd"
            >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['test:detect:edit']"
            :disabled="single"
            icon="Edit"
            plain
            type="success"
            @click="handleUpdate"
            >修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['test:detect:remove']"
            :disabled="multiple"
            icon="Delete"
            plain
            type="danger"
            @click="handleDelete"
            >删除
          </el-button>
        </el-col>
        <!--      <el-col :span="1.5">-->
        <!--        <el-button-->
        <!--            type="warning"-->
        <!--            plain-->
        <!--            icon="Download"-->
        <!--            @click="handleExport"-->
        <!--            v-hasPermi="['test:detect:export']"-->
        <!--        >导出-->
        <!--        </el-button>-->
        <!--      </el-col>-->
        <right-toolbar
          v-model:showSearch="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row>
    </div>

    <div :style="containerHeight">
      <el-table
        v-loading="loading"
        height="100%"
        :data="detectList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column align="center" type="selection" width="55" />
        <el-table-column
          align="center"
          label="id"
          prop="id"
          show-overflow-tooltip
        />
        <el-table-column
          align="center"
          label="检测项名称"
          prop="detectName"
          show-overflow-tooltip
        />
        <el-table-column
          align="center"
          label="检测项描述"
          prop="detectDesc"
          show-overflow-tooltip
        />
        <el-table-column align="center" label="所属分组" prop="groupId">
          <template #default="scope">
            {{
              groupList?.find((item) => item.value === scope.row.groupId)[
                "label"
              ]
            }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="备注"
          prop="remark"
          show-overflow-tooltip
        />
        <el-table-column align="center" label="启用状态" prop="status">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-text="启用"
              active-value="0"
              inactive-text="停用"
              inactive-value="1"
              inline-prompt
              @change="handleChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" label="配置状态" prop="isDeploy">
          <template #default="scope">
            <TableTags
              :options="[
                {
                  label: '已配置',
                  value: '0',
                  type: 'success',
                },
                {
                  label: '未配置',
                  value: '1',
                  type: 'warning',
                },
              ]"
              :value="scope.row.isDeploy"
            ></TableTags>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          class-name="small-padding fixed-width"
          label="操作"
          width="200"
        >
          <template #default="scope">
            <el-button
              v-hasPermi="['test:detect:edit']"
              icon="Edit"
              link
              type="primary"
              @click="handleUpdate(scope.row)"
            >
              修改
            </el-button>
            <el-button
              v-hasPermi="['device:terminal:deploy']"
              icon="Cpu"
              link
              type="primary"
              @click="handleDeploy(scope.row)"
              >配置
            </el-button>
            <!--          <el-button v-hasPermi="['device:terminal:deploy']" icon="Cpu" link type="primary"-->
            <!--                     @click="()=>dialogVisible=true">配置参数-->
            <!--          </el-button>-->
            <el-button
              v-hasPermi="['test:detect:remove']"
              icon="Delete"
              link
              type="primary"
              @click="handleDelete(scope.row)"
              >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

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

    <!-- 添加或修改检测项配置对话框 -->
    <el-dialog v-model="open" :title="title" append-to-body width="500px">
      <el-form ref="detectRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="检测项名称" prop="detectName">
          <el-input v-model="form.detectName" placeholder="请输入检测项名称" />
        </el-form-item>
        <el-form-item label="检测项描述" prop="detectDesc">
          <el-input v-model="form.detectDesc" placeholder="请输入检测项描述" />
        </el-form-item>
        <el-form-item label="所属分组" prop="groupId">
          <el-select v-model="form.groupId" placeholder="请选择所属分组">
            <el-option
              v-for="group in groupList"
              :key="group.value"
              :label="group.label"
              :value="group.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="场景类型" prop="sceneCode">
          <el-select v-model="form.sceneCode" placeholder="请输入检测项描述">
            <el-option v-for="item in sceneList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            :rows="2"
            placeholder="请输入备注"
            type="textarea"
          />
        </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>

    <el-dialog v-model="dialogVisible" title="参数配置" width="1080px">
      <EditTable></EditTable>
    </el-dialog>
  </div>
</template>

<script name="Detect" setup>
import {
  addDetect,
  delDetect,
  getDetect,
  listDetect,
  updateDetect,
} from "@/api/test/detect";
import TableSearch from "@/components/TableSearch/index.vue";
import { listGroup } from "@/api/system/group.js";
import { appendParamsToPath } from "@/utils/fn.js";
import TableTags from "@/components/TableTags/index.vue";
import EditTable from "@/components/EditTable/index.vue";

import { useContainerHeight } from "@/hooks/tableHeight";

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

const { proxy } = getCurrentInstance();

const detectList = ref([]);
const open = ref(false);
const dialogVisible = 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 sceneList = [{
  label: '普通',
  value: 'NORMAL'
},{
  label: '语音交互-唤醒场景',
  value: 'VI_WAKEUP_CORPUS'
},{
  label: '语音交互-单次对话场景',
  value: 'VI_SINGLE_CORPUS'
},{
  label: '语音交互-连续对话场景',
  value: 'VI_CONTINUOUS_CORPUS'
},{
  label: '触控交互',
  value: 'TI_TOUCH'
}]

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    detectName: null,
    detectDesc: null,
    status: null,
    detectVersion: null,
  },
  rules: {
    detectName: [
      { required: true, message: "检测项名称不能为空", trigger: "blur" },
    ],
    groupId: [
      { required: true, message: "所属分组不能为空", trigger: "change" },
    ],
  },
});

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

/** 查询检测项配置列表 */
function getList() {
  loading.value = true;
  listDetect(queryParams.value).then((response) => {
    detectList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

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

// 表单重置
function reset() {
  form.value = {};
  proxy.resetForm("detectRef");
}

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

/** 重置按钮操作 */
function resetQuery() {
  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;
  getDetect(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改检测项配置";
  });
}

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

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

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

// 监听 visibilitychange 事件
// document.addEventListener("visibilitychange", () => {
//   if (document.visibilityState === "visible") {
//     // 用户重新进入当前标签页
//     getList();
//   }
// });

const isMount = ref(false);

onMounted(() => {
  handleGetSystemGroup();
  getList();

  nextTick(() => {
    isMount.value = true;
  });
});

/** 状态开关操作 */
function handleChange(row) {
  if (isMount.value) {
    updateDetect({ status: row.status, id: row.id }).then((response) => {
      proxy.$modal.msgSuccess("修改成功");
      getList();
    });
  }
}

const groupList = ref([]);

/** 获取系统分组列表(默认传1查询检测项列表) */
function handleGetSystemGroup(row) {
  listGroup({ type: 1 }).then((response) => {
    groupList.value = response.rows?.map((item) => {
      return {
        label: item.groupName,
        value: item.groupId,
      };
    });
  });
}
</script>
