<template>
  <div class="app-container">
    <div ref="topContainerRef">
      <el-form
        :model="queryParams"
        ref="queryRef"
        :inline="true"
        v-show="showSearch"
        label-width="100px"
      >
        <el-form-item label="方案名称" prop="schemeName">
          <el-input
            v-model="queryParams.schemeName"
            placeholder="请输入方案名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="queryParams.remark"
            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-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:scheme:add']"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:scheme:edit']"
            >修改</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:scheme:remove']"
            >删除</el-button
          >
        </el-col>
        <!-- <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:scheme: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"
        :data="schemeList"
        height="100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="方案ID" align="center" prop="schemeId" min-width="150" show-overflow-tooltip />
        <el-table-column label="所属项目ID" align="center" prop="projectId" min-width="150" show-overflow-tooltip />
        <el-table-column label="方案名称" align="center" prop="schemeName" min-width="150" show-overflow-tooltip />
        <el-table-column
          label="语料ID列表"
          align="center"
          prop="corpusIds"
          width="300"
          show-overflow-tooltip
        />
        <el-table-column label="排序" align="center" prop="sort" />
        <el-table-column label="备注" align="center" prop="remark" min-width="150" show-overflow-tooltip />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          width="200"
          fixed="right"
        >
          <template #default="scope">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:scheme:edit']"
              >修改</el-button
            >
            <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:scheme:remove']"
              >删除</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"
      />
    </div>

    <!-- 添加或修改语音交互-方案对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="700px"
      :append-to-body="false"
      body-class="plan_dialog"
    >
      <el-form ref="schemeRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="方案名称" prop="schemeName">
          <el-input v-model="form.schemeName" placeholder="请输入方案名称" />
        </el-form-item>
        <el-form-item label="播放配置" prop="sceneType">
          <el-select
            v-model="form.sceneType"
            placeholder="Select"
            style="width: 240px"
          >
            <el-option
              v-for="item in settingOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="唤醒语料列表" prop="wakeId">
          <el-select
            v-model="form.wakeId"
            placeholder="Select"
            style="width: 240px"
          >
            <el-option
              v-for="item in corpusIdsOptions"
              :key="item.parentId"
              :label="item.corpusName"
              :value="item.parentId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :step="1" step-strictly />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div v-if="form.sceneType && form.sceneType != 1">
        <div>语料配置({{ form.sceneType == 2 ? "单次" : "连续" }})</div>
        <!-- <Setting
          type="1"
          v-if="form.sceneType == 2"
          :corpusIds="selectCorpusIds"
          @updateSelectRows="getSelectRows"
        /> -->
        <Single v-if="form.sceneType == 2" :corpusIds="selectCorpusIds" @updateSelectRows="getSelectRows" />
        <Setting
          type="0"
          v-if="form.sceneType == 3"
          :corpusIds="selectCorpusIds"
          @updateSelectRows="getSelectRows"
        />
      </div>
      <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>
import {
  listScheme,
  getScheme,
  delScheme,
  addScheme,
  updateScheme,
} from "@/api/vi/plan";
import { listCorpus } from "@/api/vi/corpus";
import Setting from "./setting.vue";
import { onMounted } from "vue";
import { ElMessage } from "element-plus";
import { useContainerHeight } from "@/hooks/tableHeight";
import Single from "./single.vue";

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

const route = useRoute();

const { proxy } = getCurrentInstance();

const schemeList = 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 selectCorpusIds = ref("");

const data = reactive({
  form: {
    corpusIds: null,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: route.params.id,
    schemeName: null,
    corpusIds: null,
  },
  rules: {
    projectId: [
      { required: true, message: "所属项目ID不能为空", trigger: "blur" },
    ],
    schemeName: [
      { required: true, message: "方案名称不能为空", trigger: "blur" },
    ],
  },
});

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

/** 查询语音交互-方案列表 */
function getList() {
  loading.value = true;
  listScheme(queryParams.value).then((response) => {
    schemeList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

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

// 表单重置
function reset() {
  form.value = {
    schemeId: null,
    schemeName: null,
    corpusIds: null,
    remark: null,
  };
  proxy.resetForm("schemeRef");
}

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

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

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

const settingOptions = [
  { value: 1, label: "唤醒场景" },
  { value: 2, label: "单次对话场景" },
  { value: 3, label: "连续对话场景" },
];

const corpusIdsOptions = ref([]);

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加方案";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _schemeId = row.schemeId || ids.value;
  getScheme(_schemeId).then((response) => {
    form.value = response.data;
    selectCorpusIds.value = response.data.corpusIds;
    title.value = "修改方案";
    open.value = true;
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["schemeRef"].validate((valid) => {
    if (valid) {
      if (form.value.sceneType === 1) {
        form.value.corpusIds = null;
      } else {
        if (!form.value?.corpusIds || form.value?.corpusIds?.length === 0) {
          ElMessage.error("请先添加语料");
          return;
        }
      }
      if (form.value.schemeId != null) {
        updateScheme(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addScheme({
          ...form.value,
          projectId: route.params.id,
        }).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _schemeIds = row.schemeId || ids.value;
  proxy.$modal
    .confirm('是否确认删除语音交互-方案编号为"' + _schemeIds + '"的数据项？')
    .then(function () {
      return delScheme(_schemeIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

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

const getWakeList = () => {
  listCorpus({
    pageNum: 1,
    pageSize: 100000,
    type: "WAKEUP",
    continuous: 1,
  })
    .then((response) => {
      corpusIdsOptions.value = response.rows;
    })
    .catch((err) => {});
};

const getSelectRows = (arr) => {
  const corpusIds = arr.map((item) => item.id);
  form.value.corpusIds = corpusIds.toString();
};

onMounted(() => {
  getList();
  getWakeList();
});
</script>
<style lang="scss" scoped>
:deep() {
  .plan_dialog {
    .el-select {
      width: 100% !important;
    }
  }
}
</style>
