<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-03-20 14:36:37
 * @LastEditors: 无尘
 * @LastEditTime: 2020-06-22 15:47:24
 -->
<template>
  <div class="app-detail-wrap">
    <div class="border-box">
      <div class="list-body flex">
        <div class="list-left border-box">
          <org-tree v-if="gicData.length" :brandId="brandId" :departObj="departObj" :itemData="gicData" @getSelectData="getSelectData"></org-tree>
        </div>
        <div class="list-right p-20 border-box">
          <store-list v-if="!showMember" :brandId="brandId" :departObj="departObj" @getStore="getStore"></store-list>

          <div v-if="showMember" class="list-right-body">
            <div role="navigation" class="el-breadcrumb m-b-20">
              <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-select class="w-168" v-model="clerkId" placeholder="" @change="changeCondition">
                  <el-option label="全部" value="0"></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-input placeholder="请输入会员姓名/手机号/卡号" prefix-icon="el-icon-search" v-model="searchInput" class="w-264 m-l-10" style="width: 264px;" clearable @clear="clearSearch" @keyup.native="value => toInput(value, searchInput)"> </el-input>
              </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%' }" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="45"> </el-table-column>
                <el-table-column width="25">
                  <template slot="header" slot-scope="scope">
                    <el-dropdown style="line-height: 10px; padding: 0; margin-left: -15px; transform: translateY(4px); -webkit-transform: translateY(4px);" @command="handleCommand" placement="bottom-start">
                      <span class="el-dropdown-link"><i class="iconfont icongengduo"></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>
                  <template slot-scope="scope"> </template>
                </el-table-column>
                <el-table-column label="会员姓名" width="120" show-overflow-tooltip>
                  <template slot-scope="scope">{{ scope.row.memberName || '--' }}</template>
                </el-table-column>
                <el-table-column prop="" label="会员等级">
                  <template slot-scope="scope">{{ scope.row.gradeName || '--' }}</template>
                </el-table-column>
                <el-table-column prop="" label="消费总额" show-overflow-tooltip>
                  <template slot-scope="scope"
                    >{{ scope.row.costFee }} {{ scope.row.costFee == null && scope.row.costFee != 0 ? '--' : '' }}</template
                  >
                </el-table-column>
                <el-table-column prop="" label="最近消费时间" show-overflow-tooltip>
                  <template slot-scope="scope">
                    {{ scope.row.lastCostTime | timeStampToYmd }} {{ !scope.row.lastCostTime ? '--' : '' }}
                  </template>
                </el-table-column>
                <el-table-column prop="" label="生日" show-overflow-tooltip>
                  <template slot-scope="scope">{{ scope.row.birthday || '--' }}</template>
                </el-table-column>
                <el-table-column prop="" label="所属导购" show-overflow-tooltip>
                  <template slot-scope="scope">
                    {{ scope.row.clerkName || '--' }}
                  </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" :brandId="brandId" :clerkId="clerkId" :searchParams="searchInput" :editRow="editRow" :chooseAll="selectRadio" :departObj="storeObj" :multipleData="multipleSelection" @closeText="closeText" @submitText="submitText"></customer-assign>
  </div>
