<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-04-14 09:50:16
 * @LastEditors: 无尘
 * @LastEditTime: 2020-06-18 09:57:11
 -->
<!--
  <customer-assign v-if="assignShow" :brandId="brandId" :clerkId="clerkId" :searchParams="searchInput" :chooseAll="selectRadio" :departObj="departObj" :multipleData="multipleSelection" @closeText="closeText" @submitText="submitText"></customer-assign>
  import customerAssign from '@/components/app/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" :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>
          <span
            >可分配会员 <span class="color-303133">{{ assignPeople }}</span> 人</span
          >
        </div>
      </div>
      <div>
        <ul>
          <el-checkbox-group v-model="checkedClerks" @change="handleCheckedChange">
            <template v-for="(item, index) in clerkOptions">
              <li class="clerk-cell border-box 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="!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" @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="text-right m-t-20">
          分配总数 <span :class="[totalPeople != 0 && totalPeople != assignPeople ? 'color-f5222d' : 'color-2f54eb']">{{ totalPeople }}</span> 人
        </div>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="toCancel">取消</el-button>
      <el-button :disabled="totalPeople != assignPeople" type="primary" @click="submitForm('ruleForm')">确定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { _debounce } from '@/common/js/public';
import { postRequest } from '@/api/api';
import showMsg from '@/common/js/showmsg';
import errMsg from '@/common/js/error';
export default {
  props: {
    brandId: {
      type: String,
      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
        };
      }
    }
  },
  components: {},
  data() {
    return {
      dialogVisible: true,
      checked: false, // 手动
      checkAll: false,
      isIndeterminate: false,
      clerkOptions: [
        /*  {
          clerkId: 1,
          clerlName: '1',
          memberCount: 1
        } */
      ], // 导购
      checkedClerks: [],
      totalPeople: 0, // 分配总数
      assignPeople: 0 // 可分配会员
    };
  },
  methods: {
    /**
     * 单个值改变
     */
    changeCell(e, item) {
      const that = this;
      console.log(e, item);
      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 = false;
          });
        }
      });
    },
    /**
     * 手动分配选择
     */
    async changeHand(e) {
      const that = this;
      if (!e) {
        // 非手动 需要分配
        await that.calcNum();
        await that.totalCalc();
      } else {
        that.totalCalc();
      }
    },
    /**
     * 手动值改变，计算总数
     */
    handleChange() {
      const that = this;
      that.totalCalc();
    },
    blurNum() {
      const that = this;
      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;
    },
    /**
     * 单选
     */
    async handleCheckedChange(value) {
      const that = this;
      console.log(value);
      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();
      }
    },
    /**
     * 全选
     */
    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;
          }
        });
      });
    },
    /**
     * 获取导购
     */
    getClerkData() {
      const that = this;
      let para = {
        enterpriseId: that.brandId,
        wxEnterpriseRelatedId: that.wxEnterpriseRelatedId,
        storeId: that.departObj.departmentId
      };
      postRequest('/haoban-app-customer-web/clerk-list', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            resData.result.forEach(ele => {
              ele.memberCount = 1;
              ele.disabled = false;
            });
            that.clerkOptions = resData.result || [];
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 获取会员数量
     */
    getMemberData() {
      const that = this;
      let para = {
        enterpriseId: that.brandId,
        wxEnterpriseRelatedId: that.wxEnterpriseRelatedId,
        storeId: that.departObj.departmentId,
        clerkId: that.clerkId,
        keyword: that.searchParams
      };
      postRequest('/haoban-app-customer-web/get-member-count', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.assignPeople = resData.result || [];
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    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');
    },
    submitForm: _debounce(function(formName) {
      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(ele);
        }
      });
      const data = {
        enterpriseId: that.brandId,
        chooseAll: that.chooseAll,
        storeId: that.departObj.departmentId,
        clerkId: that.clerkId,
        keyword: that.searchParams,
        memberIds: that.chooseAll == 1 ? '' : Object.keys(that.editRow).length ? that.editRow.memberId : that.multipleData.map(ele => ele.memberId).join(','),
        clerkIds: JSON.stringify(clerkIds)
      };
      postRequest('/haoban-app-customer-web/app-distribute-members', data)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            showMsg.showmsg('操作成功', 'success');
            that.resetData();
            that.$emit('submitText');
          } else {
            errMsg.errorMsg(resData);
          }
        })
        .catch(error => {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 设置人数和获取数量判断
     */
    setNum() {
      const that = this;
      if (Object.keys(that.editRow).length) {
        that.assignPeople = 1;
      } else {
        that.chooseAll == 0 ? (that.assignPeople = that.multipleData.length) : that.getMemberData();
      }
    }
  },
  watch: {
    departObj(newData) {
      const that = this;
      if (Object.keys(newData).length && newData.isStore == 1) {
        that.getClerkData();
        that.setNum();
      }
    }
  },
  mounted() {
    const that = this;
    if (Object.keys(that.departObj).length && that.departObj.isStore == 1) {
      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;
}
.material-content {
  position: relative;
  .material-body {
    /*  resize: none;
    width: 440px;
    height: 273px;
    border-radius: 2px;
    border: 1px solid rgba(196, 198, 207, 1); */
  }
  .emoji-img {
    position: absolute;
    left: 10px;
    bottom: 10px;
  }
}

.color-f5222d {
  color: #f5222d;
}
.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>
