<template>
    <div>
        <Row class="search-row">
            <i-col span="24" class="search-col">
                <Row class="row-style">
                    <i-input placeholder="店铺名称或编码" class="search-select" v-model="searchShop"/>
                    <span class="search-span">大区</span>
                    <Select v-model="regionId" filterable class="search-select" @on-change="regionSelect">
                        <Option v-for="item in regionList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                    </Select>
                    <span class="search-span">零售公司</span>
                    <Select v-model="companyId" filterable class="search-select" @on-change="companySelect">
                        <Option v-for="item in companyList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                    </Select>
                    <span class="search-span">店铺</span>
                    <Select v-model="selectedStore" filterable class="search-select">
                        <Option v-for="item in shopList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                    </Select>
                    <Button type="primary" @click="searchCustomerDataBtnClick" class="search-btn">查询</Button>
                    <!--<Button type="primary" @click="downloadStoreCode" style="margin-right: 10px;">批量下载门店码</Button>-->
                    <!--<Button type="primary"  @click="downloadStoreSellerCode"  style="margin-right: 10px;">批量下载导购码</Button>-->
                    <!--<Button type="primary" @click="open()" style="margin-right: 10px;">开通门店号</Button>-->
                </Row>
            </i-col>
        </Row>

        <Table :columns="columns1" :data="data1" class="table-store" size="small">
            <template slot-scope="{row}" slot="qrCodeAction">
                <img :src="require('../../../static/img/qrCode-init.png')" @click="show(row)"
                     class="table-img-qr-code"/>
            </template>
            <router-link slot-scope="{row}" slot="action"
                         :to="{path:'/shop/increase/manager/staff',query:{storeId:row.id}}">
                <Button ghost class="router-btn"> 门店导购管理</Button>
            </router-link>
        </Table>

        <!-- 预览二维码 -->
        <Modal
                v-model="isShow"
                :title="showStoreName"
                :footer-hide="true"
                width="230"
                class-name="vertical-center-modal"
                @on-ok="ok">
            <div slot="header">
                <p></p>
            </div>
            <p>{{this.showStoreName}}</p>
            <img :src="qrCodeImage" style="width:200px;height:200px;"/>
            <div style="text-align: center;">
                <Button ghost type="primary" @click="download(rowData)">下载</Button>
            </div>
        </Modal>

        <!-- 开通企业微信号 -->
        <Modal
                v-model="isShowAdd"
                :footer-hide="true"
                @on-ok="ok">
            <div slot="header">开通企业微信号</div>

            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
                <FormItem label="名称" prop="name">
                    <i-input type="text" v-model="formValidate.name" placeholder="请输入名字"></i-input>
                </FormItem>
                <FormItem label="别名" prop="alias">
                    <i-input v-model="formValidate.alias" placeholder="请输入别名"></i-input>
                </FormItem>
                <FormItem label="账号" prop="userId">
                    <i-input v-model="formValidate.userId" placeholder="请输入账号"></i-input>
                </FormItem>
                <FormItem label="手机" prop="mobile">
                    <i-input v-model="formValidate.mobile" placeholder="成员通过验证该手机号后可加入企业">
                        <Select v-model="formValidate.selectedPhoneRegion" slot="prepend" style="width: 80px">
                            <Option v-for="item in prefixDefault" :key="item.prefix + item.en" :value="item.prefix">
                                {{item.prefix}}
                            </Option>
                        </Select>
                    </i-input>
                </FormItem>
                <FormItem label="邮箱" prop="mail">
                    <i-input v-model="formValidate.email" placeholder="请输入邮箱"></i-input>
                </FormItem>
                <FormItem label="地址" prop="address">
                    <i-input v-model="formValidate.address" placeholder="请输入地址"></i-input>
                </FormItem>
                <FormItem label="零售公司" prop="departIds">
                    <Select v-model="formValidate.departIds" placeholder="选择零售公司"
                            @on-change="downCompanyChange(formValidate)">
                        <Option v-for="item in regionList" :value="item.id" :key="item.id">{{item.name}}</Option>
                    </Select>
                </FormItem>
                <FormItem label="店铺" prop="storeId">
                    <Select v-model="formValidate.storeId" placeholder="选择店铺">
                        <Option v-for="item in shopList" :value="item.id" :key="item.id">{{item.name}}</Option>
                    </Select>
                </FormItem>
                <!--

                                <FormItem label="职务" prop="position">
                                    <i-input v-model="formValidate.position" placeholder="请输入职务"></i-input>
                                </FormItem>
                -->

                <!--<FormItem label="身份" prop="position">
                    <i-input v-model="formValidate.position" placeholder="请输入身份"></i-input>
                </FormItem>-->

                <FormItem label="">
                    <CheckboxGroup v-model="formValidate.checkbox">
                        <Checkbox label="vail">通过邮箱或短信发送企业邀请</Checkbox>
                    </CheckboxGroup>
                </FormItem>

                <FormItem style="text-align: left;">
                    <Button type="primary" @click="handleSubmit(formValidate)">保存并继续添加</Button>
                    <Button @click="handleReset('formValidate')" style="margin-left: 8px">取消</Button>
                </FormItem>
            </Form>
        </Modal>

        <!-- 批量开通 -->
        <Modal
                width="85"
                v-model="isShowImport"
                :footer-hide="true"
                @on-ok="ok">
            <div slot="header">批量开通账号</div>

            <div v-show="isShowError" style="width: 100%;height: 200px;background-color: #FEE6EE;overflow-y: auto;">
                <p>导入失败：</p>
                <p style="margin-left: 40px" v-for="item in errorList" :value="item.row" :key="item.row">
                    {{item.reason}}</p>
            </div>

            <div style="text-align: center;background-color:#FAFAFC;height: 80px;line-height: 80px;width:50%;margin-left: 25%;margin-top: 10px">
                导入说明：请下载模板，然后将资料填到模板中
                <Button
                        style="color: #2074E2;border: 1px solid #2074E2;width: 97px;height: 28px"
                        @click="downLoadImportExcel"
                >下载模板
                </Button>
            </div>

            <Upload
                    multiple
                    type="drag"
                    :action="updateUrl"
                    :on-success="updateSuccess"
                    style="margin-top:30px;width:50%;margin-left: 25%">
                <div style="padding: 20px 0;background-color:#FAFAFC">
                    <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                    <p>点击或拖拽文件</p>
                </div>
            </Upload>
        </Modal>
        <Page :total="total" :current="pageNum" :page-size="pageSize" show-elevator show-total
              placement="top" @on-change="handlePage" class-name="ks-page"></Page>
    </div>
