<template>
  <el-drawer size="75%" title="客户选择" :visible.sync="shows" append-to-body>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
        <el-form-item label="公司名称" prop="companyId">
          <el-select filterable  v-model="queryParams.companyId" :disabled="designatedCompany" placeholder="请选择公司名称"  @change="companyChange" clearable size="small">
            <el-option
              v-for="item in companys"
              :key="item.companyId"
              :label="item.companyName"
              :value="item.companyId"
            />
          </el-select>
        </el-form-item>
        <el-form-item >
          <treeselect style="width: 220px" :clearable="false"  v-model="queryParams.deptId"  :options="deptOptions" :show-count="true" placeholder="请选择归属部门" />
        </el-form-item>
        <el-form-item label="认领人" prop="companyUserNickName">
          <el-input
            v-model="queryParams.companyUserNickName"
            placeholder="请输入认领人"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <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-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-form-item label="创建时间" prop="createTime">
          <el-date-picker clearable size="small" style="width: 205.4px"
                          v-model="dateRange"
                          type="daterange"
                          value-format="yyyy-MM-dd"
                          start-placeholder="开始日期" end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="领取时间" prop="receiveTimeRange">
          <el-date-picker
            style="width:205.4px"
            clearable size="small"
            v-model="receiveTimeRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <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-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-form-item>
          <el-button type="cyan" 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-row :gutter="10" class="mb8" v-if="designatedCompany">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="checkWithCondition()"
        >按筛选条件选中
        </el-button>
      </el-col>
    </el-row>
      <el-table border v-loading="loading" :data="customerList" :row-key="getRowKeys" @selection-change="handleSelectionChange" size="mini" ref="table" height="450">
        <el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
        <el-table-column label="ID" align="center" prop="customerId" />
        <el-table-column label="公司名称" align="center" prop="companyName" width="300"/>
        <el-table-column label="客户编码" align="center" prop="customerCode" width="150"/>
        <el-table-column label="客户名称" align="center" prop="customerName" />
        <el-table-column label="手机号码" align="center" prop="mobile" width="90"/>
        <el-table-column  label="性别" align="center" prop="sex" width="55">
          <template slot-scope="scope">
            <el-tag prop="sex" v-for="(item, index) in sexOptions" :key="'sex'+index"   v-if="scope.row.sex==item.dictValue">{{item.dictLabel}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="微信号" align="center" prop="weixin" width="95"/>
        <el-table-column label="所在地" align="center" prop="address" />
        <el-table-column label="标签" align="center" prop="tags" width="100" :show-overflow-tooltip="true"/>
        <el-table-column  label="客户来源" align="center" prop="source">
          <template slot-scope="scope">
            <el-tag prop="source" v-for="(item, index) in sourceOptions"  :key="'source'+index"    v-if="scope.row.source==item.dictValue">{{item.dictLabel}}</el-tag>
          </template>
        </el-table-column>

        <el-table-column  label="客户类型" align="center" prop="customerType">
          <template slot-scope="scope">
            <el-tag prop="customerType" v-for="(item, index) in typeOptions" :key="'customerType'+index"   v-if="scope.row.customerType==item.dictValue">{{item.dictLabel}}</el-tag>
          </template>
        </el-table-column>

        <el-table-column  label="客户状态" align="center" prop="status">
          <template slot-scope="scope">
            <el-tag prop="status" v-for="(item, index) in statusOptions"  :key="'status'+index"  v-if="scope.row.status==item.dictValue">{{item.dictLabel}}</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="认领人" align="center" prop="companyUserNickName" />
        <el-table-column label="领取时间" align="center" prop="receiveTime"  width="135"/>
        <el-table-column label="创建时间" align="center" prop="createTime" width="135"/>
        <el-table-column label="最后一次跟进时间" align="center" prop="lastTime" width="180">
        </el-table-column>
        <el-table-column label="入公海时间" align="center" prop="poolTime" width="180" />
        <el-table-column label="操作" fixed="right" width="180px" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleShow(scope.row)"
              v-hasPermi="['crm:customer:query']"
            >查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer" style="width: 100%;display: flex;flex-direction: row-reverse;margin-top: 20px;z-index: 9898989;padding-top: 5px">
        <el-button type="primary" @click="submitForm" style="margin-bottom: 5px">确 定</el-button>
      </div>
      <el-drawer
        size="75%"
        :title="show.title" :visible.sync="show.open" append-to-body>
        <customer-details  ref="customerDetails" />
      </el-drawer>
    </div>
  </el-drawer>
</template>

<script>
import { listCustomerAll,listNoPage } from "@/api/crm/customer";
import { getCompanyList } from "@/api/company/company";
import customerDetails from '@/views/crm/components/customerDetails.vue';
import editCustomerSource from '@/views/crm/components/editSource.vue';
import {getCitys} from "@/api/store/city";

import { treeselect } from "@/api/company/companyDept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "CustomerSelect",
  components: { customerDetails,editCustomerSource,Treeselect },
  data() {
    return {
      designatedCompany:false,
      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();
    this.getList();
  },
  methods: {
    setRows(rows){
      this.shows = true;
      this.rows = rows;
      this.initSelect();
    },
    setRowsDesignatedCompany(rows,companyId){
      this.designatedCompany = true;
      this.shows = true;
      this.rows = rows;
      this.companyChange(companyId);
      this.initSelect();
      this.queryParams.companyId = companyId;
    },
    initSelect(){
      if(this.rows && this.rows.length > 0){
        this.rows.forEach(row => {
          this.$refs.table.toggleRowSelection(row);
        })
      }
    },
    getRowKeys(item){
      return item.customerId;
    },
    handleEditSource(){
      this.source.open=true;
      var that=this;
      setTimeout(() => {
        that.$refs.editSource.handleEdit(that.ids);
      }, 200);

    },
    closeSource(){
      this.source.open=false;
      this.getList();
    },
    tagsChange(e){
      var item=this.tagsOptions.find(val => val.dictValue === e);
      console.log(item);
      this.tags.push(item.dictLabel);
      this.form.tags=this.tags.toString();
    },
    handleCityChange(value) {
      console.log(value);
      var nodes=this.$refs.citySelect.getCheckedNodes();
      this.form.address=nodes[0].pathLabels[0]+"-"+nodes[0].pathLabels[1]+"-"+nodes[0].pathLabels[2];
      this.form.cityIds=value.toString();
    },
    getCitys(){
        getCitys().then(res => {
          this.loading = false;
          this.citys=res.data;
        })
    },
    handleClose(tag) {
        this.tags.splice(this.tags.indexOf(tag), 1);
        this.form.tags=this.tags.toString();
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.tags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = '';
      this.form.tags=this.tags.toString();
    },
    handleShow(row){
      var that=this;
      that.show.open=true;
      setTimeout(() => {
          that.$refs.customerDetails.getDetails(row.customerId);
      }, 200);
    },
    /** 查询客户列表 */
    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
      }
      listCustomerAll(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.customerList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.initSelect();
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.rows = selection;
      this.ids = selection.map(item => item.customerId)
      this.names = selection.map(item => item.customerName)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    getTreeselect() {
        var that=this;
        var param={companyId:this.companyId}
        treeselect(param).then((response) => {
          this.deptOptions = response.data;
          console.log(this.deptOptions)
          if(response.data!=null&&response.data.length>0){
            //this.queryParams.deptId=response.data[0].id;
          }
        });
    },
    companyChange(val){
      console.log(val);
      this.companyId=val;
      this.getTreeselect();
    },
     currDeptChange(val){
          this.queryParams.deptId=val;
          this.getList();
    },
    submitForm(){
      console.log(this.ids);
      this.$nextTick(() => {
        this.$emit("success", {ids: this.ids, names: this.names, rows: this.rows})
        this.shows = false;
        this.$refs.table.clearSelection();
      })
    },
    //按照筛选条件选择客户
    checkWithCondition(){

    let queryParamNoPage = {};
    queryParamNoPage = this.queryParams;
    if(this.receiveTimeRange!=null&&this.receiveTimeRange.length==2){
        queryParamNoPage.receiveTimeRange=this.receiveTimeRange[0]+"--"+this.receiveTimeRange[1]
      }
      else{
        queryParamNoPage.receiveTimeRange=null;
      }
      if(this.ctsTypeArr.length>0){
        queryParamNoPage.customerType=this.ctsTypeArr.toString();
      }
      else{
        queryParamNoPage.customerType=null
      }

      if(this.sourceArr.length>0){
        queryParamNoPage.source=this.sourceArr.toString();
      }
      else{
        queryParamNoPage.source=null
      }
      if(this.tagIds.length>0){
        queryParamNoPage.tags=this.tagIds.toString();
      }
      else{
        queryParamNoPage.tags=null
      }
      listNoPage(this.addDateRange(queryParamNoPage, this.dateRange)).then(response => {
        let resList = response.rows; 
        this.ids = [];
        this.names = [];
        this.rows = [];
        if(!!resList){
          this.ids = resList.map(item => item.customerId);
          this.names = resList.map(item => item.customerName);
          this.rows = resList;
        }
        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;
  }
</style>
