<template>
  <div class="common-set-wrap">
    <nav-crumb :navpath="navpath"></nav-crumb>
    <div class="right-content">
      <div class="right-box">
        <div class="store-estrutura-container common-frame-container">
            <search-menu
                ref="searchMenu"
                :storeFrame="true"
                :treeData="menuData"
                :searchResult="searchResult"
                @handleSearchKey="handleSearchKey"
                @handleTreeSelection="handleTreeSelection"
                @handleStoreSelection="handleStoreSelection"
                @handleEmployeeSelection="handleEmployeeSelection">
                <template slot="buttonBox">
                    <div class="slot-button">
                        <el-button @click="addBrand" :disabled="disableBtn">新建品牌</el-button>
                        <el-popover
                            placement="right"
                            width="550"
                            content="若您的企业为集团企业，可通过新建品牌，不同品牌的门店可以创建在不同的品牌下面"
                            trigger="hover">
                            <i class="el-icon-question" slot="reference"></i>
                        </el-popover>
                    </div>
                </template>
            </search-menu>
            <clerk-info v-if="showEmployee == 'employee'" :perId="perId"></clerk-info>
            <store-info ref="store_info" v-else-if="showEmployee == 'store'" :storeInfo="storeInfo"></store-info>
            <div class="sf-right-container common-right-container"
                v-else
                v-loading="loading">
                <div class="sf-right-header common-right-header">
                    <span class="title-span">{{groupInfo.groupName}}（{{total}}家）</span>
                    <span class="id-span">部门ID： {{groupInfo.departmentId}}</span>
                    <span class="handle-area">
                        <el-button @click="addSon" class="no-bdr-btn" :disabled="groupInfo.hasPression != 1">添加子分组</el-button>
                        <!-- <template v-if="groupInfo.level != 0"> -->
                            <span class="hurdle"></span>
                            <el-button @click="goToEdit(groupInfo.level)" :href="'#/addGroup?level='+groupInfo.level+'&groupId='+groupInfo.departmentId" :disabled="groupInfo.hasPression != 1" class="no-bdr-btn">编辑</el-button>
                        <!-- </template> -->
                    </span>
                </div>
                <div class="tab-div">
                    <el-radio-group v-model="tableView" @change="switchView">
                        <el-radio-button :label="1">门店视图</el-radio-button>
                        <el-radio-button :label="2">店员视图</el-radio-button>
                    </el-radio-group>
                    <a :href="'#/recycle?dept=' + groupInfo.departmentId + '&showChild=' + showChildMember * 1 + '&type=' + storeType" class="a-href fr">
                        <el-button type="primary" icon="el-icon-delete">回收站（{{recycleList.length}}）</el-button>
                    </a>
                </div>
                <template v-if="tableView == 1">
                    <store-view :tableData="storeList" @setChildMemberShow="setChildMemberShow" :departmentId="groupInfo.departmentId" :brandId="groupInfo.brandId" @getStoreList="getStoreList"></store-view>
                </template>
                <template v-else>
                    <clerk-view :tableData="storeList" @setChildMemberShow="setChildMemberShow" @selectByStatus="selectByStatus" @selectByType="selectByType"></clerk-view>
                </template>
                <div class="pagination">
                    <el-pagination
                        background
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :page-sizes="[20, 40, 60, 80]"
                        :page-size="pageSize"
                        :current-page="pageNumber"
                        layout="total, sizes, prev, pager, next"
                        :total="total">
                    </el-pagination>
                </div>
            </div>
            <add-brand ref="add_brand" @addSuccess="addSuccess"></add-brand>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import navCrumb from '@/components/nav/nav.vue';
