<!--
 * @Descripttion: 顾客分配
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-08-20 14:36:37
 * @LastEditors: 无尘
 * @LastEditTime: 2020-09-21 15:47:13
 -->
<template>
  <div class="customer-assign-wrap">
    <div class="border-box">
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="分配策略" name="first"></el-tab-pane>
        <el-tab-pane label="顾客列表" name="second"></el-tab-pane>
      </el-tabs>
      <div v-if="activeName == 'first'" class="customer-assign-set">
        <div class="m-b-10">
          <el-checkbox v-model="customerSetData.unbindClerkDisMemberFlag">解绑导购code，顾客自动分配给店长</el-checkbox>
          <div class="font-12 color-909399 set-tip-item">注：保存勾选项后，解绑当前导购code，该导购cede名下的顾客会分配到店长，在移动端可重新分配顾客</div>
        </div>
        <div class="m-t-46 p-l-20">
          <el-button type="primary" :loading="loadingSet" @click="submitSet">保存</el-button>
        </div>
      </div>
      <div v-if="activeName == 'second'" class="list-body flex">
        <div class="list-left border-box" :style="{minWidth: gicData.length ? '200px' : 0, maxWidth: gicData.length ? '200px' : 0}">
          <org-tree v-if="gicData.length" :brand-id="brandId" :depart-obj="departObj" :item-data="gicData" @getSelectData="getSelectData"></org-tree>
        </div>
        <div :class="['list-right p-20 border-box', gicData.length ? '' : 'no-left-list']">
          <store-list v-if="!showMember" :brand-id="brandId" :depart-obj="departObj" @getStore="getStore"></store-list>
          <div v-if="showMember" class="list-right-body">
            <div role="navigation" class="el-breadcrumb m-b-10">
              <span class="el-breadcrumb__item" v-for="(item, index) in navData" :key="index + 'nav'">
                <span role="link" class="el-breadcrumb__inner is-link" @click="changeDepart(item, index)"><span class="el-breadcrumb__inner is-link font-14  color-606266">
                    {{ index == navData.length - 1 ? item.storeName : item.storeGroupName }}
                  </span></span><i v-if="index != navData.length - 1" class="el-breadcrumb__separator el-icon-arrow-right"></i>
                </span>
            </div>
            <div class="table-top flex flex-space-between">
              <div>
                <el-input placeholder="请输入姓名/昵称/会员卡号" maxlength="50" prefix-icon="el-icon-search" v-model="searchInput" style="width: 274px;" clearable @clear="clearSearch" @keyup.native="value => toInput(value, searchInput)"> </el-input><el-select class="w-168 m-l-10" v-model="clerkId" placeholder="" @change="changeCondition">
                  <el-option label="全部" value=""></el-option>
                  <!-- <el-option label="无归属" value="-1"></el-option> -->
                  <el-option v-for="item in clerkOptions" :key="item.clerkId" :label="item.clerkName" :value="item.clerkId"> </el-option>
                </el-select><el-select class="w-168 m-l-10" v-model="storeBrandId" placeholder="" @change="changeCondition">
                  <el-option v-for="item in storeBrandOptions" :key="item.brandId" :label="item.brandName" :value="item.brandId"></el-option>
                </el-select>
              </div>
              <el-button type="primary" @click="toAssign">批量分配会员</el-button>
            </div>
            <div class="table-body  m-t-20">
              <el-table class="select-table" ref="multipleTable" v-loading="loading" :data="tableData" tooltip-effect="dark" :style="{ width: '100%' }" @sort-change="sortChange" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="45"> </el-table-column>
                <el-table-column width="25">
                  <template slot="header">
                    <el-dropdown style="line-height: 10px; padding: 0; margin-left: -25px; transform: translateY(0px); -webkit-transform: translateY(0px);" @command="handleCommand" placement="bottom-start">
                      <span class="el-dropdown-link"><i class="iconfont icongengduo font-12"></i> </span>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item command="0"><span :style="{ color: selectRadio == 0 ? '#2f54eb' : '#606266' }">选择当页</span></el-dropdown-item>
                        <el-dropdown-item command="1"><span :style="{ color: selectRadio == 1 ? '#2f54eb' : '#606266' }">选择全部</span></el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </template>
                </el-table-column>
                <el-table-column label="会员姓名" width="160px" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <div class="flex common-table-user">
                      <div class="flex flex-align-center flex-pack-center common-table-photo">
                        <img v-if="scope.row.headUrl" :src="scope.row.headUrl" alt="img" />
                        <img v-else src="../../../assets/member.png" alt="img" />
                      </div>
                      <div class="common-table-text hide-ellipsis">
                        <div class="font-14 color-606266 hide-ellipsis">{{ scope.row.memberName || '--' }}</div>
                        <div class="font-12 color-909399 hide-ellipsis">{{ scope.row.cardNo || '--' }}</div>
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="consumeTotal" label="消费总额" sortable="custom" show-overflow-tooltip>
                  <template slot-scope="scope">¥ {{ scope.row.consumeTotal }} {{ scope.row.consumeTotal == null && scope.row.consumeTotal != 0 ? '--' : '' }}</template>
                </el-table-column>
                <el-table-column prop="consumeTimes" label="消费次数" sortable="custom">
                  <template slot-scope="scope">{{ scope.row.consumeTimes || '0' }}</template>
                </el-table-column>
                <el-table-column prop="lastConsume" label="最近消费" sortable="custom" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <div class="line-h-18">{{ scope.row.lastConsume | timeStampToYmd }} {{ !scope.row.lastConsume ? '--' : '' }}</div>
                    <div class="line-h-18">{{ scope.row.lastConsume | timeStampToHms }} {{ !scope.row.lastConsume ? '--' : '' }}</div>
                  </template>
                </el-table-column>
                <el-table-column prop="" label="所属导购" show-overflow-tooltip>
                  <template slot-scope="scope">
                    {{ scope.row.mainClerkName || '--' }}
                  </template>
                </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button type="text" @click="toAssignMember(scope.$index, scope.row)">分配</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div class="block common-wrap__page text-right m-t-24" v-if="tableData.length != 0">
                <dm-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[20, 40, 60, 80]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </dm-pagination>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <customer-assign v-if="assignShow" :store-brand-id="storeBrandId" :brand-id="brandId" :customer-assign-total="total" :clerk-id="clerkId" :search-params="searchInput" :edit-row="editRow" :choose-all="selectRadio" :depart-obj="storeObj" :multiple-data="multipleSelection" @closeText="closeText" @submitText="submitText"></customer-assign>
  </div>
