<!--
 * @Descripttion: 分配导购
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-04-14 09:50:16
 * @LastEditors: 无尘
 * @LastEditTime: 2020-09-21 10:28:33
 -->
<!--
  <customer-assign v-if="assignShow" :store-brand-id="storeBrandId" :brand-id="brandId" :customer-assign-total="customerAssignTotal" :clerk-id="clerkId" :search-params="searchInput" :choose-all="selectRadio" :depart-obj="departObj" :multiple-data="multipleSelection" @closeText="closeText" @submitText="submitText"></customer-assign>
  import customerAssign from '@/components/app/my-customer/customer-assign.vue';
-->
<template>
  <el-dialog title="批量分配会员" :visible.sync="dialogVisible" width="600px" :before-close="handleClose">
    <div class="assign-table">
      <div class="check-all border-box flex  flex-space-between">
        <div class="font-14 color-606266"><el-checkbox :disabled="clerkOptions.length > assignPeople || unbindFlag" :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox></div>
        <div class="font-14 color-606266">
          <el-checkbox v-model="checked" @change="changeHand">手动分配</el-checkbox> <span class="span-line"></span>
          <span>可分配会员 <span class="color-303133">{{ assignPeople }}</span> 人</span>
        </div>
      </div>
      <div>
        <ul class="clerk-list-ul">
          <el-checkbox-group v-model="checkedClerks" @change="handleCheckedChange">
            <template v-for="(item, index) in clerkOptions">
              <li class="clerk-cell font-14 color-606266" :key="index + 'clerk'">
                <el-checkbox :disabled="item.disabled" :label="item.clerkId" @change="changeCell($event, item)">{{ item.clerkName }}</el-checkbox><span v-if="!item.bindStaffFlag" class="font-14 color-f56c6c p-l-20">未关联企微用户</span>
                <span v-if="!checked && checkedClerks.includes(item.clerkId)" class="p-l-20">
                  分配会员 <span class="color-303133">{{ item.memberCount }}</span> 人</span>
                <span v-if="checked && checkedClerks.includes(item.clerkId)" class="p-l-20 p-r-10">分配会员 </span><el-input-number v-if="checked && checkedClerks.includes(item.clerkId)" class="w-100" v-model="item.memberCount" controls-position="right" @blur="blurNum($event, item)" @change="handleChange" :step="1" step-strictly :min="1" :max="999999999"></el-input-number><span v-if="checked && checkedClerks.includes(item.clerkId)" class="p-l-10"> 人</span>
              </li>
            </template>
          </el-checkbox-group>
        </ul>
        <div class="flex flex-space-between m-t-20">
          <div class="font-14 color-909399">最多分配会员 5000 人</div>
          <div class="font-14 color-606266">
            分配总数 <span :class="[totalPeople != 0 && totalPeople != assignPeople ? 'color-f5222d' : 'color-2f54eb']">{{ totalPeople }}</span> 人
          </div>
        </div>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="toCancel">取消</el-button>
      <el-button :disabled="totalPeople != assignPeople" :loading="loadBtn" type="primary" @click="submitForm('ruleForm')">确定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { _debounce } from '@/common/js/public';