</template>
<script>
import orgTree from '@/components/company/org-tree.vue';
import customerAssign from '@/components/app/customer/customer-assign.vue';
import storeList from '@/components/app/customer/store-list.vue';
// import showMsg from '@/common/js/showmsg';
import errMsg from '@/common/js/error';
import { _debounce } from '@/common/js/public';
import { getRequest, postRequest } from '@/api/api';
export default {
  name: 'app-detail',
  props: {
    brandId: {
      type: String,
      default() {
        return '';
      }
    },
    tabType: {
      type: String,
      default() {
        return '1';
      }
    },
    activeGroupId: {
      type: String,
      default() {
        return '';
      }
    }
  },
  data() {
    return {
      projectName: '', // 当前项目名
      wxEnterpriseRelatedId: localStorage.getItem('userInfos') ? JSON.parse(localStorage.getItem('userInfos')).wxEnterpriseId : '',
      departObj: {}, //选中的部门、门店
      gicData: [], // gic
      clerkId: '0', // 导购
      searchInput: '',
      clerkOptions: [], // 导购下拉列表
      tableData: [],
      currentPage: 1,
      pageSize: 20,
      total: 0,
      loading: false,
      selectRadio: 0, // 0：选择当页； 1：选择全部
      multipleSelection: [],
      assignShow: false,
      // 是否显示会员列表
      showMember: false,
      storeObj: {},
      gicDataCopy: [],
      chainData: [],
      navData: []
    };
  },
  methods: {
    async setParent(obj, copyData) {
      const that = this;
      for (let i = 0; i < copyData.length; i++) {
        if (obj.parentGroupId == copyData[i].storeGroupId) {
          copyData[i].expand = true;
          if (copyData[i].parentGroupId != 0) {
            await that.setParent(copyData[i], copyData);
          }
        }
      }
    },
    /**
     * 面包屑选择分组
     */
    async changeDepart(item) {
      const that = this;
      if (!!item.storeId) {
        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.parentGroupId == copyData[i].storeGroupId) {
          copyData[i].expand = true;
          if (copyData[i].parentGroupId != 0) {
            await that.setParent(copyData[i], copyData);
          }
        }
      }
      that.gicData = await that.treeData(JSON.parse(JSON.stringify(copyData)));
      that.gicData[0].expand = true;
    },
    /**
     * 获取会员数据
     */
    getStore(obj) {
      const that = this;
      that.storeObj = obj;
      that.showMember = true;
      that.getClerkData();
      that.getTableList();
      that.toGetNavData();
    },
    /**
     * 是否在分配中
     */
    async assignStatus() {
      const that = this;
      return new Promise((resolve, reject) => {
        let para = {
          storeId: that.storeObj.storeId
        };
        getRequest('/haoban-app-customer-web/app-distribute-status', para)
          .then(res => {
            let resData = res.data;
            if (resData.errorCode == 1) {
              resolve(resData.result);
              return;
            }
            errMsg.errorMsg(resData);
            resolve(false);
          })
          .catch(function(error) {
            resolve(false);
            that.$message.error({
              duration: 1000,
              message: error.message
            });
          });
      });
    },
    /**
     * 关闭分配
     */
    closeText() {
      const that = this;
      that.assignShow = false;
      that.selectRadio = 0;
      that.multipleSelection = [];
      that.editRow = {};
      that.$refs.multipleTable.clearSelection();
    },
    /**
     * 完成分配回调
     */
    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);
        }
      });
    },
    /**
     * 输入
     */
    toInput: _debounce(function(e, value) {
      const that = this;
      that.currentPage = 1;
      that.getTableList();
    }, 500),
    /**
     * 搜索标签清空
     */
    clearSearch() {
      const that = this;
      that.currentPage = 1;
      that.getTableList();
    },
    /**
     * 每次选中一个树中节点，把当前数据返回，
     * 获取选中部门
     */
    getSelectData(obj) {
      const that = this;
      console.log(obj);
      that.departObj = obj;
      that.selectRadio = 0;
      that.showMember = false;
      that.storeObj = {};
      // 判断是不是门店
      that.currentPage = 1;
      that.tableData = [];
      that.clerkOptions = [];
      that.clerkId = '0'; // 导购
      that.searchInput = '';
      that.multipleSelection = [];
    },
    /**
     * 表格选择
     */
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    /**
     * 显示选择本页/全部
     */
    handleCommand(command) {
      this.selectRadio = command;
    },
    /**
     * 分配
     */
    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;
    },
    /**
     * 批量分配
     */
    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;
    },
    /**
     * 简单数组-->父子数组对象
     */
    async treeData(data) {
      // const that = this;
      let tree = data.filter(father => {
        //循环所有项
        let branchArr = data.filter(child => {
          return father.storeGroupId == child.parentGroupId; //返回每一项的子级数组
        });
        if (branchArr.length > 0) {
          father.hasSonNode = true;
          father.children = branchArr; //如果存在子级，则给父级添加一个children属性，并赋值
        } else {
          father.hasSonNode = false;
          father.children = [];
        }
        return father.parentGroupId == 0; //返回第一层
      });
      return tree;
    },
    /**
     * 获取 gic 数据
     */
    getGicData() {
      const that = this;
      let para = {
        enterpriseId: that.brandId,
        wxEnterpriseRelatedId: that.wxEnterpriseRelatedId
      };
      getRequest('/haoban-app-customer-web/gic-department-list', para)
        .then(async res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            if (resData.result.length) {
              resData.result.forEach(ele => {
                ele.loading = false;
                ele.expand = false;
                ele.children = [];
                ele.label = ele.storeGroupName;
                if (ele.parentGroupId == 0) {
                  ele.expand = true;
                  that.departObj = ele;
                }
              });
              that.gicDataCopy = JSON.parse(JSON.stringify(resData.result));
              that.gicData = await that.treeData(JSON.parse(JSON.stringify(resData.result)));
            }
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 条件
     */
    changeCondition() {
      const that = this;
      that.currentPage = 1;
      that.getTableList();
    },
    /**
     *  分页---页码变化
     */
    handleSizeChange(val) {
      const that = this;
      that.pageSize = val;
      that.getTableList();
    },

    /**
     * 分页---当前页变化
     */
    handleCurrentChange(val) {
      const that = this;
      that.currentPage = val;
      that.getTableList();
    },
    /**
     * 获取面包屑
     */
    toGetNavData() {
      const that = this;
      let params = {
        departmentId: that.storeObj.storeGroupId
      };
      postRequest('/haoban-app-customer-web/get-chain', params)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.navData = resData.result || [];
            that.navData.push(that.storeObj);
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 获取导购列表
     */
    getClerkData() {
      const that = this;
      let para = {
        enterpriseId: that.brandId,
        wxEnterpriseRelatedId: that.wxEnterpriseRelatedId,
        storeId: that.storeObj.storeId
      };
      postRequest('/haoban-app-customer-web/clerk-list', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.clerkOptions = resData.result || [];
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 获取列表数据（只有门店才有）
     */
    getTableList() {
      const that = this;
      let para = {
        enterpriseId: that.brandId,
        wxEnterpriseRelatedId: that.wxEnterpriseRelatedId,
        pageNum: that.currentPage,
        pageSize: that.pageSize,
        storeId: that.storeObj.storeId,
        clerkId: that.clerkId,
        keyword: that.searchInput
      };
      postRequest('/haoban-app-customer-web/app-get-member-info-list', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.tableData = resData.result.result || [];
            that.total = resData.result.totalCount;
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  },
  watch: {
    brandId: function(newData, oldData) {
      const that = this;
      if (newData) {
        that.showMember = false;
        that.currentPage = 1;
        that.tableData = [];
        that.clerkOptions = [];
        that.clerkId = '0'; // 导购
        that.searchInput = '';
        that.selectRadio = 0;
        that.multipleSelection = [];
        that.storeObj = {};
        that.getGicData(that.brandId);
      }
    }
  },
  mounted() {
    const that = this;
    that.$emit('showTab', '2');
    if (that.brandId) {
      that.getGicData(that.brandId);
    }
  },
  components: { orgTree, customerAssign, storeList }
};
</script>
<style lang="less" scoped>
.w-500 {
  width: 500px;
}

.w-195 {
  width: 195px;
}

.color-1890ff {
  color: #2f54eb;
}

.p-20 {
  padding: 20px;
}

.p-l-38 {
  padding-left: 38px;
}

.p-l-199 {
  padding-left: 199px;
}
.m-b-10 {
  margin-bottom: 10px;
}
.el-breadcrumb__inner.is-link:hover,
.el-breadcrumb__inner a:hover {
  color: #2f54eb;
}

.app-detail-wrap {
  height: 100%;
  background: #fff;
  .list-body {
    position: relative;
    width: 100%;
    .list-left {
      position: relative;
      width: 300px;
      min-width: 300px;
      max-width: 300px;
      padding: 20px 0 0 0px;
    }
    .list-right {
      position: relative;
      min-width: calc(100% - 300px);
      min-height: calc(100vh - 94px);
      border-left: 1px solid #e4e7ed;
    }
  }
}
</style>
