<!--
 * @Descripttion : 当前组件信息
 * @Author       : 无尘
 * @Date         : 2020-02-13 16:13:59
 * @LastEditors: 无尘
 * @LastEditTime: 2020-06-12 09:29:23
 * @FilePath     : \Hapi-demoj:\公司\haoban-3\src\components\company\add-relate.vue
 -->
<!--

  <add-relate :departObj="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" trigger="click">
          <div class="daily-store-select">
            <div class="select-search">
              <el-input placeholder="请输入code/手机号搜索进行账号关联" clearable maxlength="40" v-model="searchSelect" style="width: 100%;" prefix-icon="el-icon-search" @keyup.native="value => toInput(value, searchSelect)" @clear="clearSearch"> </el-input>
            </div>
            <div class="el-scrollbar define-search-select">
              <div class="el-select-dropdown__wrap el-scrollbar__wrap" style="margin-bottom: -5px; margin-right: -5px;">
                <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="text-ellipsis">{{ item.clerkName }}（{{ item.clerkCode }}）</span>
                        <div class="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.relationStatus == 1" class="font-12 color-909399">已添加不能关联</span><el-button v-if="item.relationStatus == 1" class="m-l-10" type="text" @click="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">{{ partForm.salerName }} <span v-if="!partForm.salerName" class="font-14 color-c0c4cc">请输入code/手机号搜索进行账号关联</span></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 limitInput from '@/components/limit-input.vue';
import { getRequest, postRequest } from '@/api/api';
import errMsg from '@/common/js/error';
import showMsg from '@/common/js/showmsg';
import { _debounce } from '@/common/js/public';
export default {
  name: 'add-relate',
  components: {
    limitInput
  },
  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
    };
  },
  methods: {
    /**
     * 解绑
     */
    toUnbind(row) {
      const that = this;
      that
        .$confirm(`导购账号（${row.clerkName}）已绑定${row.staffName}，是否确认解绑？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          that.postUnbind(row);
        })
        .catch(() => {});
    },
    postUnbind(row) {
      const that = this;
      let para = {
        staffId: row.staffId,
        clerkId: row.clerkId
      };
      postRequest('/haoban-manage3-web/del-clerk-relation', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            showMsg.showmsg('解绑成功', 'success');
            that.getTableList();
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 选择
     */
    checkStore(item) {
      const that = this;
      if (item.relationStatus == 1) {
        return false;
      }
      that.selectId = item.clerkId;
      that.partForm.salerName = item.clerkName;
    },
    /**
     * 输入
     */
    toInput: _debounce(function(e, value) {
      const that = this;
      if (that.searchSelect.trim() == '') {
        return false;
      }
      that.getData();
    }, 500),
    // 搜索清除
    clearSearch() {
      const that = this;
      that.storeData = [];
    },
    /**
     * 关闭弹窗
     */
    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');
    },
    /**
     * 确定保存
     */
    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
      };
      postRequest('/haoban-manage3-web/add-clerk-relation', params)
        .then(res => {
          let resData = res.data;
          that.loading = false;
          if (resData.errorCode == 1) {
            showMsg.showmsg('添加成功', 'success');
            that.$emit('refreshData', that.partForm);
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.loading = false;
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    getData() {
      const that = this;
      let para = {
        search: that.searchSelect
      };
      getRequest('/haoban-manage3-web/search-clerk-relation', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.storeData = resData.result || [];
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  },
  watch: {
    departObj(newData) {
      // const that = this;
      if (Object.keys(newData).length) {
        // that.partForm = newData;
      }
    }
  },
  mounted() {
    // const that = this;
    // that.getData();
    /* if (Object.keys(that.departObj).length) {
      that.partForm = that.departObj;
    } */
  }
};
</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;
  .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>
