<!--
 * @Descripttion : 当前组件信息
 * @Author       : 无尘
 * @Date         : 2020-02-13 16:13:59
 * @LastEditors: Drama
 * @LastEditTime: 2022-09-15 13:33:03
 * @FilePath: /haoban-3/src/components/company/add-relatecopy.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" :rules="rules" ref="partForm" 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="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="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"><span>暂无数据</span></li>
                </ul>
              </div>
            </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-popover>
      </el-form-item> -->
      <el-form-item label="关联角色" prop="glrole">
        <el-radio-group v-model="partForm.glrole">
          <el-radio :label="1">导购</el-radio>
          <el-radio :label="2">区经/督导</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="关联账号" prop="clerkId" class="test-wrap">
        <dm-select-scroller v-model="partForm.clerkId" placeholder="请选择" :data="brandList" :props="props" :width="352" @load="load" @remote-search="remoteSearch" :total-count="totalCount" :clearable="true"></dm-select-scroller>
      </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 {
      partForm: {
        salerName: '',
        glrole: 1, // TODO: 关联角色 导购 区经/督导
        clerkId: ''
      },
      brandParams: {
        pageNum: 1,
        pageSize: 10,
        search: ''
      }, // TODO: 远程搜索参数
      rules: {
        salerName: [
          {
            required: true,
            message: '请选择导购',
            trigger: 'change'
          }
        ]
      },
      searchSelect: '',
      storeData: [],
      selectId: '',
      departVisible: true,
      loading: false,
      visible: false,
      brandList: [], // TODO: 远程搜索数组
      totalCount: 0,
      props: {
        label: 'clerkName',
        value: 'clerkId',
        childLabel: 'storeName'
      }
    };
  },
  methods: {
    // TODO: 加载更多
    load() {
      console.log('load');
      this.brandParams.pageNum++;
      this.getRemoteAccountList();
    },
    // TODO: 远程搜索方法
    remoteSearch(query) {
      this.brandParams.search = query;
      this.brandParams.pageNum = 1;
      this.getRemoteAccountList();
    },
    // TODO: 获取远程关联账号数据
    getRemoteAccountList(test) {
      if (this.brandParams.pageNum == 1) {
        this.brandList = [];
      }
      // if (!this.brandParams.search) return;

      // getRequest('/', { ...this.brandParams }).then(res => {
      //   // TODO: 逻辑确认
      // });
      console.log('zoule');
      console.log(this.brandParams.search, 'search--');
      console.log(this.partForm.clerkId, 'id--');
      let testArray = [
        {
          clerkName: 'admin',
          clerkCode: '1',
          clerkId: '8e414a85362c436dad66385eadd2f318',
          enterpriseName: null,
          enterpriseId: 'ff8080815dacd3a2015dacd3ef5c0000',
          storeId: 'ff808081732e0c720173325c1cf5001c',
          storeName: '8300105乌鲁木齐新市汇嘉时代百货Yatlas哈哈哈哈哈哈哈哈哈哈',
          relationStatus: 0,
          staffId: null,
          staffName: null
        },
        {
          clerkName: 'admin222',
          clerkCode: '1333',
          clerkId: '8e414a85362c436dad66385eadd2f31822',
          enterpriseName: null,
          enterpriseId: 'ff8080815dacd3a2015dacd3ef5c000033',
          storeId: 'ff808081732e0c720173325c1cf5001c44',
          storeName: '号码摩托',
          relationStatus: 0,
          staffId: null,
          staffName: null
        }
      ];
      this.brandList = testArray;
      // getRequest('/haoban-manage3-web/search-clerk-relation', {
      //   search: test ? test : this.brandParams.search
      // })
      //   .then(res => {
      //     let resData = res.data;
      //     if (resData.errorCode == 1) {
      //       this.brandList = resData.result || [];
      //       return;
      //     }
      //     errMsg.errorMsg(resData);
      //   })
      //   .catch(function(error) {
      //     this.$message.error({
      //       duration: 1000,
      //       message: error.message
      //     });
      //   });
    },
    /**
     * 显示pop
     */
    showPop() {
      const that = this;
      that.visible = true;
    },
    /**
     * 解绑
     */
    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) {
      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
        clerkId: that.partForm.clerkId
      };
      console.log(params, 'cscsc');
      that.loading = false;

      return;
      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;
    } */
    // TODO: 初始化加载
    // this.getRemoteAccountList();
  }
};
</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;
}
.damolish .el-popper {
  min-width: 352px;
}

.text-ellipsis {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
