<template>
    <div class="div-page">
        <template>
            <Row class="search-row">
                <!--                    <span class="search-span">账户名</span>-->
                <i-input placeholder="搜索用户名/账户" class="left-15 search-select" @on-enter="listAccountInfoFunction" v-model="searchContent"/>
                <span class="search-span">角色</span>
                <Select filterable placeholder="请选择角色" v-model="selectedRoleId" class="left-15 search-select"
                        @on-change="onRoleChangeLister">
                    <Option v-for="item in roleList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                </Select>
                <span class="left-15 txt-font-a">零售公司</span>
                <Select v-model="selectedCompanyId" filterable class="left-15 txt-font-a search-select"
                        @on-change="companySelect">
                    <Option v-for="item in companyList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                </Select>
                <span class="left-15 txt-font-a">店铺</span>
                <Select filterable placeholder="全部" v-model="selectedShopId" class="left-15 txt-font-a search-select"
                        @on-change="downShopChange">
                    <Option v-for="item in shopList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                </Select>
                <Button type="primary" class="search-btn" @click="listAccountInfoFunction">查询</Button>
                <div class="search-div-btn">
                    <Button type="primary" class="search-btn"
                            @click="addOneAccount()">+添加账户
                    </Button>

                    <Button type="primary" class="search-btn" @click="exportData" :loading="loading">导出数据</Button>

                </div>
            </Row>
        </template>
        <Table :loading="loading" :columns="columns1" :data="data1" class="table-account" size="small"></Table>
        <Page :total="totalSize" :current="pageNum" :page-size="pageSize" show-elevator show-total
              placement="top" @on-change="handlePage" class-name="ks-page"></Page>
        <Modal
                v-model="modal13"
                title="删除提示"
                @on-cancel="cancel" align="center">
            <p style="margin-top: 20px;margin-bottom: 20px">确定要删除此账户吗？删除后不可恢复</p>
            <div slot="footer" style="text-align: center;margin-bottom: 10px;margin-top: 10px">
                <Button style="width: 100px;" @click="modal13 = false">取消删除</Button>
                <Button type="error" style="width: 100px;margin-left: 20px" @click="ok">确认删除</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
    import accountManagement from "../../services/account/AccountManagement";
    import zeroExtend from "../../services/customer/zeroExtend";
    import staff from "../../services/staff/staff";
    import IncreaseData from "../../services/generalize/IncreaseData";

    export default {
        data() {
            return {
                userId: JSON.parse(sessionStorage.getItem("loginInfo")).userId,
                loading: false,
                modal13: false,
                roleList: [
                    {
                        id: '0',
                        name: '全部',
                    },
                    {
                        id: '1',
                        name: '系统管理员',
                    },
                    {
                        id: '2',
                        name: '运营人员',
                    },
                    {
                        id: '3',
                        name: '店长',
                    },
                    {
                        id: '4',
                        name: '导购',
                    },
                ],
                columns1: [
                    {
                        type: 'index2',
                        width: 80,
                        title: "序号",
                        align: 'center',
                        render: (h, params) => {
                            return h('span', params.index + (this.pageNum - 1) * this.pageSize + 1);
                        }
                    },
                    {
                        title: '用户名',
                        key: 'userName'
                    },
                    {
                        title: '别名',
                        key: 'abbreviation'
                    },
                    {
                        title: '系统账号',
                        key: 'account'
                    },
                    {
                        title: '手机号',
                        key: 'mobil',
                    },
                    {
                        title: '系统角色',
                        key: 'roleName'
                    },
                    {
                        title: '零售公司',
                        key: 'companyName'
                    },
                    {
                        title: '零售公司编码',
                        key: 'companyCode'
                    },
                    {
                        title: '店铺',
                        key: 'shopName'
                    },
                    {
                        title: '店铺编码',
                        key: 'shopCode'
                    },
                    {
                        title: '操作',
                        key: 'operation',
                        render: (h, params) => {
                            let that = this;
                            return h('div', [
                                h('span', {
                                    style: {
                                        background: 'white',
                                        border: '0',
                                        color: '#3496EB',
                                        marginRight: '15px',
                                        cursor: 'pointer'
                                    },
                                    on: {
                                        click: () => {
                                            this.$router.push({
                                                path: '/account/management/modify',
                                                query: {
                                                    accountId: params.row.accountId,
                                                    userId: params.row.userId,
                                                    userName: params.row.userName,
                                                    account: params.row.account,
                                                    password: params.row.password,
                                                    confirmPassword: params.row.confirmPassword,
                                                    roleId: params.row.roleId,
                                                    roleCode: params.row.roleCode,
                                                    shopId: params.row.shopId,
                                                    companyId: params.row.orgId,
                                                    mobil: params.row.mobil,
                                                }
                                            });
                                        }
                                    }
                                }, '修改'),
                                h('span', {
                                    style: {
                                        background: 'white',
                                        border: '0',
                                        color: 'red',
                                        marginRight: '15px',
                                        cursor: 'pointer'
                                    },
                                    on: {
                                        click: () => {
                                            that.modal13 = true;
                                            that.updateAccountId = that.data1[params.index].accountId;
                                            that.updateUserId = that.data1[params.index].userId;
                                        }
                                    }
                                }, '删除')
                            ])

                        }
                    },
                ],
                data1: [],
                selectedRoleId: 0,
                //分页内容
                totalSize: 0,
                pageNum: 1,
                pageSize: 10,
                //搜索内容
                searchContent: '',
                updateAccountId: 0,
                updateUserId: 0,
                item: null,
                companyList: [], // 零售公司列表
                selectedCompanyId: 0, // 选中的零售公司ID
                organizationalList: [],
                selectedShopId: 0, // 店铺ID
                shopList: [], // 店铺列表
            }
        },
        mounted: function () {
            this.getSelectList();
            this.listRoleInfo();
            // this.listOfShop();
            // 绑定enter事件
            this.enterKeyup();
        },
        methods: {
            //切页处理
            handlePage: function (value) {
                this.pageNum = value;
                this.listAccountInfoFunction();
            },
            //添加单个账户
            addOneAccount() {
                this.$router.push({
                    path: '/account/management/add',
                });
            },
            //查询所有角色
            listRoleInfo() {
                let that = this;
                that.roleList = [];
                accountManagement.listRoleInfoApi({}, function (data) {
                    data = data.data;
                    if (data.code === '0001') {
                        that.$Message.error("查询角色失败!");
                        return;
                    }
                    if (data.code === '0000') {
                        data = data.results;
                        that.roleList.push({
                            id: "0",
                            name: "全部"
                        });
                        for (let i = 0; i < data.length; i++) {
                            let row = data[i];
                            that.roleList.push(row);
                        }
                        if (that.$route.query != null) {
                            that.item = that.$route.query;
                            //别的页面跳转过来
                            if (that.item.id === undefined) {
                                that.selectedRoleId = "0";
                            } else {
                                that.selectedRoleId = that.item.id;
                            }
                        } else {
                            that.selectedRoleId = "0";
                        }
                        that.listAccountInfoFunction();
                    }
                })
            },
            //查询所有店铺
            listOfShop() {
                let that = this;
                that.shopList = [];
                let request = {
                    userId: this.userId
                };
                accountManagement.listAllShopApi(request, function (data) {
                    data = data.data;
                    that.loading = false;
                    if (data.code === '0001') {
                        that.$Message.error("查询店铺失败!");
                        return;
                    }
                    if (data.code === '0000') {
                        that.shopList.push({
                            id: '-1',
                            name: "全部"
                        });
                        that.selectedShopId = '-1';
                        data = data.results;
                        for (let i = 0; i < data.length; i++) {
                            let row = data[i];
                            that.shopList.push(row);
                        }

                        that.listAccountInfoFunction();
                    }
                }, function () {
                    that.loading = false;
                });
            },
            /**基础数据：区域list、零售公司list、好友list*/
            getSelectList: function () {
                let that = this;
                let request = {
                    userId: this.userId,
                };
                zeroExtend.getSelectListRequest(request, function (data) {
                    if (data.data.code !== "0000") {
                        that.$Message.error("系统异常");
                    }
                    data = data.data.results;
                    if (data) {
                        that.organizationalList = data;
                        that.companyList = that.organizationalList.filter(item => item.level === 2);
                    }
                    //插入全部选项
                    that.insertAllOption();
                });
            },
            insertAllOption: function () {
                if (this.companyList.length === 0 || this.companyList[0].id !== 0) {
                    this.companyList.splice(0, 0, {"id": 0, "name": "全部"});
                }
                if (this.shopList.length === 0 || this.shopList[0].id !== 0) {
                    this.shopList.splice(0, 0, {"id": 0, "name": "全部"});
                }
            },
            //搜索账号内容
            listAccountInfoFunction: function () {
                this.loading = true;
                let that = this;
                let request = {
                    searchContent: that.searchContent,
                    pageNum: that.pageNum,
                    pageSize: that.pageSize,
                    roleId: that.selectedRoleId,
                    companyId: that.selectedCompanyId,
                    shopId: that.selectedShopId
                };
                accountManagement.listAccountInfoApi(request, function (data) {
                    that.loading = false;

                    that.data1 = [];
                    data = data.data;
                    if (data.code === '0001') {
                        that.$Message.error("系统繁忙!");
                        return
                    }
                    if (data.code === '0000') {
                        if (data) {
                            let row = data.results.list;
                            that.totalSize = data.results.total;
                            for (let i = 0; i < row.length; i++) {
                                let entity = row[i];
                                if (!entity.channel) {
                                    entity.channel = '--';
                                }
                                if (!entity.account) {
                                    entity.account = '--';
                                }
                                if (!entity.userName) {
                                    entity.userName = '--';
                                }
                                if (!entity.roleName) {
                                    entity.roleName = '--';
                                }
                                if (!entity.shopName) {
                                    entity.shopName = '--';
                                }
                                that.data1.push(entity);
                            }
                            if (row === null || row.length === 0) {
                                that.totalSize = 0;
                            }
                        }
                    }
                }, function () {
                    that.loading = false;
                });

            },
            //删除账号
            remove() {
                let that = this;
                let request = {
                    accountId: that.updateAccountId,
                    userId: that.updateUserId
                };
                accountManagement.removeAccountApi(request, function (data) {
                    if (data.data.code === '0001') {
                        that.$Message.info("删除失败");
                        return
                    }
                    if (data.data.code === '0000') {
                        that.$Message.info("删除成功");
                        that.pageNum = 1;
                        that.listAccountInfoFunction();
                    }
                })
            },
            cancel() {

            },
            ok() {
                this.modal13 = false;
                this.remove();
            },
            enterKeyup() {
                document.addEventListener("keyup", this.buttonOperation);
            },
            buttonOperation() {
                const code = event.keyCode
                    ? event.keyCode
                    : event.which
                        ? event.which
                        : event.charCode;
                if (code === 13) {
                    this.pageNum = 1;
                    this.listAccountInfoFunction();
                } else if (code !== 13 && code === 1) {
                    this.pageNum = 1;
                    this.listAccountInfoFunction();
                }
            },
            // 角色选择改变事件
            onRoleChangeLister: function (value) {
                let val = value;

            },
            //零售公司选择
            companySelect: function (value) {
                this.selectedCompanyId = value;
                //加载店铺
                this.downShopData(this.selectedCompanyId);
                this.selectedStore = 0;
                this.shopList = [];
            },
            // 店铺选择
            downShopChange: function (value) {
                let val = value;
                let that = this;
                this.selectedStore = val;

            },
            downShopData: function (selected) {
                let that = this;
                let companyId = selected;
                if (!selected) {
                    companyId = that.companyId;
                }
                let customerIds = [];
                this.customerList = [];
                if (companyId === 0) {
                    //
                    that.selectedShopId = 0;
                } else {
                    this.customerList = this.organizationalList.filter(item => item.parentId === companyId && item.level === 3);
                    this.insertAllOption();
                }
                customerIds = this.customerList.map(item => item.id);

                let request = {userId: that.userId, customerIds: customerIds, companyId: companyId};
                staff.downShopData(request, function (data) {
                    data = data.data.results;
                    if (data) {
                        that.shopList = [{"id": 0, "name": "全部"}];
                        for (let i = 0; i < data.length; i++) {
                            let entity = data[i];
                            if (entity) {
                                that.shopList.push(entity);
                            }
                        }
                    }
                })
            },
            //零推广导出
            exportData: function () {

                this.loading = true;
                let that = this;
                let request = {
                    searchContent: that.searchContent,
                    pageNum: that.pageNum,
                    pageSize: that.totalSize,
                    roleId: that.selectedRoleId,
                    companyId: that.selectedCompanyId,
                    shopId: that.selectedShopId
                };
                accountManagement.listAccountInfoApi(request, function (data) {
                    that.loading = false;
                    data = data.data;
                    if (data.code === '0001') {
                        return
                    }
                    if (data.code === '0000') {
                        if (data) {
                            let row = data.results.list;
                            if (row && row.length > 0) {
                                let originAllData = [];
                                for (let i = 0; i < row.length; i++) {
                                    let entity = row[i];
                                    entity.index = i + 1;
                                    originAllData.push(entity);
                                }
                                let title = "账号";
                                require.ensure([], () => {
                                    const {export_json_to_excel} = require('../../excel/Export2Excel');
                                    const tHeader = ['序号', '用户名', '别名', '账号', '手机号码', '角色', '零售公司', '零售公司编码', '店铺名称', '店铺编码'];
                                    // 属性名
                                    const filterVal = ['index', 'userName', 'abbreviation', 'account', 'mobil', 'roleName', 'companyName', 'companyCode', 'shopName', 'shopCode'];

                                    // 数据
                                    //把data里的tableData存到list
                                    const data = that.formatJson(filterVal, originAllData);
                                    export_json_to_excel(tHeader, data, title);
                                });
                            }
                        }
                    }
                }, function () {
                    that.loading = false;
                });
            },
            formatJson(filterVal, jsonData) {
                return jsonData.map(v => filterVal.map(j => v[j]))
            },
        },

    }
</script>

<style scoped>

    .left-15 {
        margin-left: 15px;
    }

    .div-page {
        margin-top: 20px;
        margin-left: 20px;
    }

    .search-row {
        background-color: #F7F8FA;
        line-height: 80px;
    }

.search-btn {
  margin-left: 30px;
}

.search-btn-add-row {
  text-align: right;
  padding-right: 20px;
}

    .table-account {
        margin-top: 30px;
    }
</style>
