<!--
 * @Descripttion : 当前组件信息
 * @Author       : 无尘
 * @Date         : 2020-02-13 16:13:59
 * @LastEditors: 无尘
 * @LastEditTime: 2020-09-08 15:09:42
 * @FilePath     : \haoban-4\src\components\company\add-relate.vue
 -->
<!--

  <add-relate :depart-obj="departObj" @refreshData="refreshData"></add-relate>
  import addRelate from '@/components/company/add-relate.vue';
  -->

<template>
  <el-dialog width="600px" title="新增绑定" :visible.sync="departVisible" append-to-body :before-close="handleClose">
    <el-form :model="partForm" :rules="rules" ref="partForm" label-width="0px" class="dialog-form">
      <el-form-item label="" prop="salerName">
        <el-popover placement="bottom" title="" width="457" v-model="visible">
          <div class="daily-store-select">
            <div class="el-scrollbar define-search-select">
              <div class="el-select-dropdown__wrap el-scrollbar__wrap" style="overflow: auto;">
                <ul class="el-scrollbar__view el-select-dropdown__list">
                  <li :class="['el-select-dropdown__item', item.clerkId == selectId ? 'selected hover' : '']" v-for="item in storeData" :key="item.clerkId" @click="checkStore(item)">
                    <div class="flex flex-space-between">
                      <div style="line-height:26px;">
                        <span class="block text-ellipsis">{{ item.clerkName }}（{{ item.clerkCode }}）</span>
                        <div class="text-ellipsis font-12 color-909399">{{ item.storeName || '--' }}</div>
                      </div>
                      <span v-if="item.clerkId == selectId" class="font-12 color-2f54eb el-icon-check flex-align-center" style="display:flex;"></span>
                      <span v-if="item.bindFlag == 1" class="font-12 color-909399">已添加不能绑定</span><el-button v-if="item.bindFlag == 1" class="m-l-10" type="text" @click.stop="toUnbind(item)">解绑</el-button>
                    </div>
                  </li>
                  <li v-if="!storeData.length" class="text-center"><span>暂无数据</span></li>
                </ul>
              </div>
            </div>
          </div>
          <div class="show-select-num cursor-pointer w-558" slot="reference">
            <div class="select-search-input"><span class="el-icon-search"></span><span class="p-l-5">{{ partForm.salerName }}</span> <el-input placeholder="请输入code/手机号搜索进行账号绑定" maxlength="40" v-model="searchSelect" @keyup.native="value => toInput(value)" @clear="clearSearch"> </el-input></div>
          </div>
        </el-popover>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" :loading="loading" @click="submitForm('partForm')">确定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import fetch from '@/api/contact.js';
