<template>
  <div>
    <!-- 表单筛选 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      inline
      v-show="showSearch"
      label-width="auto"
    >
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="问题类型">
            <el-select
              style="width: 100%"
              v-model="queryParams.type"
              placeholder="请选择状态"
              clearable
            >
              <el-option
                v-for="dict in typeOption"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="问题描述">
            <el-input
              v-model="queryParams.descripiton"
              placeholder="请输入问题描述"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 按钮组 -->
    <el-row :gutter="10" class="mb8">
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getTableList"
      ></right-toolbar>
    </el-row>
    <!-- 表格 -->
    <!-- @selection-change="handleSelectionChange" -->
    <el-table
      ref="tableRef"
      :class="[selectMode]"
      v-loading="loading"
      :data="tableList"
      :row-key="(row) => row.id"
      @select="handleSelect"
      @select-all="handleSelectAll"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
        reserve-selection
      />
      <el-table-column label="问题类型" align="center" prop="type">
        <template slot-scope="scope">
          {{ scope.row.type === "1" ? "单选" : "多选" }}
        </template>
      </el-table-column>
      <el-table-column
        label="问题描述"
        align="center"
        prop="descripiton"
        show-overflow-tooltip
      />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            >查看</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getTableList"
    />
    <div class="footer">
      <el-button type="primary" @click="handleConfirm">确 定</el-button>
      <el-button @click="handleCancel">取 消</el-button>
    </div>

    <!-- 详情弹窗 -->
    <el-dialog
      :title="title"
      :visible.sync="dlgVisible"
      append-to-body
      width="40%"
    >
      <AddAndEdit
        :loading="dlgLoading"
        :data="formData"
        :dlgType="3"
        @cancel="dlgVisible = false"
      ></AddAndEdit>
    </el-dialog>
  </div>
</template>

<script>
import { getList, getDetail } from "@/api/exerciseManage/question";
import AddAndEdit from "@/views/exerciseManage/question/components/addAndEdit.vue";
export default {
  components: { AddAndEdit },
  props: {
    // 传过来的勾选的数据
    selectedIds: {
      type: String,
      default: "",
    },
    // 勾选模式  single 单选  multiple 多选，默认多选
    selectMode: {
      type: String,
      default: "multiple",
    },
  },
  data() {
    return {
      // 显示搜索条件
      showSearch: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: "",
        descripiton: "",
      },
      // 时间
      dateRange: [],
      // 状态组
      typeOption: [
        { value: "1", label: "单选" },
        { value: "2", label: "多选" },
      ],
      // 表格相关
      loading: false,
      tableList: [],
      curSelection: [], // 存储当前勾选的数据
      total: 0,
      //  弹窗相关
      title: "",
      dlgVisible: false,
      formData: {},
      dlgLoading: false,
    };
  },
  created() {
    this.resetQuery();
  },
  watch: {
    // 传过来的勾选的数据
    selectedIds: {
      handler(newVal) {
        // console.log("selectedIds", newVal);
        if (newVal) {
          let arr = newVal.split(",");
          this.curSelection = arr.map((item) => ({ id: Number(item) }));
        } else {
          this.curSelection = [];
        }
      },
      immediate: true,
    },
  },
  methods: {
    showSelect() {
      this.$refs.tableRef.clearSelection();
      this.tableList.forEach((row) => {
        const isSelected = this.curSelection.some((item) => item.id === row.id);
        this.$refs.tableRef.toggleRowSelection(row, isSelected);
      });
    },
    // 确认选择
    handleConfirm() {
      this.$emit("confirm", this.curSelection);
      this.handleCancel();
    },
    // 关闭弹窗
    handleCancel() {
      this.$emit("close");
      // 清空选择
      this.$refs.tableRef.clearSelection();
    },
    // 搜索
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getTableList();
    },
    // 重置
    resetQuery() {
      this.dateRange = [];
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        type: "",
        descripiton: "",
      };
      this.getTableList();
    },
    // 表格选中
    handleSelect(selection, row) {
      // console.log("选择数据", selection, row);
      // 目前this.curSelection是所有传进来的选中项
      // 判断this.curSelection中有没有该操作项row
      const index = this.curSelection.findIndex((item) => item.id === row.id);
      // 如果有的话说明是取消选中，没有则是新选中的
      if (index === -1) {
        if (this.selectMode === "single") {
          this.curSelection = [row];
          this.showSelect();
        } else {
          this.curSelection.push(row);
        }
      } else {
        this.curSelection.splice(index, 1);
      }
    },
    handleSelectAll(selection) {
      // console.log("全选数据", selection);
      if (selection.length) {
        selection.forEach((row) => {
          if (!this.curSelection.some((item) => item.id === row.id)) {
            this.curSelection.push(row);
          }
        });
      } else {
        // 当前页面取消全选，获取当前页面全部数据的id
        const currentPageIds = this.tableList.map((item) => item.id);
        // console.log("currentPageIds", currentPageIds);
        this.curSelection = this.curSelection.filter(
          (item) => !currentPageIds.includes(item.id)
        );
      }
    },
    // 查看
    handleDetail(row) {
      this.title = "查看";
      this.dlgVisible = true;
      this.dlgLoading = true;
      getDetail(row.id)
        .then((res) => {
          if (res.code === 200) {
            this.formData = { ...res.data, categoryName: row.categoryName };
          }
        })
        .finally(() => (this.dlgLoading = false));
    },
    // 查询列表
    getTableList() {
      let params = this.addDateRange(this.queryParams, this.dateRange);
      this.loading = true;
      getList(params)
        .then((res) => {
          if (res.code === 200) {
            this.tableList = res.rows;
            this.total = res.total;
            this.$nextTick(() => this.showSelect());
          }
        })
        .finally(() => (this.loading = false));
    },
  },
};
</script>

<style lang="scss" scoped>
// 单选情况下不展示head的勾选框
::v-deep .single.el-table {
  thead .el-checkbox {
    display: none;
  }
}
.footer {
  text-align: right;
  margin-top: 40px;
}
</style>