import fetch from '@/api/my-customer-app.js';
const { saveAssign, getMemberCount, getClerkList } = fetch;
import showMsg from '@/common/js/showmsg';
import errMsg from '@/common/js/error';
export default {
  components: {},
  props: {
    brandId: {
      type: String,
      default() {
        return '';
      }
    },
    storeBrandId: {
      type: String,
      default() {
        return '';
      }
    },
    customerAssignTotal: {
      type: [ String, Number ],
      default() {
        return '';
      }
    },
    clerkId: {
      type: String,
      default() {
        return '';
      }
    },
    searchParams: {
      type: String,
      default() {
        return '';
      }
    },
    editRow: {
      type: Object,
      default() {
        return {};
      }
    },
    multipleData: {
      type: [ Array, Object ],
      default() {
        return [];
      }
    },
    chooseAll: {
      type: [ String, Number ],
      default() {
        return '0';
      }
    },
    // 选中节点
    departObj: {
      type: Object,
      default() {
        return {
          departmentId: '',
          departmentName: '',
          wxDepartmentId: '',
          parentId: '',
          isStore: '',
          staffCount: '',
          bindFlag: '',
          loading: false
        };
      }
    }
  },
  data() {
    return {
      wxEnterpriseId: localStorage.getItem('haoBanUser') ? JSON.parse(localStorage.getItem('haoBanUser')).wxEnterpriseId : '',
      staffName: localStorage.getItem('haoBanUser') ? JSON.parse(localStorage.getItem('haoBanUser')).staffName : '',
      dialogVisible: true,
      unbindFlag: false,
      checked: false, // 手动
      checkAll: false,
      isIndeterminate: false,
      // 导购
      clerkOptions: [
        /*  {
          clerkId: 1,
          clerlName: '1',
          memberCount: 1
        } */
      ],
      checkedClerks: [],
      totalPeople: 0, // 分配总数
      assignPeople: 0, // 可分配会员
      loadBtn: false
    };
  },
  mounted() {
    const that = this;
    if (Object.keys(that.departObj).length) {
      that.getClerkData();
      that.setNum();
    }
  },
  methods: {
    /**
     * @description: 单个值改变
     * @param {Boolean} e
     * @param {Object} item
     * @author: 无尘
     */
    changeCell(e, item) {
      const that = this;
      that.$nextTick(() => {
        if (e) {
          // 如果选择的导购中人数和分配会员人数相同了，再选择就不能再选了
          if (that.checkedClerks.length == that.assignPeople) {
            that.clerkOptions.forEach((ele, index) => {
              if (!that.checkedClerks.includes(ele.clerkId)) {
                ele.disabled = true;
              }
            });
            return false;
          }
        } else {
          that.clerkOptions.forEach((ele, index) => {
            ele.disabled = !ele.bindStaffFlag ? true : false;
          });
        }
      });
    },
    /**
     * @description: 手动分配选择
     * @param {Boolean} e
     * @author: 无尘
     */
    async changeHand(e) {
      const that = this;
      if (!e) {
        // 非手动 需要分配
        await that.calcNum();
        await that.totalCalc();
      } else {
        that.totalCalc();
      }
    },
    /**
     * @description: 手动值改变，计算总数
     * @author: 无尘
     */
    handleChange() {
      const that = this;
      that.totalCalc();
    },
    /**
     * @description: 手动值改变，计算总数
     * @param {Object} e
     * @param {Object} item
     * @author: 无尘
     */
    blurNum(e, item) {
      const that = this;
      if (!item.memberCount) {
        item.memberCount = 1;
      }
      that.totalCalc();
    },
    totalCalc() {
      const that = this;
      let num = 0;
      that.clerkOptions.forEach((ele, index) => {
        if (that.checkedClerks.includes(ele.clerkId)) {
          num += ele.memberCount;
        }
      });
      that.totalPeople = num;
    },
    /**
     * @description: 单选
     * @param {Array} value
     * @author: 无尘
     */
    async handleCheckedChange(value) {
      const that = this;
      let checkedCount = value.length;
      that.checkAll = checkedCount === that.clerkOptions.length;
      that.isIndeterminate = checkedCount > 0 && checkedCount < that.clerkOptions.length;

      if (!that.checked) {
        // 非手动 需要分配
        await that.calcNum();
        await that.totalCalc();
      } else {
        that.totalCalc();
      }
    },
    /**
     * @description: 全选
     * @param {Array} value
     * @author: 无尘
     */
    async handleCheckAllChange(value) {
      const that = this;
      that.checkedClerks = value ? that.clerkOptions.map(ele => ele.clerkId) : [];
      that.isIndeterminate = false;
      if (!that.checked) {
        // 非手动 需要分配
        await that.calcNum();
        await that.totalCalc();
      } else {
        that.totalCalc();
      }
    },
    calcNum() {
      const that = this;
      // 这里需要注意商 == 0 情况
      if (!that.checkedClerks.length) {
        return false;
      }
      let averageNum = Math.floor(that.assignPeople / that.checkedClerks.length);
      let leftNum = that.assignPeople % that.checkedClerks.length;
      let arr = [];
      that.clerkOptions.forEach((ele, index) => {
        ele.memberCount = averageNum;
        if (that.checkedClerks.includes(ele.clerkId)) {
          arr.push(index);
        }
      });
      that.clerkOptions.forEach((ele, index) => {
        arr.forEach((el, key) => {
          if (el == index && key < leftNum) {
            ele.memberCount = ele.memberCount + 1;
          }
        });
      });
    },
    /**
     * @description: 获取导购
     * @author: 无尘
     */
    getClerkData() {
      const that = this;
      const para = {
        enterpriseId: that.brandId,
        wxEnterpriseId: that.wxEnterpriseId,
        storeInfoId: that.departObj.storeInfoId
      };
      getClerkList(para, { headers: { sign: that.brandId } })
        .then(res => {
          if (res.code == '0000') {
            res.result.forEach(ele => {
              ele.memberCount = 1;
              ele.disabled = ele.bindStaffFlag ? false : true; // 未绑定的禁止选择
              if (!ele.bindStaffFlag) {
                that.unbindFlag = true; // 存在未绑定禁止全选
              }
            });
            that.clerkOptions = res.result || [];
          }else {
            errMsg.errorMsg(res);
          }
        })
        .catch(function(error) {

        });
    },
    /**
     * @description: 获取会员数量（暂无用）
     * @author: 无尘
     */
    getMemberData() {
      const that = this;
      const para = {
        enterpriseId: that.brandId,
        wxEnterpriseId: that.wxEnterpriseId,
        storeInfoId: that.departObj.storeInfoId,
        clerkId: that.clerkId,
        keyword: that.searchParams
      };
      getMemberCount(para, { headers: { sign: that.brandId } })
        .then(res => {
          if (res.code == '0000') {
            that.assignPeople = res.result || [];
          }else {
            errMsg.errorMsg(res);
          }
        })
        .catch(function(error) {

        });
    },
    /**
     * @description: 关闭弹窗，重置数据
     * @author: 无尘
     */
    resetData() {
      const that = this;
      that.checkedClerks = [];
      that.totalPeople = 0; // 分配总数
      that.assignPeople = 0; // 可分配会员
      that.checked = false;
    },
    toCancel() {
      const that = this;
      that.resetData();
      that.$emit('closeText');
    },
    handleClose(done) {
      const that = this;
      that.resetData();
      that.$emit('closeText');
    },
    /**
     * @description: 保存分配
     * @author: 无尘
     */
    submitForm: _debounce(function() {
      const that = this;
      that.postSave();
    }, 300),
    postSave() {
      const that = this;
      let clerkIds = [];
      that.clerkOptions.forEach(ele => {
        if (that.checkedClerks.includes(ele.clerkId) && ele.memberCount != 0) {
          clerkIds.push({
            clerkId: ele.clerkId,
            count: ele.memberCount
          });
        }
      });
      that.loadBtn = true;
      const data = {
        wxEnterpriseId: that.wxEnterpriseId,
        enterpriseId: that.brandId,
        chooseFlag: that.chooseAll,
        storeInfoId: that.departObj.storeInfoId,
        mainClerkId: that.clerkId,
        search: that.searchParams,
        mcuIds: that.chooseAll == 1 ? [] : Object.keys(that.editRow).length ? [ that.editRow.mcuId ] : that.multipleData.map(ele=>ele.mcuId),
        clerkIds: clerkIds,
        staffName: that.staffName,
        brandId: that.storeBrandId
      };
      saveAssign(data, { headers: { sign: that.brandId } })
        .then(res => {
          that.loadBtn = false;
          showMsg.showmsg('操作成功', 'success');
          that.resetData();
          that.$emit('submitText');
        })
        .catch(error => {
          that.loadBtn = false;
        });
    },
    /**
     * @description: 设置人数和获取数量判断
     * @author: 无尘
     */
    setNum() {
      const that = this;
      if (Object.keys(that.editRow).length) {
        that.assignPeople = 1;
      } else {
        that.chooseAll == 0 ? (that.assignPeople = that.multipleData.length) : that.assignPeople = that.customerAssignTotal; // that.getMemberData();
      }
    }
  },
  watch: {
    departObj(newData) {
      const that = this;
      if (Object.keys(newData).length) {
        that.getClerkData();
        that.setNum();
      }
    }
  }
};
</script>
<style lang="less" scoped>
.w-100 {
  width: 100px;
}
.w-402 {
  width: 402px;
}
.m-b-20 {
  margin-bottom: 20px;
}
.p-l-18 {
  padding-left: 18px;
}
.span-line {
  position: relative;
  padding: 0 15px;
  &::after {
    content: '';
    position: absolute;
    top: 5px;
    height: 11px;
    width: 1px;
    background: #c4c6cf;
  }
}

.color-f5222d {
  color: #f5222d;
}
.clerk-list-ul {
  min-height: 40px;
  max-height: 400px;
  overflow-y: auto;
}
.check-all {
  background: rgba(245, 247, 250, 1);
  height: 36px;
  line-height: 36px;
  padding: 0 10px;
}
.clerk-cell {
  height: 40px;
  line-height: 40px;
  padding: 0 10px;
  border-bottom: 1px solid #e4e7ed;
}
</style>