const { addStaffRelation, delStaffRelation, getClerkRelation } = fetch;
import showMsg from '@/common/js/showmsg';
import { _debounce } from '@/common/js/public';
export default {
  name: 'AddRelate',
  components: {
  },
  props: {
    departObj: {
      type: [ Object, Array ],
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      partForm: {
        salerName: ''
      },
      rules: {
        salerName: [
          {
            required: true,
            message: '请选择导购',
            trigger: 'change'
          }
        ]
      },
      searchSelect: '',
      storeData: [],
      selectId: '',
      departVisible: true,
      loading: false,
      visible: false
    };
  },
  methods: {
    /**
     * @description: 显示 pop
     * @author: 无尘
     */
    showPop() {
      const that = this;
      that.visible = true;
    },
    /**
     * @description: 解绑
     * @param {Object} row
     * @author: 无尘
     */
    toUnbind(row) {
      const that = this;
      that
        .$confirm(`导购账号（${row.clerkName}）已绑定${row.bindStaffName}，是否确认解绑？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          that.visible = true;
          that.postUnbind(row);
        })
        .catch(() => {
          that.visible = true;
        });
    },
    postUnbind(row) {
      const that = this;
      let para = {
        staffId: row.bindStaffId,
        clerkId: row.clerkId
      };
      delStaffRelation(para)
        .then(res => {
          if (res.code == '0000') {
            showMsg.showmsg('解绑成功', 'success');
            that.getData();
            that.visible = true;
          }else {
            that.$message({
              message: res.message || '接口异常',
              type: 'warning'
            });
          }
        })
        .catch(function(error) {

        });
    },
    /**
     * @description: 选择
     * @param {Object} item
     * @returns {Boolean}
     * @author: 无尘
     */
    checkStore(item) {
      const that = this;
      if (item.bindFlag == 1) {
        return false;
      }
      that.selectId = item.clerkId;
      that.partForm.salerName = item.clerkName;
      that.$set(that.partForm, 'salerName', item.clerkName);
      that.$forceUpdate();
      that.$nextTick(() => {
        that.$refs['partForm'].validate(valid => {
          if (valid) {
            return false;
          }
        });
      });
    },
    /**
     * @description: 输入
     * @author: 无尘
     */
    toInput: _debounce(function() {
      const that = this;
      if (that.searchSelect.trim() == '') {
        that.storeData = [];
        return false;
      }
      that.getData();
    }, 500),
    /**
     * @description: 搜索清除
     * @author: 无尘
     */
    clearSearch() {
      const that = this;
      that.storeData = [];
    },
    /**
     * @description: 关闭弹窗
     * @param {Function} done
     * @author: 无尘
     */
    handleClose(done) {
      const that = this;
      that.$refs['partForm'].resetFields();
      that.$emit('refreshData', 'close');
      done();
    },
    cancel() {
      const that = this;
      that.$refs['partForm'].resetFields();
      that.$emit('refreshData', 'close');
    },
    /**
     * @description: 确定保存
     * @param {String} form
     * @author: 无尘
     */
    submitForm: _debounce(function(form) {
      const that = this;
      that.loading = true;
      that.$refs[form].validate(valid => {
        if (valid) {
          that.postAdd();
        } else {
          that.loading = false;
          return false;
        }
      });
    }, 300),
    postAdd() {
      const that = this;
      let params = {
        staffId: that.departObj.staffId,
        clerkId: that.selectId
      };
      addStaffRelation(params)
        .then(res => {
          that.loading = false;
          if (res.code == '0000') {
            showMsg.showmsg('添加成功', 'success');
            that.$emit('refreshData', that.partForm);
          }else {
            that.$message({
              message: res.message || '接口异常',
              type: 'warning'
            });
          }
        })
        .catch(function(error) {
          that.loading = false;
        });
    },
    /**
     * @description: 获取关联导购
     * @author: 无尘
     */
    getData() {
      const that = this;
      let para = {
        search: that.searchSelect
      };
      getClerkRelation(para)
        .then(res => {
          that.storeData = res.result || [];
        })
        .catch(function(error) {

        });
    }
  }
};
</script>
<style lang="less" scoped>
.span-dot {
  display: inline-block;
  width: 6px;
  height: 6px;
  margin-right: 5px;
  background: rgba(217, 217, 217, 1);
  border-radius: 50%;
}

.w-95 {
  width: 95px;
}

.m-l-30 {
  margin-left: 30px;
}
.w-319 {
  width: 319px;
}
.w-558 {
  width: 558px;
}
.show-select-num {
  position: relative;
  display: inline-block;
  font-size: inherit;
  height: 32px;
  line-height: 32px;
  padding-left: 10px;
  -webkit-appearance: none;
  background-color: #fff;
  background-image: none;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  color: #606266;
  overflow: hidden;
  .select-search-input {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    white-space: nowrap;
    flex-wrap: nowrap;
    .el-input {
      width: auto;
      min-width: 327px;
      /deep/ .el-input__inner {
        border: none;
        background-color: transparent;
        &:focus {
          border-color: transparent;
          box-shadow: none;
        }
      }
    }
  }
  .el-select__caret {
    color: #c0c4cc;
    font-size: 14px;
    transition: transform 0.3s;
    transform: rotate(180deg);
    cursor: pointer;
    &.is-reverse {
      transform: rotate(0deg);
    }
  }
}
.daily-store-select {
  position: relative;
}
.selected {
  div {
    span {
      color: #2f54eb;
    }
  }
}
.el-form {
  min-height: 200px;
}
.el-select-dropdown__item {
  height: 52px;
  line-height: 52px;
}
.text-ellipsis {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
