<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px"
      @submit.prevent="handleQuery">

      <el-form-item label="销售名称" prop="memberName">
        <el-input v-model="queryParams.memberName" placeholder="请输入销售名称" clearable size="small"
          @keydown.enter.native="handleQueryEnter" />
      </el-form-item>
      <el-form-item label="所属公司" prop="roleName">
        <el-input v-model="queryParams.roleName" placeholder="请输入所属公司" clearable size="small"
          @keydown.enter.native="handleQueryEnter" />
      </el-form-item>

      <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-form>

    <el-table
      v-loading="loading"
      :data="roleList"
      ref="roleList"
      :row-key="row => String(row.id)"
      :class="{ 'cus-role-single': !multiple }"
      @select="singleSelectHandler"
      @select-all="allSelectHandler"
     >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="销售id" align="center" prop="id" min-width="100"/>
      <el-table-column label="销售名称" align="center" prop="memberName" min-width="140" show-overflow-tooltip/>
      <el-table-column label="所属公司" align="center" prop="roleName" min-width="140" show-overflow-tooltip/>
      <el-table-column label="备注" align="center" prop="remark" min-width="160" show-overflow-tooltip/>
    </el-table>

    <div style="margin-top: 30px;display: flex;justify-content: center">
      <el-button type="warning" icon="el-icon-search" @click="confirmSelect">确定选择</el-button>
    </div>

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

<script>
import { listRole } from "@/api/app/user/userList";
export default {
  name: "SelectedCustomer",
  props: {
    defaultPageNum: {
      type: Number,
      default: 1
    },
    defaultPageSize: {
      type: Number,
      default: 10
    },
    selected: {
      type: Array,
      default: () => [],
    },
    // 是否允许多选，false 时只能勾选一个
    multiple: {
      type: Boolean,
      default: true,
    },
    // 排除的销售id
    ignoreIds: {
      type: Array,
      default: () => [],
    },
    // 仅查询指定销售id
    ids: {
      type: Array,
      default: () => [],
    },
    // 所属公司id：有值时仅查该公司下销售
    companyId: {
      type: [Number, String],
      default: null,
    },
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 客服成员表格数据
      roleList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        memberName: null,
        roleName: null,
        companyId: null,
      },
    };
  },
  created() {
    this.queryParams.pageNum = this.defaultPageNum;
    this.queryParams.pageSize = this.defaultPageSize;
    this.queryParams.companyId = this.companyId || null;
    this.getList();
  },
  watch: {
    selected: {
      immediate: true,
      handler(nv) {
        this.setSelectionStatus();
      }
    },
    companyId: {
      handler(n) {
        this.reloadByCompany(n);
      }
    }
  },
  methods: {
    /**
     * 按公司刷新列表（搜索页切换所属公司后调用）
     */
    reloadByCompany(companyId) {
      this.queryParams.companyId = companyId || null;
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /**
     * 查询客服成员列表
     */
    getList() {
      this.loading = true;
      let qp = { ...this.queryParams };
      if (this.companyId) {
        qp.companyId = this.companyId;
      } else if (!qp.companyId) {
        delete qp.companyId;
      }
      if (this.ignoreIds && this.ignoreIds.length) {
        qp['ignoreIds'] = this.ignoreIds;
      } else {
        delete qp.ignoreIds;
      }
      if (this.ids && this.ids.length) {
        qp['ids'] = this.ids;
      } else {
        delete qp.ids;
      }
      listRole(qp).then(response => {
        this.roleList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.setSelectionStatus();
      });
    },
    // 取消按钮
    cancel() {
      this.reset();
      try {
        this.$emit("cancel", this.selected);
      } catch (e) {
        console.warn('暂未指定确认选择回调');
      }
    },
    setSelectionStatus() {
      if (this.roleList.length == 0) {
        return;
      }
      this.$nextTick(() => {
        this.roleList.forEach(row => {
          // 判断当前行ID是否在全局选中集合中
          const isSelected = this.selected.some(si => row.id == si.id);
          this.$refs.roleList.toggleRowSelection(row, isSelected);
        });
      });
    },
    /**
     * 表单重置
     */
    reset() {
      this.queryParams = {
        pageNum: this.defaultPageNum,
        pageSize: this.defaultPageSize,
        memberName: null,
        roleName: null,
        companyId: this.companyId || null,
      }
      this.resetForm("form");
    },
    /**
     * 确定选择
     */
    confirmSelect() {
      try {
        this.$emit("confirm", this.selected);
      } catch (e) {
        console.warn('暂未指定确认选择回调');
      }
    },
    /**
     * 搜索按钮操作
     */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleQueryEnter(event) {
      // 确保事件对象存在
      if (event && event.preventDefault) {
        event.preventDefault(); // 阻止默认提交行为
      }
      this.handleQuery();
    },
    /**
     * 重置按钮操作
     */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.companyId = this.companyId || null;
      this.handleQuery();
    },    /**
     * 单选
     * @param selection
     * @param row
     */
    singleSelectHandler(selection, row) {
      // 单选模式：只保留当前行
      if (!this.multiple) {
        const isSelected = selection.some(l => l.id == row.id)
        this.$refs.roleList.clearSelection()
        if (isSelected) {
          this.$nextTick(() => {
            this.$refs.roleList.toggleRowSelection(row, true)
          })
        }
        try {
          this.$emit('selectionChange', {
            mode: 0,
            row,
            selected: isSelected
          })
        } catch (e) {
          console.warn('当前组件暂未指定selection回调')
        }
        return
      }
      let pm = {
        mode: 0,//0-单行选，1-全选
        row,//操作的行
      }
      //列表中找不到当前行数据，则说明是取消选中
      if (!selection.some(l => l.id == row.id)) {
        pm['selected'] = false;//设置取消选中
      } else {
        pm['selected'] = true;//设置选中
      }
      try {
        this.$emit("selectionChange", pm);
      } catch (e) {
        console.warn('当前组件暂未指定selection回调');
      }
    },
    /**
     * 全选
     * @param selection
     */
    allSelectHandler(selection) {
      // 单选模式不允许全选
      if (!this.multiple) {
        this.$refs.roleList.clearSelection()
        return
      }
      let pm = {
        mode: 1,//0-单行选，1-全选
        rows: this.roleList,//操作的所有行
        selected: selection.length > 0 ? true : false,
      }
      try {
        this.$emit("selectionChange", pm);
      } catch (e) {
        console.warn('当前组件暂未指定selection回调');
      }
    },
  }
};
</script>

<style scoped>
/* 单选模式隐藏表头全选勾选框 */
.cus-role-single ::v-deep .el-table__header-wrapper .el-checkbox {
  display: none;
}
</style>
