<template>
  <el-dialog
    title="关联客户"
    :visible.sync="visible"
    @close="handleClose"
    @open="open"
    v-dialogDrag
    custom-class="common-dialog over-dialog dig-cascade"
    :close-on-click-modal="false"
  >
    <el-form :model="paramForm"
      :disabled="openType === 'view'"
      label-position="left" ref="formRef"
      label-width="110px" size="mini">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="客户编码">
            <el-input v-model="paramForm.customerNo" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="客户名称">
            <el-input v-model="paramForm.customerName" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-button @click="doQuery" type="warning"
            size="mini" icon="el-icon-search">查询</el-button>
        </el-col>
      </el-row>
    </el-form>
    <div class="container">
      <div class="table-wrap">
        <div class="box">
          <div class="title">客户列表</div>
          <el-table
            :data="tableData"
            ref="tableRefLeft"
            highlight-current-row
            size="mini"
            stripe border height="100%"
            @select-all="selectAll"
            @select="select"
            @cell-dblclick="cellDblclick">
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column type="index" label="序号" width="50" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ pager.pageSize * (pager.currPage - 1) + scope.$index + 1}}
              </template>
            </el-table-column>
            <el-table-column
              v-for="(item, index) in colunms"
              :key="index"
              :prop="item.prop"
              :label="item.label"
              :fixed="item.fixed"
              :min-width="item.width"
              :show-overflow-tooltip="item.tooltip"
            ></el-table-column>
          </el-table>

          <!-- 分页-->
          <ls-pagination
            :curr-page.sync="pager.currPage"
            :page-size.sync="pager.pageSize"
            :total="pager.total"
            :page-options="pager.pageOptions"
            @query="doQuery">
          </ls-pagination>
        </div>

        <!-- 控制左右选中箭头-->
        <!--  <div class="bar-charts">
          <span @click="switchData('right')" class="el-icon-right"></span>
          <span @click="switchData('left')" class="el-icon-back"></span>
        </div> -->

        <div class="box">
          <div class="title">已选客户</div>

          <el-table
            :data="selectData"
            ref="tableRefRight"
            highlight-current-row
            size="mini"
            stripe border height="100%"
            @select-all="selectAllDel"
            @select="selectDel"
            @cell-dblclick="cellDblclickDel">
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column type="index" label="序号" width="50" show-overflow-tooltip>
            </el-table-column>

            <el-table-column
              v-for="(item, index) in colunms"
              :key="index"
              :prop="item.prop"
              :label="item.label"
              :fixed="item.fixed"
              :min-width="item.width"
              :show-overflow-tooltip="item.tooltip"
            ></el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <div style="text-align: center;margin-top: 10px;">
      <el-button @click="submitData" type="warning" size="mini">保存</el-button>
      <el-button @click="visible = false" type="default" size="mini">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'dig-customer',
  mounted() {},
  created() {

  },
  props: {
    customerInfo: {
      type: Object,
      default: () => {},
      required: true
    },

  },
  data() {
    return {
      visible: false,
      openTitle: '',
      openType: '',
      paramForm: {},
      customerId: '',
      applyType: '',
      remarks: '',
      salesName: '',
      cmFollowList: [],
      tableData: [],
      selectData: [],
      colunms: [
        //表格列
        { prop: 'customerNo', label: '客户编码', width: 80, fixed: false, tooltip: true },
        { prop: 'customerName', label: '公司名称', width: 80, fixed: false, tooltip: true },
        { prop: 'gradeId', label: '等级', width: 80, fixed: false, tooltip: true },
        { prop: 'areaName', label: '销售区域', width: 80, fixed: false, tooltip: true },
        { prop: 'deptName', label: '销售部门', width: 80, fixed: false, tooltip: true },
        { prop: 'salesName', label: '业务', width: 80, fixed: false, tooltip: true }
      ],

      //分页参数
      pager: {
        currPage: 1,
        pageSize: 10,
        pageOptions: [10, 20, 30, 50],
        total: 0
      }
    };
  },
  methods: {
    open() {
      this.doQuery();
    },
    handleClose() {
      this.$refs['formRef'].resetFields();
      Object.keys(this.paramForm).forEach(key => (this.paramForm[key] = ''));
      // this.doQuery();
      this.selectData = [];
      this.$refs.tableRefLeft.clearSelection(); //清空用户的选择
      this.visible = false;
    },
    doQuery() {
      let param = {
        currPage: this.pager.currPage,
        pageSize: this.pager.pageSize,
        customerNo: this.paramForm.customerNo,
        customerName: this.paramForm.customerName,
        approveStatus: 'audited' //已通过
      };
      //如果是终端客户的话，只能查询终端客户和特约经销商。
      if (this.customerInfo.type == 'agentApply' || this.customerInfo.type == 'agentList') {
        param.customerClassifyIds = ['ternimalCustomer', 'franchisedDealer'];
      }
      this.$ajax.post({
        domain: 'crmCmUrl',
        url: 'cmInfo.findAgentCorrelationPage',
        data: JSON.stringify(param),
        requestType: 'body',
        showLoad: true,
        success: function(res) {
          if (res.errorCode === 200) {
            this.tableData = res.data.records || [];
            this.pager.total = res.data.total;
            this.tableData.forEach((item, i) => {
              item.cmFollowList.forEach(item2 => {
                if (item2.whetherMain == 'Y') {
                  item.deptName = item2.deptName;
                  item.salesRepresent = item2.salesRepresent;
                  item.salesName = item2.salesName;
                  item.assistantName = item2.assistantName;
                }
              });
            });
            this.selectData.forEach( item =>{
              for(let i = 0; i < this.tableData.length; i++){
                if(item.id === this.tableData[i].id){
                  this.$nextTick( () => {
                    this.$refs.tableRefLeft.toggleRowSelection(this.tableData[i], true);//选中
                  })
                  break;
                }
              }
            })
          }
        }.bind(this),
        error: function(res) {
          this.$message.error(res.body.msg || res.msg);
        }.bind(this)
      });
    },
    submitData() {
      if (this.selectData.length == 0) {
        this.$message('请选择关联客户信息!');
        return;
      }

      if(this.customerInfo.type != 'groupApply'){
        if (this.selectData.length > 1) {
          let status = 0;
          let deptName = this.selectData[0].deptName;
          for (let i = 0; i < this.selectData.length; i++) {
            if (this.selectData[i].deptName != deptName) {
              status += 1;
            }
          }
          if (status > 0) {
            this.$message('报备请选择同一部门!');
            return;
          }
        }
      }

      this.$parent.setTableData(this.selectData);
      this.visible = false;
    },
    //全选选中赋值右边操作
    selectAll(arr) {
      // let addItems = arr.filter(a => this.selectData.every( s => s.id !== a.id));
      // this.selectData = this.selectData.concat(addItems);
      this.selectData = JSON.parse(JSON.stringify(arr));
      this.selectData.forEach(item=> item.customerId = item.id);
    },
    //单选选中赋值右边操作
    select(selects, row) {
      this.onSetData(row);
      let index = selects.findIndex(item => item.id === row.id);
      if(index === -1){//已经取消选中
        this.onDeleteData(row);
      }
    },
    cellDblclick(row, column, event){
      this.onSetData(row);
    },
    onSetData(row){
      let valid = this.selectData.some( item => item.id === row.id);
      if(!valid){
        let obj = JSON.parse(JSON.stringify(row));
        obj.customerId = row.id;
        this.selectData.push(obj);
      }
    },
    //右边已选中全选移除操作
    selectAllDel() {
      this.selectData = [];
      this.$refs.tableRefLeft.clearSelection(); //清空用户的选择
    },
    //右边单选已选中移除操作
    selectDel(selects, row) {
      this.onDeleteData(row);
    },
    cellDblclickDel(row, column, event){
      this.onDeleteData(row);
    },
    onDeleteData(row){
      this.selectData.some((item, i) => {
        if (item.id === row.id) {
          for(let i = 0; i < this.tableData.length; i++){
             if(row.id === this.tableData[i].id){
               this.$refs.tableRefLeft.toggleRowSelection(this.tableData[i], false);
               break;
             }
          }
          this.selectData.splice(i, 1);
          return true;//在数组的some方法中，若是return true，就会当即终止这个数组的后续循环
        }
      });
    },

  }
};
</script>

<style type="text/css" scoped lang="scss">
@mixin flex-column {
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.over-dialog.dig-cascade {
  .container {
    flex: 1;
    @include flex-column;

    .btns {
      padding: 10px 0;
      display: flex;
      justify-content: flex-end;
    }
    .table-wrap {
      flex: 1;
      display: flex;
      overflow: hidden;
      .box {
        flex: 1;
        @include flex-column;
        background-color: #f5f5f5;
        border-radius: 2px;
        padding: 5px;

        &:nth-child(2) {
          margin: 0 10px;
        }
        .title {
          font-size: 16px;
          padding: 5px 0;
          font-weight: bold;
        }
      }
      .bar-charts {
        width: 40px;
        margin: 0 20px;
        background: #b3d8ff;
        border: 1px solid #b3d8ff;
        border-radius: 5px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        font-size: 24px;
        span {
          color: #409eff;
          cursor: pointer;
          &:last-child {
            margin-top: 20px;
          }
        }
      }
    }
    .el-table .el-table__empty-block {
      min-height: unset;
    }
  }
}
</style>
