<!--
 * @Descripttion : 当前组件信息
 * @Author       : 无尘
 * @Date         : 2020-02-13 16:13:59
 * @LastEditors: Drama
 * @LastEditTime: 2022-09-26 13:12:59
 * @FilePath: /haoban-3/src/components/company/add-relate-new.vue
 -->
<!--

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

<template>
  <el-dialog custom-class="add-remote-dialog" width="600px" title="新增关联" :visible.sync="departVisible" append-to-body :before-close="handleClose">
    <el-form :model="partForm" label-width="95px" ref="partForm" class="dialog-form">
      <el-form-item label="关联角色" prop="manageFlag">
        <el-radio-group v-model="partForm.manageFlag" @change="manageChange">
          <el-radio :label="0">导购</el-radio>
          <el-radio :label="1">区经/督导</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="关联账号" prop="salerName">
        <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" v-if="searchSelect">
            <div class="el-select-dropdown__wrap el-scrollbar__wrap test" style="margin-bottom: -5px; margin-right: -5px">
              <ul class="el-scrollbar__view el-select-dropdown__list" v-loading="searchLoading">
                <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.relationStatus == 1" class="font-12 color-909399">已添加不能关联</span><el-button v-if="item.relationStatus == 1" class="m-l-10" type="text" @click.stop="toUnbind(item)">解绑</el-button>
                  </div>
                </li>
                <li v-if="!storeData.length" class="text-center" style="margin-top: 10px"><span>暂无数据</span></li>
              </ul>
            </div>
          </div>
          <div v-if="isShowError" class="el-form-item__error">请选择关联账号</div>
        </div>
        <div class="show-select-num cursor-pointer w-558" slot="reference">
          <div>{{ partForm.salerName }} <span v-if="!partForm.salerName" class="font-14 color-c0c4cc">请输入code/手机号搜索进行账号关联</span></div>
        </div>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button class="btn-class" @click="cancel">取消</el-button>
      <el-button class="btn-class" 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 {
      searchLoading: false,
      partForm: {
        salerName: '',
        manageFlag: 0, // 关联角色 导购 区经/督导
        clerkId: ''
      },
      searchSelect: '',
      storeData: [],
      selectId: '',
      departVisible: true,
      loading: false,
      visible: false,
      isShowError: false
    };
  },
  methods: {
    /**
     * 解绑
     */
    toUnbind(row) {
      const that = this;
      that
        .$confirm(`导购账号（${row.clerkName}）已绑定${row.staffName}，是否确认解绑？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          that.visible = true;
          that.postUnbind(row);
        })
        .catch(() => {
          that.visible = true;
        });
    },
    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.getData();
            that.visible = true;
            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;
      that.$set(that.partForm, 'salerName', item.clerkName);
      that.$forceUpdate();
      that.$nextTick(() => {
        that.$refs['partForm'].validate(valid => {
          if (valid) {
            return false;
          }
        });
      });
    },
    /**
     * 输入
     */
    toInput: _debounce(function(e, value) {
      console.log('input--');
      const that = this;
      if (that.searchSelect.trim() == '') {
        that.storeData = [];
        that.selectId = '';
        return false;
      }
      that.getData();
    }, 500),
    // 搜索清除
    clearSearch() {
      const that = this;
      that.storeData = [];
      that.selectId = '';
      that.searchSelect = '';
    },

    manageChange(value) {
      // 清空搜索数组、字段
      this.storeData = [];
      this.searchSelect = '';
      this.selectId = '';
    },
    // 获取搜索列表
    getData() {
      const that = this;
      let para = {
        search: that.searchSelect,
        manageFlag: that.partForm.manageFlag
      };
      that.searchLoading = true;
      that.selectId = '';
      getRequest('/haoban-manage3-web/search-clerk-relation', para)
        .then(res => {
          let resData = res.data;
          that.searchLoading = false;
          if (resData.errorCode == 1) {
            that.storeData = resData.result || [];
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.searchLoading = false;
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 关闭弹窗
     */
    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) {
          if (!that.searchSelect || !that.selectId) {
            this.isShowError = true;
            that.loading = false;
            return;
          }
          that.postAdd();
        } else {
          that.loading = false;
          return false;
        }
      });
    }, 300),
    postAdd() {
      const that = this;
      let params = {
        staffId: that.departObj.staffId,
        manageFlag: that.partForm.manageFlag,
        clerkId: that.selectId
      };
      that.loading = false;
      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
          });
        });
    }
  },
  watch: {
    searchSelect(newV, oldV) {
      if (!newV) {
        this.isShowError = false;
      }
    },
    selectId(newV, oldV) {
      if (newV) {
        this.isShowError = false;
      }
    }
  }
};
</script>
<style lang="less" scoped>
/deep/ .add-remote-dialog {
  // .el-dialog {
  //   height: 221px;
  // }
  .el-dialog__header {
    padding: 24px 24px 0 24px;
    .el-dialog__title {
      line-height: 25px;
      font-size: 16px;
      font-family: PingFangSC-Regular, PingFang SC;
      color: #37383a;
    }
  }
  .el-dialog__body {
    padding: 30px;
  }
}
// .damolish .el-select-dropdown .el-select-dropdown__empty {
//   width: 352px;
// }
// .damolish .el-select-dropdown .el-select-dropdown__item {
//   height: 45px;
//   line-height: 45px;
// }
.w-95 {
  width: 95px;
}
.w-352 {
  width: 352px;
}
.m-l-30 {
  margin-left: 30px;
}
.w-319 {
  width: 319px;
}
.w-558 {
  width: 558px;
}
.btn-class {
  box-sizing: border-box;
  padding: 5px 24px;
  width: 80px;
  height: 32px;
}
.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: 120px;
}
.el-select-dropdown__item {
  height: 52px;
  line-height: 52px;
}
.text-ellipsis {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.test {
  // position: absolute;
  // height: 300px;
  // z-index: 99990000099999;
}
</style>
