<template>
  <el-drawer size="75%" title="选择个微账号" :visible.sync="shows" append-to-body destroy-on-close class="qw-user-select-drawer">
    <div class="drawer-container">
      <!-- 搜索表单 -->
      <el-card shadow="never" class="search-card">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="80px" class="search-form">
          <el-row :gutter="16">
            <el-col :span="8">
              <el-form-item label="认领人" prop="companyUserNickName">
                <el-input v-model="queryParams.companyUserNickName" placeholder="请输入" clearable size="small" @keyup.enter.native="handleQuery" @blur="trimInput('companyUserNickName')"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="请选择" clearable size="small">
                  <el-option v-for="item in statusOptions" :key="'status'+item.dictValue" :label="item.dictLabel" :value="item.dictValue"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户类型" prop="customerType">
                <el-select multiple v-model="ctsTypeArr" placeholder="请选择" clearable size="small">
                  <el-option v-for="(item, index) in typeOptions" :key="`${item.dictValue}-${index}`" :label="item.dictLabel" :value="item.dictValue"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="16">
            <el-col :span="8">
              <el-form-item label="创建时间" prop="createTime">
                <el-date-picker clearable size="small" v-model="dateRange" type="daterange" value-format="yyyy-MM-dd"
                  start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%;"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="领取时间" prop="receiveTimeRange">
                <el-date-picker clearable size="small" v-model="receiveTimeRange" type="daterange" value-format="yyyy-MM-dd"
                  start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%;"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户来源" prop="source">
                <el-select multiple v-model="sourceArr" placeholder="请选择" clearable size="small">
                  <el-option v-for="item in sourceOptions" :key="'source'+item.dictValue" :label="item.dictLabel" :value="item.dictValue"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="16">
            <el-col :span="8">
              <el-form-item label="客户标签" prop="tags">
                <el-select multiple v-model="tagIds" placeholder="请选择" clearable size="small">
                  <el-option v-for="(item, index) in tagsOptions" :key="`${item.dictValue}-${index}`" :label="item.dictLabel" :value="item.dictLabel"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="16" style="text-align: right;">
              <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
            </el-col>
          </el-row>
        </el-form>
      </el-card>

      <!-- 个微账号列表 -->
      <el-card shadow="never" class="table-card">
        <div slot="header" class="card-header">
          <span>个微账号列表</span>
          <el-tag v-if="selectedRows.length" type="success">已选择 {{ selectedRows.length }} 个账号</el-tag>
        </div>
        <el-table border v-loading="loading" :data="customerList" :row-key="getRowKeys" @selection-change="handleSelectionChange" size="small" ref="table" height="500">
          <el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
          <el-table-column label="微信昵称" align="center" prop="wxNickName" min-width="120"/>
          <el-table-column label="微信号" align="center" prop="wxNo" min-width="150"/>
          <el-table-column label="手机号" align="center" prop="phone" width="120"/>
          <el-table-column label="员工" align="center" prop="companyUserName" width="100"/>
        </el-table>
      </el-card>

      <!-- 底部按钮 -->
      <div class="footer-actions">
        <el-button @click="shows = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确定选择</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import { getCompanyList } from "@/api/company/company";
import {getCitys} from "@/api/store/city";
import {companyUserList} from "@/api/company/companyVoiceRobotic";