</template>
<script>
import orgTree from '@/components/app/my-customer/org-tree.vue';
import customerAssign from '@/components/app/my-customer/customer-assign.vue';
import storeList from '@/components/app/my-customer/store-list.vue';
import showMsg from '@/common/js/showmsg';
import errMsg from '@/common/js/error';
import { _debounce } from '@/common/js/public';
import fetch from '@/api/my-customer-app.js';
const { getCustomerSet, saveCustomerSet, getGroupList, getMemberList, getNavChain, getAssignStatus, getListBrand, getClerkList } = fetch;
export default {
  name: 'CustomerAssignPage',
  components: { orgTree, customerAssign, storeList },
  props: {
    brandId: {
      type: String,
      default() {
        return '';
      }
    },
    tabType: {
      type: String,
      default() {
        return '1';
      }
    },
    activeGroupId: {
      type: String,
      default() {
        return '';
      }
    }
  },
  data() {
    return {
      projectName: '', // 当前项目名
      wxEnterpriseId: localStorage.getItem('haoBanUser') ? JSON.parse(localStorage.getItem('haoBanUser')).wxEnterpriseId : '',
      // 分配策略
      activeName: 'first',
      loadingSet: false,
      customerSetData: {
        unbindClerkDisMemberFlag: false
      },
      // 顾客列表
      departObj: {}, // 选中的部门、门店
      gicData: [], // gic
      clerkId: '', // 导购
      searchInput: '',
      clerkOptions: [], // 导购下拉列表
      storeBrandId: '',
      storeBrandOptions: [], // 店招品牌下拉列表
      tableData: [],
      currentPage: 1,
      pageSize: 20,
      total: 0,
      loading: false,
      selectRadio: 0, // 0：选择当页； 1：选择全部
      multipleSelection: [],
      assignShow: false,
      // 是否显示会员列表
      showMember: false,
      sortCode: '',
      sortRule: '',
      storeObj: {},
      gicDataCopy: [],
      navData: []
    };
  },
  mounted() {
    const that = this;
    that.$emit('showTab', '/customer-assign');
    if (that.brandId) {
      that.getSetData();
    }
  },
  methods: {
    /**
     * @description: 排序
     * @param {Object} column
     * @param {String} prop
     * @param {String} order
     * @author: 无尘
     */
    sortChange(column, prop, order) {
      const that = this;
      that.sortCode = column.prop;
      that.sortRule = column.order == 'ascending' ? 'asc' : 'desc';
      that.currentPage = 1;
      that.getTableList();
    },
    /**
     * @description: 当前函数信息
     * @author: 无尘
     */
    handleTabClick() {
      const that = this;
      if (that.activeName == 'first') {
        that.getSetData();
      }else {
        that.showMember = false;
        that.currentPage = 1;
        that.tableData = [];
        that.clerkOptions = [];
        that.clerkId = ''; // 导购
        that.searchInput = '';
        that.selectRadio = 0;
        that.multipleSelection = [];
        that.storeObj = {};
        that.getGicData();
      }
    },
    /**
     * @description: 保存
     * @author: 无尘
     */
    submitSet: _debounce(function() {
      const that = this;
      that.loadingSet = true;
      that.setData();
    }, 300),
    /**
     * @description: 保存-API
     * @author: 无尘
     */
    setData() {
      const that = this;
      let openCodes = [];
      for(let i in that.customerSetData) {
        if(that.customerSetData[i]){
          openCodes.push(i);
        }
      }
      const para = {
        wxEnterpriseId: that.wxEnterpriseId,
        enterpriseId: that.brandId,
        openCodes: openCodes.join(','),
        switchType: 2
      };
      saveCustomerSet(para, { headers: { sign: that.brandId } })
        .then(res => {
          that.loadingSet = false;
          that.getSetData();
          if (res.code == '0000') {
            showMsg.showmsg('操作成功', 'success');
          }else {
            showMsg.showmsg(res.message || '接口异常', 'warning');
          }
        })
        .catch(function(error) {
          that.loadingSet = false;
        });
    },
    /**
     * @description: 获取展示数据
     * @author: 无尘
     */
    getSetData() {
      const that = this;
      const para = {
        wxEnterpriseId: that.wxEnterpriseId,
        enterpriseId: that.brandId,
        switchType: 2
      };
      getCustomerSet(para, { headers: { sign: that.brandId } })
        .then(res => {
          if (res.result && !!res.result.length) {
            res.result.forEach(ele => {
              that.customerSetData[ele.switchCode] = ele.switchFlag == 1 ? true : false;
            });
          }else {
            that.customerSetData = {
              unbindClerkDisMemberFlag: false
            };
          }
        })
        .catch(function(error) {

        });
    },
    /**
     * @description: 面包屑选择分组
     * @param {Object} obj
     * @param {Array} copyData
     * @author: 无尘
     */
    async setParent(obj, copyData) {
      const that = this;
      for (let i = 0; i < copyData.length; i++) {
        if (obj.parentStoreGroupId == copyData[i].storeGroupId) {
          copyData[i].expand = true;
          if (copyData[i].parentStoreGroupId != 0) {
            await that.setParent(copyData[i], copyData);
          }
        }
      }
    },
    /**
     * @description: 面包屑选择分组
     * @param {Object} item
     * @author: 无尘
     */
    async changeDepart(item) {
      const that = this;
      if (!!item.storeInfoId) {
        return false;
      }
      that.departObj = item;
      that.showMember = false;
      // 重新组装树形部门
      let copyData = JSON.parse(JSON.stringify(that.gicDataCopy));
      for (let i = 0; i < copyData.length; i++) {
        if (that.departObj.parentStoreGroupId == copyData[i].storeGroupId) {
          copyData[i].expand = true;
          if (copyData[i].parentStoreGroupId != 0) {
            await that.setParent(copyData[i], copyData);
          }
        }
      }
      that.gicData = await that.treeData(JSON.parse(JSON.stringify(copyData)));
      that.gicData[0].expand = true;
    },
    /**
     * @description: 获取会员数据
     * @param {Object} obj
     * @author: 无尘
     */
    getStore(obj) {
      const that = this;
      that.storeObj = obj;
      that.showMember = true;
      that.searchInput = '';
      that.clerkId = ''; // 导购
      that.getBrandData();
      that.getClerkData();
      that.toGetNavData();
    },
    /**
     * @description: 是否在分配中
     * @author: 无尘
     */
    async assignStatus() {
      const that = this;
      return new Promise((resolve, reject) => {
        let para = {
          enterpriseId: that.brandId,
          wxEnterpriseId: that.wxEnterpriseId,
          storeInfoId: that.storeObj.storeInfoId
        };
        getAssignStatus(para, { headers: { sign: that.brandId } })
          .then(res => {
            if (res.code == '0000') {
              resolve(res.result);
              return;
            }
            errMsg.errorMsg(res);
            resolve(false);
          })
          .catch(function(error) {
            resolve(false);
          });
      });
    },
    /**
     * @description: 关闭分配
     * @author: 无尘
     */
    closeText() {
      const that = this;
      that.assignShow = false;
      that.selectRadio = 0;
      that.multipleSelection = [];
      that.editRow = {};
      that.$refs.multipleTable.clearSelection();
    },
    /**
     * @description: 完成分配回调
     * @author: 无尘
     */
    submitText() {
      const that = this;
      that.selectRadio = 0;
      that.multipleSelection = [];
      that.assignShow = false;
      that.$refs.multipleTable.clearSelection();
      that.currentPage = 1;
      that.getTableList();
      // 后端分配是异步的，列表不会很快显示分配的导购
      that.$alert('会员分配中，请稍候查看', '', {
        confirmButtonText: '确定',
        callback: action => {
          that.currentPage = 1;
          that.getTableList();
          let t = setTimeout(function() {
            that.currentPage = 1;
            that.getTableList();
            clearTimeout(t);
          }, 1000);
        }
      });
    },
    /**
     * @description: 输入
     * @author: 无尘
     */
    toInput: _debounce(function() {
      const that = this;
      that.currentPage = 1;
      that.getTableList();
    }, 500),
    /**
     * @description: 搜索标签清空
     * @author: 无尘
     */
    clearSearch() {
      const that = this;
      that.currentPage = 1;
      that.getTableList();
    },
    /**
     * @description: 每次选中一个树中节点，把当前数据返回，
     * @description: 获取选中部门
     * @param {Object} obj
     * @author: 无尘
     */
    getSelectData(obj) {
      const that = this;
      that.departObj = obj;
      that.selectRadio = 0;
      that.showMember = false;
      that.storeObj = {};
      // 判断是不是门店
      that.currentPage = 1;
      that.tableData = [];
      that.clerkOptions = [];
      that.clerkId = ''; // 导购
      that.searchInput = '';
      that.multipleSelection = [];
    },
    /**
     * @description: 表格选择
     * @param {Array} val
     * @author: 无尘
     */
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    /**
     * @description: 显示选择本页/全部
     * @param {String} command
     * @author: 无尘
     */
    handleCommand(command) {
      this.selectRadio = command;
    },
    /**
     * @description: 分配
     * @param {Number} index
     * @param {Object} row
     * @author: 无尘
     */
    async toAssignMember(index, row) {
      const that = this;
      const flag = await that.assignStatus();
      if (flag) {
        that.$message.error({
          duration: 1000,
          message: '会员正在分配中，请稍后再试'
        });
        return false;
      }
      that.editRow = row;
      // 如果选中一个分配，就要把批量已选的全部置空
      that.selectRadio = 0;
      that.multipleSelection = [];
      that.$refs.multipleTable.clearSelection();
      that.assignShow = true;
    },
    /**
     * @description: 批量分配
     * @author: 无尘
     */
    async toAssign() {
      const that = this;
      that.editRow = {};
      const flag = await that.assignStatus();
      if (flag) {
        that.$message.error({
          duration: 1000,
          message: '会员正在分配中，请稍后再试'
        });
        return false;
      }
      if (!that.multipleSelection.length) {
        that.$message.error({
          duration: 1000,
          message: '请选择会员'
        });
        return false;
      }
      that.assignShow = true;
    },
    /**
     * @description: 简单数组-->父子数组对象
     * @param {Array} data
     * @author: 无尘
     */
    async treeData(data) {
      const that = this;
      let tree = data.filter(father => {
        // 循环所有项
        let branchArr = data.filter(child => {
          return father.storeGroupId == child.parentStoreGroupId; // 返回每一项的子级数组
        });
        if (branchArr.length > 0) {
          father.hasSonNode = true;
          father.children = that.sortGroup(branchArr); // 如果存在子级，则给父级添加一个children属性，并赋值
        } else {
          father.hasSonNode = false;
          father.children = [];
        }
        return father.parentStoreGroupId == 0; // 返回第一层
      });
      return tree;
    },
    /**
     * @description: 树状结构排序
     * @param {Array} arr
     * @returns {Array}
     * @author: 无尘
     */
    sortGroup(arr) {
      arr.sort(function(a, b) {
        return (a.sort - b.sort);
      });
      return arr;
    },
    /**
     * @description: 获取 gic 数据
     * @author: 无尘
     */
    getGicData() {
      const that = this;
      const para = {
        enterpriseId: that.brandId,
        wxEnterpriseId: that.wxEnterpriseId,
      };
      getGroupList(para, { headers: { sign: that.brandId } })
        .then(async res => {
          if (res.result.length) {
            res.result.forEach(ele => {
              ele.loading = false;
              ele.expand = false;
              ele.children = [];
              ele.label = ele.storeGroupName;
              if (ele.parentStoreGroupId == 0) {
                ele.expand = true;
                that.departObj = ele;
              }
            });
            that.gicDataCopy = JSON.parse(JSON.stringify(res.result));
            that.gicData = await that.treeData(JSON.parse(JSON.stringify(res.result)));
          }
        })
        .catch(function(error) {

        });
    },
    /**
     * @description: 条件
     * @author: 无尘
     */
    changeCondition() {
      const that = this;
      that.currentPage = 1;
      that.getTableList();
    },
    /**
     * @description: 分页---页码变化
     * @param {Number} val
     * @author: 无尘
     */
    handleSizeChange(val) {
      const that = this;
      that.currentPage = 1;
      that.pageSize = val;
      that.getTableList();
    },

    /**
     * @description: 分页---当前页变化
     * @param {Number} val
     * @author: 无尘
     */
    handleCurrentChange(val) {
      const that = this;
      that.currentPage = val;
      that.getTableList();
    },
    /**
     * @description: 获取面包屑
     * @author: 无尘
     */
    toGetNavData() {
      const that = this;
      let params = {
        enterpriseId: that.brandId,
        wxEnterpriseId: that.wxEnterpriseId,
        storeInfoId: that.storeObj.storeInfoId
      };
      getNavChain(params, { headers: { sign: that.brandId } })
        .then(res => {
          if (res.code == '0000') {
            that.navData = res.result || [];
            that.navData.push(that.storeObj);
            return false;
          }
          errMsg.errorMsg(res);
        })
        .catch(function(error) {

        });
    },
    /**
     * @description: 获取店招品牌
     * @author: 无尘
     */
    getBrandData() {
      const that = this;
      const para = {
        enterpriseId: that.brandId,
        wxEnterpriseId: that.wxEnterpriseId,
        storeInfoId: that.storeObj.storeInfoId
      };
      getListBrand(para, { headers: { sign: that.brandId } })
        .then(res => {
          that.storeBrandOptions = res.result || [];
          that.storeBrandId = res.result.length ? res.result[0].brandId : '';
          that.getTableList();
        })
        .catch(function(error) {

        });
    },
    /**
     * @description: 获取导购列表
     * @author: 无尘
     */
    getClerkData() {
      const that = this;
      const para = {
        enterpriseId: that.brandId,
        wxEnterpriseId: that.wxEnterpriseId,
        storeInfoId: that.storeObj.storeInfoId
      };
      getClerkList(para, { headers: { sign: that.brandId } })
        .then(res => {
          that.clerkOptions = res.result || [];
        })
        .catch(function(error) {

        });
    },
    /**
     * @description: 获取列表数据（只有门店才有）
     * @author: 无尘
     */
    getTableList() {
      const that = this;
      that.loading = true;
      const para = {
        enterpriseId: that.brandId,
        wxEnterpriseId: that.wxEnterpriseId,
        pageNum: that.currentPage,
        pageSize: that.pageSize,
        storeInfoId: that.storeObj.storeInfoId,
        mainClerkId: that.clerkId,
        brandId: that.storeBrandId,
        search: that.searchInput,
        sortCode: that.sortCode,
        sortRule: that.sortRule
      };
      getMemberList(para, { headers: { sign: that.brandId } })
        .then(res => {
          that.loading = false;
          that.tableData = res.result.result || [];
          that.total = res.result.totalCount;
        })
        .catch(function(error) {
          that.loading = false;
          that.tableData = [];
          that.total = 0;
        });
    }
  },
  watch: {
    brandId: function(newData, oldData) {
      const that = this;
      if (newData) {
        that.showMember = false;
        that.currentPage = 1;
        that.tableData = [];
        that.total = 0;
        that.clerkOptions = [];
        that.clerkId = ''; // 导购
        that.searchInput = '';
        that.selectRadio = 0;
        that.multipleSelection = [];
        that.storeObj = {};
        that.departObj = {};
        that.gicData = [];
        that.gicDataCopy = [];
        that.activeName == 'first' ? that.getSetData() : that.getGicData();
      }
    }
  }
};
</script>
<style lang="less" scoped>
.w-168 {
  width: 168px;
}