</template>

<script>
    import data from '../../utils/PhoneRegionData';
    import http from '../../services/store/IncreaseStoreManager';
    import staff from "../../services/staff/staff";
    import zeroExtend from "../../services/customer/zeroExtend";

    export default {
        name: "IncreaseStoreManager",
        inject: ['setMenuName'],
        data() {
            return {
                userId: JSON.parse(sessionStorage.getItem("loginInfo")).userId,
                searchShop: null,
                total: 0,
                pageSize: 10,
                pageNum: 1,
                prefixDefault: data.prefixDefault,
                isShow: false,
                isShowImport: false,
                isShowError: false,
                isShowAdd: false,
                showStoreName: '',
                updateUrl: http.getBaseUrl() + "/store/emp/import",
                downLoadStoreCodeUrl: http.getBaseUrl() + "/store/emp/download/store/code",
                qrCodeImage: '',
                selectedRegion: 0,
                selectedBigRegion: 0,
                //所有组织list
                organizationalList: [],
                //区域list
                regionList: [],
                regionId: 0,
                //零售公司list
                companyList: [],
                customerList: [],
                companyId: 0,

                errorList: [],
                selectedStore: 0,
                shopList: [],
                rowData: {},
                company: null,
                columns1: [
                    {
                        title: '序号',
                        key: 'orderNum',
                        className: 'table-width-80'
                    },
                    {
                        title: '店铺名称',
                        key: 'name',
                        className: 'table-width-300'
                    },
                    {
                        title: '店铺编码',
                        key: 'code',
                        className: 'table-width-90'
                    },
                    {
                        title: '门店企业号',
                        key: 'cpUserId',
                        className: 'table-width-140'
                    },
                    {
                        title: '大区名',
                        key: 'regionName',
                        className: 'table-width-100'
                    },
                    {
                        title: '零售公司',
                        key: 'companyName',
                        className: 'table-width-200'
                    },
                    {
                        title: '员工数',
                        key: 'staffNum',
                        className: 'table-width-80'
                    },
                    {
                        title: '客户数',
                        key: 'customerNum',
                        className: 'table-width-80'
                    },
                    {
                        title: '推广码',
                        slot: 'qrCodeAction',
                        className: 'table-width-80'
                    },
                    {
                        title: '操作',
                        slot: 'action'
                    }
                ],
                data1: [
                    /* {
                         id: 1,
                         storeName: '店铺1',
                         storeWx: 'D1',
                         staffNum: 10,
                         customerNum: 999
                     },
                     {
                         id: 2,
                         storeName: '店铺2',
                         storeWx: 'D2',
                         staffNum: 10,
                         customerNum: 999
                     },
                     {
                         id: 3,
                         storeName: '店铺3',
                         storeWx: 'D3',
                         staffNum: 10,
                         customerNum: 999
                     },
                     {
                         id: 4,
                         storeName: '店铺4',
                         storeWx: 'D4',
                         staffNum: 10,
                         customerNum: 999
                     }*/
                ],
                // 开通企业微信 表单
                formValidate: {
                    alias: '',
                    userId: '',
                    gender: '',
                    mobile: '',
                    email: '',
                    address: '',
                    departIds: '',
                    selectedPhoneRegion: '86',
                    duty: '',
                    position: '',
                    interest: [],
                    desc: '',
                    checkbox: ['vail'],
                    storeId: '',
                },
                ruleValidate: {
                    userId: [
                        {required: true, message: '账号不能为空', trigger: 'blur'}
                    ],
                    // gender: [
                    //     { required: true, message: '请选择性别', trigger: 'change' }
                    // ],
                    mobile: [
                        {required: true, message: '手机号码不能为空', trigger: 'blur'}
                    ],
                    // mail: [
                    //     { required: true, message: '邮箱不能为空', trigger: 'blur' },
                    //     { type: 'email', message: '邮箱格式错误', trigger: 'blur' }
                    // ],
                    departIds: [
                        {required: true, message: '请选择部门', trigger: 'change'}
                    ],
                    storeId: [
                        {required: true, message: '请选择部门', trigger: 'change'},
                    ]
                }
            }
        },
        mounted() {
            this.setMenuName("门店推广", "推广管理");
            this.listOfStore();
            this.getSelectList();
            // this.downBigRegionData();
            // this.downRegionData();
            this.downShopData();
        },
        methods: {
            searchCustomerDataBtnClick: function () {
                this.listOfStore();
            },
            listOfStore() {
                let that = this;
                let request = {
                    userId: that.userId,
                    regionId: that.changeData(that.regionId),
                    companyId: that.changeData(that.companyId),
                    storeId: that.changeData(that.selectedStore),
                    pageNum: that.pageNum,
                    pageSize: that.pageSize,
                    code: that.searchShop
                };
                http.storeList(request, function (data) {
                    data = data.data;
                    if (data.code == "0000") {
                        that.data1 = [];
                        let datas = data.results;
                        //总页数
                        if (datas.total == null) {
                            that.total = 0;
                        } else {
                            that.total = datas.total;
                        }
                        if (datas.list == null) {
                            datas.list = [];
                        }
                        that.data1 = datas.list;
                    }
                })
            },
            addStoreWX: function (request) {
                let that = this;
                http.addStoreWX(request, function (data) {
                    data = data.data;
                    if (data.code == "0000") {
                        if (data.results.indexOf("8888") != -1) {
                            let str = data.results.split(",");
                            that.$Message.success('该企业微信已被 【' + str[1] + '】绑定 请从新绑定微信号');
                        } else {
                            that.$Message.success('添加成功!');
                            that.listOfStore();
                            this.handleAdd(this.formValidate);
                        }
                    }
                })
            },
            //插入全部选项
            insertAllOption: function () {
                if (this.regionList.length === 0 || this.regionList[0].id !== 0) {
                    this.regionList.splice(0, 0, {"id": 0, "name": "全部"});
                }
                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": "全部"});
                }
            },
            /**基础数据：区域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.regionList = that.organizationalList.filter(item => item.level === 1);
                        that.companyList = that.organizationalList.filter(item => item.level === 2);
                    }
                    //插入全部选项
                    that.insertAllOption();
                });
            },
            //区域选择
            regionSelect: function () {
                let regionId = this.regionId;
                if (regionId === 0) {
                    this.companyList = this.organizationalList.filter(item => item.level === 2);
                } else {
                    this.companyList = this.organizationalList.filter(item => item.parentId === regionId && item.level === 2);
                }
                this.insertAllOption();
                this.companyId = 0;
                this.selectedStore = 0;
                //加载店铺
                this.downShopData();
            },
            //零售公司选择
            companySelect: function () {
                //加载店铺
                this.downShopData(this.companyId);
                this.selectedStore = 0;
            },
            downCompanyChange: function (formValidate) {
                this.downShopData(formValidate.departIds);
            },
            downShopData: function (selected) {
                let that = this;
                let companyId = selected;
                if (!selected) {
                    companyId = that.companyId;
                }
                let regionId = that.regionId;
                let customerIds = [];
                this.customerList = [];
                if (regionId === 0) {
                    //
                } else {
                    this.companyList = this.organizationalList.filter(item => item.parentId === regionId && item.level === 2);
                    let companyIds = this.companyList.map(item => item.id);
                    this.customerList = this.organizationalList.filter(item => companyIds.indexOf(item.parentId) !== -1 && item.level === 3);
                    this.insertAllOption();
                }
                if (companyId === 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: JSON.stringify(customerIds)};
                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);
                            }
                        }
                    }
                })
            },
            changeData: function (value) {
                if (value == 0) {
                    return null;
                }
                return value;
            },
            show: function (index) {
                this.isShow = true;
                this.showStoreName = index.name;
                this.qrCodeImage = index.qrCodeAction;
                this.rowData = index;
            },
            hide: function () {
                this.isShow = false;
            },
            // 下载二维码
            download: function (index) {
                let fileName = index.name + "-门店码";
                http.downloadImg({
                    url: index.qrCodeAction
                }, fileName, function (/*data*/) {

                })
            },
            //切页处理
            handlePage: function (value) {
                this.pageNum = value;
                this.listOfStore();
            },

            ok: function () {
                this.isShow = false;
            },
            cancel: function () {
                this.isShow = false;
            },
            open: function () {
                this.isShowAdd = true;

            },
            remove: function () {

            },
            showImport() {
                this.isShowImport = true;
                this.isShowError = false
            },
            handleSubmit(name) {
                if (name) {
                    // 调用添加接口
                    this.addStoreWX(name);
                } else {
                    this.$Message.error('Fail!');
                }
            },
            handleReset(name) {
                this.$refs[name].resetFields();
                this.isShowAdd = false;
            },
            downLoadImportExcel() {
                window.location.href = '/门店号批量开通模板.xlsx'
            },
            handleAdd(value) {
                value.alias = '',
                    value.userId = '',
                    value.gender = '',
                    value.mobile = '',
                    value.email = '',
                    value.address = '',
                    value.departIds = '',
                    value.selectedPhoneRegion = '86',
                    value.duty = '',
                    value.position = '',
                    value.interest = [],
                    value.desc = '',
                    value.checkbox = ['vail'],
                    value.storeId = ''
            },
            downloadStoreCode() {
                http.downloadStoreCode({}, null);
            },
            downloadStoreSellerCode() {
                http.downloadStoreSellerCode({}, null);
            },
            updateSuccess(response) {
                if (response.code === "0000") {
                    let data = response.results;
                    if (data && data.length > 0) {
                        this.errorList = data;
                        this.isShowError = true;
                    }
                }
            }
        }
    }
</script>

<style scoped>
    .table-store {
        margin-top: 20px;
    }

    .table-img-qr-code {
        margin-left: 5px;
        margin-top: 5px;
        width: 30px;
        height: 30px;
    }

    .router-btn {
        border: 0px;
        color: #3496EB !important;
        margin-left: -15px;
    }
    .modal-img{
        width:200px;height:200px;
    }

    .table-width-80 {
        width: 80px !important;
    }

    .table-width-90 {
        width: 90px !important;
    }

    .ivu-table th.table-width-100 {
        width: 100px !important;
    }

    .ivu-table th.table-width-140 {
        width: 140px !important;
    }


    .ivu-table th.table-width-200 {
        width: 200px !important;
    }

    .ivu-table th.table-width-300 {
        width: 300px !important;
    }
</style>