import searchMenu from "components/contacts/searchMenu";
import storeView from "components/contacts/storeFrame/storeView";
import clerkView from "components/contacts/storeFrame/clerkView";
import storeInfo from "components/contacts/storeFrame/storeInfo";
import addBrand from "components/contacts/storeFrame/addBrand";
import employeeInfo from "components/contacts/employeeInfo";
import clerkInfo from "components/contacts/storeFrame/clerkInfo";
import { getRequest, postRequest, postJsonRequest } from '@/api/api';
export default {
    name: "storeEstruturaContainer",
    components: {
        navCrumb,
        searchMenu,
        storeView,
        clerkView,
        employeeInfo,
        storeInfo,
        addBrand,
        clerkInfo
    },
    data() {
        return {
            // 面包屑参数
            navpath: [
              {
                name: '首页',
                path: '/index'
              },
              {
                name: '企业通讯录',
                path: '/administrativeFrame'
              },
              {
                name: '门店架构',
                path: ''
              }
            ],
            menuData: [],
            searchResult: {},
            loading: true,
            groupInfo: {
                groupName: "",
                departmentId: ""
            },
            total: 0,
            showChildMember: false, // 是否显示子成员
            pageSize: 20,
            pageNumber: 1,
            storeList: [],
            tableView: 1,
            showEmployee: 'node',
            perId: "",
            storeInfo: {},
            disableBtn: true,
            storeStatus: "",
            storeType: "",
            recycleList: []
        };
    },

        beforeRouteUpdate(to, from, next) {
            next();
        },
    methods: {
        handleSearchKey(keyWord) {
            let params = {
                keyWord
            };
            getRequest("/haoban-manage-web/store/searchpage", params)
            .then(res => {
                this.searchResult = res.data.result || {};
            })
            .catch(e => {
                console.log(e, "error");
            });
        },
        /**
         * 树形搜索结果选人处理
         */
        handleEmployeeSelection(employee, showEmployee) {
            console.log(employee, showEmployee);
            this.perId = employee.employeeClerkId;
            this.showEmployee = showEmployee;
        },
        /**
         * 新建品牌
         */
        addBrand() {
            this.$refs.add_brand.dialogVisible = true;
        },
        // 跳转添加子部门页面
        addSon() {
            location.href = '#/addGroup?addnew=1&groupId='+this.groupInfo.departmentId;
        },
        // 跳转编辑部门页面
        goToEdit(level) {
            let type = level == 0 ? "brand" : "group";
            location.href = '#/addGroup?groupId='+this.groupInfo.departmentId+'&type='+type;
        },
        addSuccess() {
            this.getGroupData();
            this.$refs.add_brand.dialogVisible = false;
        },
        /**
         * 树形搜索结果选门店处理
         */
        handleStoreSelection(store) {
            let that = this;
            let params = {storeId: store.storeId};
            getRequest("/haoban-manage-web/store/findStoreById", params)
            .then(res => {
                console.log(res, "storeInfo");
                if (res.data.errorCode == 1) {
                    that.storeInfo = res.data.result;
                    // that.$refs.store_info.formatStoreInfo(res.data.result);
                    that.showEmployee = "store";
                } else {
                    that.$message.error({
                        message: res.data.message
                    });
                }
            });
        },
        handleSizeChange(size) {
            this.pageSize = size;
            this.getStoreList();
        },
        handleCurrentChange(pageNumber) {
            this.pageNumber = pageNumber;
            this.getStoreList();
        },
        /**
         * 切换视图
         */
        switchView(view) {
            this.pageSize = 20;
            this.pageNumber = 1;
            this.storeList = [];
            this.showChildMember = false;
            this.storeStatus = "";
            this.getStoreList();
        },
        /**
         * 设置是否显示子成员
         */
        setChildMemberShow(show) {
            this.showChildMember = show;
            this.getStoreList();
        },
        /**
         * 获取树形分组数据
         */
        getGroupData() {
            let _this = this;
            let params = {
                isStoreGroup: 1
            };
            getRequest("/haoban-manage-web/dept/deptList", params)
            .then(res => {
                if (res.data.errorCode == 1) {
                    _this.menuData = res.data.result || [];
                    res.data.result.some(li => {
                        if (li.level == 0) {
                            _this.groupInfo.departmentId = li.groupId;
                            _this.groupInfo.groupName = li.name;
                        }
                        return li.level == 0;
                    });
                    _this.getStoreList();
                } else {
                    _this.menuData = [];
                    _this.loading = false;
                    _this.$message.error({
                        duration: 1000,
                        message: res.data.message
                    });
                }
            })
            .catch(e => {
                _this.$message.error({
                    duration: 1000,
                    message: e.message
                });
            });
        },
        /**
         * 获取店铺列表
         */
        getStoreList() {
            let _this = this;
            _this.loading = true;
            let params = {
                storeGroupId: _this.groupInfo.departmentId,
                showChild: _this.showChildMember * 1,
                showType: _this.tableView,
                pageSize: _this.pageSize,
                pageNumber: _this.pageNumber,
                status: _this.storeStatus,
                storeType: _this.storeType
            };
            getRequest("/haoban-manage-web/store/findSimplePage", params)
            .then(res => {
                if (res.data.errorCode == 1) {
                    if (params.status == 4) { // 获取回收站列表数据
                        _this.recycleList = res.data.result.list || [];
                        _this.storeStatus = "";
                        _this.loading = false;
                    } else {
                        _this.total =  res.data.result.total;
                        _this.storeList = res.data.result.list || [];
                        _this.loading = false;
                        _this.$message.success({
                            duration: 1000,
                            message: '操作成功！'
                        });
                        _this.storeStatus = 4;
                        _this.getStoreList();
                    }
                } else {
                    _this.loading = false;
                    _this.storeList = [];
                    _this.$message.error({
                        duration: 1000,
                        message: res.data.message
                    });
                }
            })
            .catch(e => {
                _this.loading = false;
                _this.$message.error({
                    duration: 1000,
                    message: e.message
                });
            });
        },
         /**
         * 树形菜单选择项处理
         */
        handleTreeSelection(obj, node, showEmployee) {
            console.log(obj, node, "selection");
            this.groupInfo.departmentId = obj.groupId;
            this.groupInfo.groupName = obj.name;
            this.groupInfo.brandId = obj.brandId
            this.showEmployee = showEmployee;
            this.groupInfo.hasPression = obj.hasPression;
            this.groupInfo.level = obj.level;
            this.getStoreList();
        },
        /**
         * 店员视图根据店铺状态筛选店铺
         */
        selectByStatus(val) {
            this.storeStatus = val;
            this.getStoreList();
        },
        /**
         * 店员视图根据店铺类型筛选店铺
         */
        selectByType(type) {
            this.storeType = type;
            this.getStoreList();
        }
    },
    beforeMount() {
        this.getGroupData();
    },
    mounted() {
        this.disableBtn = false;
    }
};
</script>