.w-195 {
  width: 195px;
}

.line-h-18 {
  line-height: 18px;
}

.p-20 {
  padding: 20px;
}

.m-b-10 {
  margin-bottom: 10px;
}

.el-breadcrumb__inner.is-link:hover,
.el-breadcrumb__inner a:hover {
  color: #2f54eb;
}

.m-t-46 {
  margin-top: 46px;
}

.set-tip-item {
  line-height: 22px;
  padding-left: 25px;
}

.common-table-user {
  .common-table-photo {
    width: 40px;
    min-width: 40px;
    max-width: 40px;
    max-height: 40px;
    border-radius: 2px;
    box-sizing: border-box;
    img {
      width: 100%;
      max-width: 40px;
      max-height: 40px;
      border-radius: 2px;
    }
  }
  .hide-ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .common-table-text {
    padding-left: 10px;
    box-sizing: border-box;
  }
}

.customer-assign-wrap {
  height: 100%;
  background: #fff;
  .customer-assign-set {
    padding: 30px;
  }
  .el-tabs {
    /deep/ .el-tabs__header {
      margin: 0;
    }
  }
  .list-body {
    position: relative;
    width: 100%;
    .list-left {
      position: relative;
      width: 200px;
      min-width: 200px;
      max-width: 200px;
      padding: 20px 0 0 0px;
    }
    .list-right {
      position: relative;
      min-width: calc(100% - 200px);
      min-height: calc(100vh - 94px);
      border-left: 1px solid #e4e7ed;
      &.no-left-list {
        min-width: 100%;
      }
      .el-breadcrumb__item {
        padding-bottom: 10px;
      }
      .el-dropdown-link {
        cursor: pointer;
      }
      .icongengduo {
        font-size: 12px;
        color: #909399;
      }
    }
  }
}
</style>