export default {
  name: "CustomerSelect",
  data() {
    return {
      rows: [], // 已选择的行数据
      selectedRows: [], // 已选择的行数据（别名）
      source:{
        title:"修改客户来源",
        open:false,
      },
      shows:false,
      deptOptions:[],
      receiveTimeRange:[],
      tagId:null,
      deptId:undefined,
      companyId:undefined,
      tagsOptions:[],
      ctsTypeArr:[],
      sourceArr:[],
      dateRange:[],
      cityIds:[],
      citys:[],
      tags:[],
      tagIds:[],
      inputVisible: false,
      inputValue: '',
      statusOptions:[],
      typeOptions:[],
      sourceOptions:[],
      sexOptions:[],
      pageSizes: [10, 20, 30, 50,100,500 ],
      show:{
        title:"客户详情",
        open:false,
      },
      companys:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      names: [],
      userIds: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户表格数据
      customerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        customerCode: null,
        customerName: null,
        mobile: null,
        sex: null,
        weixin: null,
        userId: null,
        createUserId: null,
        receiveUserId: null,
        customerUserId: null,
        address: null,
        location: null,
        detailAddress: null,
        lng: null,
        lat: null,
        status: null,
        isReceive: null,
        deptId: null,
        isDel: null,
        customerType: null,
        receiveTime: null,
        poolTime: null,
        companyId: null,
        isLine: null,
        source: null,
        tags: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // customerName: [
        //   { required: true, message: "客户名称不能为空", trigger: "blur" }
        // ],
        mobile: [
          { required: true, message: "手机号不能为空", trigger: "blur" }
        ],
        // sex: [
        //   { required: true, message: "性别不能为空", trigger: "blur" }
        // ],
        source: [
          { required: true, message: "客户来源不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getDicts("crm_customer_tag").then((response) => {
      this.tagsOptions = response.data;
    });
    this.getDicts("crm_customer_source").then((response) => {
      this.sourceOptions = response.data;
    });
    this.getDicts("common_sex").then((response) => {
      this.sexOptions = response.data;
    });
    this.getDicts("crm_customer_status").then((response) => {
      this.statusOptions = response.data;
    });
    this.getDicts("crm_customer_type").then((response) => {
      this.typeOptions = response.data;
    });
    getCompanyList().then(response => {
      this.companys = response.data;
    });
    this.getCitys();
  },
  methods: {
    trimInput(field) {
      if (typeof this.queryParams[field] === 'string') {
        this.queryParams[field] = this.queryParams[field].trim();
      }
    },
    setRows(rows){
      this.shows = true;
      this.rows = rows || [];
      this.selectedRows = rows || []; // 同步更新
      this.getList();
    },
    initSelect(){
      let row = this.rows;
      if(row && row.length > 0 && this.$refs.table){
        row.forEach(row => {
          this.$refs.table.toggleRowSelection(row, true);
        })
      }
    },
    getRowKeys(item){
      return item.id;
    },
    getCitys(){
        getCitys().then(res => {
          this.loading = false;
          this.citys=res.data;
        })
    },
    /** 查询客户列表 */
    getList() {
      this.loading = true;
      if(this.receiveTimeRange!=null&&this.receiveTimeRange.length==2){
        this.queryParams.receiveTimeRange=this.receiveTimeRange[0]+"--"+this.receiveTimeRange[1]
      }
      else{
        this.queryParams.receiveTimeRange=null;
      }
      if(this.ctsTypeArr.length>0){
        this.queryParams.customerType=this.ctsTypeArr.toString();
      }
      else{
        this.queryParams.customerType=null
      }

      if(this.sourceArr.length>0){
        this.queryParams.source=this.sourceArr.toString();
      }
      else{
        this.queryParams.source=null
      }
      if(this.tagIds.length>0){
        this.queryParams.tags=this.tagIds.toString();
      }
      else{
        this.queryParams.tags=null
      }
      companyUserList(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        if (this.$refs.table) {
          this.$refs.table.clearSelection();
        }
        this.customerList = response.data;
        this.loading = false;
        this.initSelect();
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.rows = selection;
      this.selectedRows = selection; // 同步更新
      this.ids = selection.map(item => item.id)
      // this.names = selection.map(item => item.qwUserName)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
     currDeptChange(val){
          this.queryParams.deptId=val;
          this.getList();
    },
    submitForm(){
      this.$nextTick(() => {
        this.$emit("success", {ids: this.ids, names: this.names, rows: this.rows})
        this.shows = false;
        this.$refs.table.clearSelection();
      })
    },
  }
};
</script>
<style scoped>
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  .el-dialog__wrapper {
    z-index: 100000;
  }
  .app-container {
    padding: 0;
  }
  .dialog-footer {
    position: absolute;
    bottom: 0;
    right: 20px;
    background: #FFF;
  }

  .drawer-container {
    display: flex;
    flex-direction: column;
    height: 100%;
    padding: 0 16px;
  }

  .search-card {
    margin-bottom: 12px;
  }
  .search-card >>> .el-card__body {
    padding: 16px 16px 0;
  }
  .search-form >>> .el-form-item {
    margin-bottom: 16px;
  }
  .search-form >>> .el-form-item__content {
    width: calc(100% - 80px);
  }
  .search-form >>> .el-select,
  .search-form >>> .el-date-editor {
    width: 100%;
  }

  .table-card {
    flex: 1;
    overflow: hidden;
    margin-bottom: 12px;
  }
  .table-card >>> .el-card__body {
    padding: 12px 16px;
  }
  .card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .footer-actions {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding: 12px 0;
    border-top: 1px solid #EBEEF5;
  }
  .footer-actions .el-button + .el-button {
    margin-left: 10px;
  }
</style>
