<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-04-14 09:50:16
 * @LastEditors: 无尘
 * @LastEditTime: 2020-06-15 15:40:18
 -->
<!--
  <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: {
    handleCheckedChange(value) {
      const that = this;
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.clerkOptions.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.clerkOptions.length;
      if (!that.checked) {
        // 分配
        that.calcNum();
      }
    },
    /**
     * 全选
     */
    handleCheckAllChange(value) {
      const that = this;
      that.checkedClerks = value ? that.clerkOptions.map(ele => ele.clerkId) : [];
      that.isIndeterminate = false;
      if (!that.checked) {
        // 分配
        that.calcNum();
      }
    },
    calcNum() {
      const that = this;
      let averageNum = Math.floor(that.assignPeople / that.clerkOptions.length);
      let leftNum = that.assignPeople % that.clerkOptions.length;
      that.clerkOptions.forEach((ele, index) => {
        ele.memberCount = averageNum;
        if (index < leftNum) {
          ele.memberCount = averageNum + 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>
