<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-04-14 09:50:16
 * @LastEditors: 无尘
 * @LastEditTime: 2020-06-15 16:09:52
 -->
<!--
  <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 flex  flex-space-between">
        <div><el-checkbox :disabled="clerkOptions.length > assignPeople" :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox></div>
        <div>
          <el-checkbox v-model="checked">手动分配</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 :key="index + 'clerk'">
                <el-checkbox :label="item.clerkId">{{ clerkName }}</el-checkbox
                ><span v-if="!checked && checkedClerks.includes(item.clerkId)"> 分配会员 {{ item.memberCount }} 人</span><el-input-number v-if="checked && checkedClerks.includes(item.clerkId)" v-model="item.memberCount" controls-position="right" @change="handleChange" :min="1" :max="999999999"></el-input-number>
              </li>
            </template>
          </el-checkbox-group>
        </ul>
        <div class="text-right">
          分配总数 <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 != 0 && 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: {
    /**
     * 手动值改变，计算总数
     */
    handleChange() {
      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;
      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;
      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/customer/clerk-list', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            resData.result.forEach(ele => {
              ele.memberCount = 1;
            });
            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/customer/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;
      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(that.clerkOptions)
      };
      postRequest('/haoban-app-customer-web/customer/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
          });
        });
    }
  },
  watch: {
    editRow(newData) {
      const that = this;
      if (Object.keys(newData).length) {
        that.ruleForm = JSON.parse(JSON.stringify(newData));
      }
    }
  },
  mounted() {
    const that = this;
    if (Object.keys(that.editRow).length) {
      that.ruleForm = JSON.parse(JSON.stringify(that.editRow));
    }
  }
};
</script>
<style lang="less" scoped>
.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); */
    .el-textarea {
      /deep/ .el-textarea__inner {
        height: 273px;
      }
    }
  }
  .emoji-img {
    position: absolute;
    left: 10px;
    bottom: 10px;
  }
}
.el-textarea {
  /deep/ .el-textarea__inner {
    height: 273px;
  }
}
.color-f5222d {
  color: #f5222d;
}
</style>
