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

      <el-form-item label="销售公司" prop="companyId">
        <el-select
          v-model="queryParams.companyId"
          placeholder="请选择或搜索销售公司"
          clearable
          filterable
          size="small"
          style="width: 220px"
          :disabled="lockedCompany"
          @change="handleCompanyChange"
        >
          <el-option
            v-for="item in companyOptions"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="销售" prop="salesId">
        <el-select
          v-model="queryParams.salesId"
          placeholder="可全局搜，或先选公司再搜"
          clearable
          filterable
          remote
          reserve-keyword
          :remote-method="remoteSearchSales"
          :loading="salesLoading"
          size="small"
          style="width: 240px"
          @focus="handleSalesFocus"
          @clear="handleSalesClear"
        >
          <el-option
            v-for="item in salesOptions"
            :key="item.id"
            :label="formatSalesLabel(item)"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否删除" prop="isDelete">
        <el-select v-model="queryParams.isDelete" placeholder="全部" clearable size="small" style="width: 140px">
          <el-option label="未删除" :value="0" />
          <el-option label="已删除" :value="1" />
        </el-select>
      </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="isDelete" width="90">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isDelete === 1" type="danger" size="mini">已删除</el-tag>
          <el-tag v-else type="success" size="mini">未删除</el-tag>
        </template>
      </el-table-column>
      <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";
import { listCustomerRoleOptions } from "@/api/app/customerRole";
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,
      salesLoading: false,
      // 总条数
      total: 0,
      // 客服成员表格数据
      roleList: [],
      companyOptions: [],
      salesOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyId: null,
        salesId: null,
        isDelete: 0,
      },
    };
  },
  computed: {
    lockedCompany() {
      return this.companyId !== null && this.companyId !== undefined && this.companyId !== '';
    },
  },
  created() {
    this.queryParams.pageNum = this.defaultPageNum;
    this.queryParams.pageSize = this.defaultPageSize;
    this.queryParams.companyId = this.companyId || null;
    // 解绑预填指定销售时，包含已删除销售
    if (this.ids && this.ids.length) {
      this.queryParams.isDelete = null;
    }
    this.loadCompanyOptions();
    this.getList();
    this.remoteSearchSales('');
  },
  watch: {
    selected: {
      immediate: true,
      handler() {
        this.setSelectionStatus();
      }
    },
    ids: {
      deep: true,
      handler(n, o) {
        const next = (n || []).map(String).join(',');
        const prev = (o || []).map(String).join(',');
        if (next === prev) {
          return;
        }
        this.queryParams.pageNum = 1;
        this.queryParams.salesId = null;
        this.queryParams.isDelete = (n && n.length) ? null : 0;
        this.getList();
        this.remoteSearchSales('');
      }
    },
    companyId: {
      handler(n) {
        this.reloadByCompany(n);
      }
    }
  },
  methods: {
    parseId(value) {
      if (value === null || value === undefined || value === '') {
        return null;
      }
      const num = Number(value);
      return Number.isNaN(num) ? value : num;
    },
    formatSalesLabel(item) {
      if (!item) {
        return '';
      }
      const name = item.memberName || '';
      const company = item.roleName ? `（${item.roleName}）` : '';
      return `${name}${company}`;
    },
    loadCompanyOptions() {
      listCustomerRoleOptions().then(response => {
        this.companyOptions = (response.rows || []).map(item => ({
          ...item,
          id: this.parseId(item.id)
        }));
      }).catch(() => {
        this.companyOptions = [];
      });
    },
    /**
     * 按公司刷新列表
     */
    reloadByCompany(companyId) {
      this.queryParams.companyId = companyId || null;
      this.queryParams.salesId = null;
      this.queryParams.pageNum = 1;
      this.salesOptions = [];
      this.remoteSearchSales('');
      this.getList();
    },
    handleCompanyChange() {
      this.queryParams.salesId = null;
      this.queryParams.pageNum = 1;
      this.salesOptions = [];
      this.remoteSearchSales('');
      this.getList();
    },
    handleSalesFocus() {
      if (!this.salesOptions.length) {
        this.remoteSearchSales('');
      }
    },
    handleSalesClear() {
      this.remoteSearchSales('');
    },
    /**
     * 远程搜索销售：可选先选公司再搜，也可不选公司全局搜
     */
    remoteSearchSales(keyword) {
      this.salesLoading = true;
      const qp = {
        pageNum: 1,
        pageSize: 50,
        memberName: keyword || null,
      };
      const companyId = this.lockedCompany ? this.companyId : this.queryParams.companyId;
      if (companyId) {
        qp.companyId = companyId;
      }
      if (this.queryParams.isDelete !== '' && this.queryParams.isDelete !== undefined && this.queryParams.isDelete !== null) {
        qp.isDelete = this.queryParams.isDelete;
      }
      listRole(qp).then(response => {
        this.salesOptions = (response.rows || []).map(item => ({
          ...item,
          id: this.parseId(item.id)
        }));
      }).catch(() => {
        this.salesOptions = [];
      }).finally(() => {
        this.salesLoading = false;
      });
    },
    /**
     * 查询客服成员列表
     */
    getList() {
      this.loading = true;
      let qp = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
      };
      const companyId = this.lockedCompany ? this.companyId : this.queryParams.companyId;
      if (companyId) {
        qp.companyId = companyId;
      }
      if (this.queryParams.isDelete !== '' && this.queryParams.isDelete !== undefined && this.queryParams.isDelete !== null) {
        qp.isDelete = this.queryParams.isDelete;
      }
      // 选了具体销售则按销售id精确查；否则按公司（或全局）查列表
      if (this.queryParams.salesId) {
        qp.ids = [String(this.queryParams.salesId)];
      } else if (this.ids && this.ids.length) {
        qp.ids = this.ids;
      }
      if (this.ignoreIds && this.ignoreIds.length) {
        qp.ignoreIds = this.ignoreIds;
      }
      listRole(qp).then(response => {
        this.roleList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.setSelectionStatus();
      }).catch(() => {
        this.loading = false;
      });
    },
    // 取消按钮
    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,
        companyId: this.companyId || null,
        salesId: null,
        isDelete: (this.ids && this.ids.length) ? null : 0,
      }
      this.salesOptions = [];
      this.resetForm("queryForm");
    },
    /**
     * 确定选择
     */
    confirmSelect() {
      try {
        this.$emit("confirm", this.selected);
      } catch (e) {
        console.warn('暂未指定确认选择回调');
      }
    },
    /**
     * 搜索按钮操作
     */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /**
     * 重置按钮操作
     */
    resetQuery() {
      this.reset();
      this.remoteSearchSales('');
      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>
