import * as API from 'api/virtual/properties';

export default {
    name: 'Products',
    components: {
        UiEdit: resolve => require(['views/virtual/properties/edit'], resolve),
        UiAgent: resolve => require(['views/virtual/properties/agent'], resolve),
        UiSettings: resolve => require(['views/virtual/properties/settings'], resolve),
        UiConfigure: resolve => require(['views/virtual/properties/configure'], resolve),
        platformSet: resolve => require(['views/virtual/properties/platform_set'], resolve),
    },
    data() {
        return {
            properties: new Map(),
            showData: [],
            params: {
                company_id: '',
                package_id: ''
            },
            only: ['company_id', 'package_id', 'product', 'vehicle_type', 'company', 'platform', 'customer', 'province', 'agent'],
            updates: new Map(),
            configureShow: false,
            platform: {
                show: false,
                id: '',
                name: '',
            },
            settingsShow: false,
            settingsData: {},
            agentsData: {},
            agentsProp: [],
            editModel: false,
            editObj: {
                show: false,
                isUpdate: false,
                data: null
            },
            agentObj: {
                show: false,
                isUpdate: false,
                data: null
            },
            search: {
                show: true
            },
            page: {
                total: 0,
                limit: 10,
                page: 1
            },
            companies: [],
            companyFilters: [],
            packages: [],
            packageFilters: [],
            data: [],
            columns: [
                {
                    title: '序号',
                    key: '',
                    width: 80,
                    render: (h, context) => {
                        return h('span', context.row._index + 1);
                    }
                },
                {
                    title: '企业名称',
                    key: 'company_name',
                    width: 210,
                    tooltip: true
                },
                {
                    title: '套餐名称',
                    key: 'package_name',
                    width: 120
                },
                {
                    title: '月流量',
                    key: 'flows',
                    width: 100
                },
                {
                    title: '销售数',
                    key: 'counts',
                    width: 100
                },
                {
                    title: '活跃数',
                    key: 'actives',
                    width: 100
                },
                {
                    title: '公司类型',
                    key: 'company',
                    minWidth: 170,
                    render: (h, context) => {
                        return this.editRender('company', h, context);
                    }
                },
                // {
                //   title: '平台/API',
                //   key: 'platform',
                //   minWidth: 120,
                //   render: (h, context) => {
                //     return this.editRender('platform', h, context);
                //   }
                // },
                // {
                //   title: '客户类型',
                //   key: 'customer',
                //   minWidth: 120,
                //   render: (h, context) => {
                //     return this.editRender('customer', h, context);
                //   }
                // },
                // {
                //   title: '产品类型',
                //   key: 'product',
                //   minWidth: 130,
                //   render: (h, context) => {
                //     return this.editRender('product', h, context);
                //   }
                // },
                // {
                //   title: '套餐类型',
                //   key: 'package_type',
                //   width: 100,
                //   render: (h, context) => {
                //     return h('span', this.productPackageTypes[context.row.product]);
                //   }
                // },
                // {
                //   title: '车辆类型',
                //   key: 'vehicle_type',
                //   minWidth: 120,
                //   render: (h, context) => {
                //     return this.editRender('vehicle_type', h, context);
                //   }
                // },
                // {
                //   title: '车型分类',
                //   key: 'vehicle_group',
                //   minWidth: 120,
                //   render: (h, context) => {
                //     return h('span', this.vehicleTypeVehicleGroups[context.row.vehicle_type]);
                //   }
                // },
                {
                    title: '销售省份',
                    key: 'action',
                    width: 150,
                    render: (h, {
                        row,
                        column,
                        index
                    }) => {
                        let html = [];

                        if (this.haveJurisdiction('update')) {
                            let button = h('Button', {
                                props: {
                                    type: row.province ? 'success' : 'error',
                                    size: 'small'
                                },
                                class: ['btn'],
                                on: {
                                    click: (event) => {
                                        this.editObj = { show: true, data: row, isUpdate: this.editModel };
                                    }
                                }
                            }, this.editModel ? '设置' : '查看');

                            html.push(h('Tooltip', {
                                props: {
                                    content: row.province ? '已设置' : '省份未设置'
                                }
                            }, [button]));
                        }

                        if (html.length) {
                            return h('div', html);
                        }
                    }
                },
                {
                    title: '代理商',
                    key: 'action',
                    width: 150,
                    render: (h, {
                        row,
                        column,
                        index
                    }) => {
                        let html = [];

                        if (this.haveJurisdiction('update')) {
                            let button = h('Button', {
                                props: {
                                    type: row.agent ? 'success' : 'error',
                                    size: 'small'
                                },
                                class: ['btn'],
                                on: {
                                    click: (event) => {
                                        this.agentObj = { show: true, data: row, isUpdate: this.editModel };
                                        this.agentsProp = this.agentsData[row.company_id] ? this.agentsData[row.company_id] : [];
                                    }
                                }
                            }, this.editModel ? '设置' : '查看');

                            html.push(h('Tooltip', {
                                props: {
                                    content: row.agent ? '已设置' : '代理商未设置'
                                }
                            }, [button]));
                        }

                        if (html.length) {
                            return h('div', html);
                        }
                    }
                },
                {
                    title: '平台配置',
                    key: 'action',
                    width: 150,
                    render: (h, {
                        row,
                        column,
                        index
                    }) => {
                        let html = [];

                        if (this.haveJurisdiction('update')) {
                            let button = h('Button', {
                                props: {
                                    type: 'success',
                                    size: 'small'
                                },
                                class: ['btn'],
                                on: {
                                    click: (event) => {
                                        this.platform.show=true;
                                        this.platform.id=row.company_id;
                                        this.platform.name=row.company_name;
                                        this.platform.packagetype=row.package[0];
                                        this.platform.propertyId=row.id;
                                    }
                                }
                            }, '配置');

                            html.push(button);
                        }

                        if (html.length) {
                            return h('div', html);
                        }
                    }
                }
            ]
        };
    },
    watch: {
        editModel(value) {
            this.columns = this.columns;
            this.$refs.table.handleResize();
        }
    },
    computed: {
        productPackageTypes() {
            let obj = {};

            let packages = this.settingsData.package ? this.settingsData.package : {};

            for (const key in packages) {
                const element = packages[key];

                for (let index = 0; index < element.length; index++) {
                    const value = element[index];
                    obj[value] = key;
                }
            }

            return obj;
        },
        vehicleTypeVehicleGroups() {
            let obj = {};

            let vehicles = this.settingsData.vehicle ? this.settingsData.vehicle : {};

            for (const key in vehicles) {
                const element = vehicles[key];

                for (let index = 0; index < element.length; index++) {
                    const value = element[index];
                    obj[value] = key;
                }
            }

            return obj;
        }
    },
    created() {
        this.index();
        this.settings();
        this.agents();
    },
    methods: {
        editRender(key, h, context) {
            if (!this.editModel) {
                return h('span', context.row[key]);
            }

            let options = [];

            let arr;
            if (key === 'product') {
                arr = Object.values(this.settingsData['package']).join(",").split(",");
            } else if (key === 'vehicle_type') {
                arr = Object.values(this.settingsData['vehicle']).join(",").split(",");
            } else {
                arr = this.settingsData[key];
            }

            for (let index = 0; index < arr.length; index++) {
                const element = arr[index];
                options.push(h('Option', {
                    props: {
                        value: element
                    }
                }, element));
            }

            return h('Select', {
                props: {
                    value: context.row[key],
                    size: 'small',
                    transfer: true
                },
                on: {
                    input: (value) => {
                        let index = this.getIndex(context.row);
                        let property = this.properties.get(index);
                        property[key] = value;
                        this.properties.set(index, property);
                        this.changePage(this.page.page);
                        this.updates.set(index, this.properties.get(index));
                    }
                }
            }, options);
        },
        /**
         * [index 列表]
         * @param  {Number} company_id [description]
         * @return {[type]}      [description]
         */
        index(page = 1) {
            if (!this.properties.size) {
                this.isShowLoading(true);
                API.index().then(res => {
                    if (res.code === 0) {
                        let properties = new Map();

                        res.data.forEach(element => {
                            properties.set(this.getIndex(element), element);
                        });

                        this.properties = properties;
                        this.changePage(page);
                        this.complete();
                    }
                    this.isShowLoading(false);
                });
            } else {
                this.changePage(page);
            }
        },
        complete() {
            let companies = {};

            let properties = Array.from(this.properties.values());

            properties.forEach((item) => {
                companies[item.company_id] = item.company_name;
            });

            let companyArray = [];

            for (const key in companies) {
                companyArray.push({ id: key, name: companies[key] });
            }

            this.companies = companyArray;

            let packages = {};

            properties.forEach((item) => {
                packages[item.package_id] = item.package_name;
            });

            let packageArray = [];

            for (const key in packages) {
                packageArray.push({ id: key, name: packages[key] });
            }

            this.packages = packageArray;
        },
        /**
         * [request 刷新]
         * @return {[type]} [description]
         */
        request() {
            this.properties = [];
            this.index();
        },
        resetSearch() {
            for (let k in this.params) {
                this.params[k] = '';
            }
            this.index(1);
        },
        changeLimit(limit) {
            this.page.limit = limit;
            this.changePage(1);
        },
        changePage(page) {
            this.page.page = page;

            let properties = Array.from(this.properties.values());

            if (this.params.company_id !== '' && this.params.company_id !== undefined) {
                properties = properties.filter(el => { return el.company_id == this.params.company_id; });
            }

            if (this.params.package_id !== '' && this.params.package_id !== undefined) {
                properties = properties.filter(el => { return el.package_id == this.params.package_id; });
            }

            if (this.params.status !== '' && this.params.status !== undefined) {
                if (this.params.status === 0) {
                    properties = properties.filter(el => { return el.product !== '' && el.province !== null; });
                } else if (this.params.status === 1) {
                    properties = properties.filter(el => { return el.product === '' || el.province === null; });
                }
            }

            this.page.total = properties.length;

            this.showData = properties.slice((page - 1) * this.page.limit, page * this.page.limit);
        },
        agents() {
            if (!this.agentsData.length) {
                API.agents().then(res => {
                    if (res.code === 0) {
                        this.agentsData = res.data;
                    }
                });
            }
        },
        settings() {
            if (!this.settingsData.length) {
                API.settings().then(res => {
                    if (res.code === 0) {
                        this.settingsData = res.data;
                    }
                });
            }
        },
        updateSettings(values) {
            this.settingsData = values;
        },
        ok() {
            if (!this.updates.size) {
                this.$Message.warning('数据未修改');
                this.editModel = false;
                return;
            }

            this.isShowLoading(true);

            let updates = [];

            this.updates.forEach((element) => {
                let obj = {};
                for (const key in element) {
                    if (this.only.indexOf(key) !== -1) {
                        obj[key] = element[key];
                    }
                }
                updates.push(obj);
            });

            console.log("updates", updates);

            API.store({ data: updates }).then(res => {
                if (res.code === 0) {
                    this.updates = new Map();
                    this.editModel = false;
                }
                this.isShowLoading(false);
            });
        },
        handleProvinceSuccess(data) {
            let index = this.getIndex(data);
            this.properties.set(index, data);
            this.changePage(this.page.page);
            this.updates.set(index, this.properties.get(index));
        },
        handleAgentSuccess(data) {
            let index = this.getIndex(data);
            this.properties.set(index, data);
            this.changePage(this.page.page);
            this.updates.set(index, this.properties.get(index));
        },
        exportExcel() {
            let params = {};

            for (const key in this.params) {
                const element = this.params[key];

                if (element !== '' && element !== undefined) {
                    params[key] = element;
                }
            }

            this.isShowLoading(true);

            API.exportExcel(params).then(res => {
                if (res.code === 0) {
                    if (res.data) {
                        this.downloadFile(res.data);
                    } else {
                        this.$Modal.success({
                            title: '提示',
                            content: '当前导出数据量大，已进入后台队列导出模式，请稍后至导出列表查看下载。'
                        });
                    }
                }
                this.isShowLoading(false);
            }).catch(() => {
                this.isShowLoading(false);
            });
        },
        importExcel(file) {
            this.isShowLoading(true);
            API.importExcel(file).then(res => {
                if (res.code === 0) {
                    this.request();
                    this.$Message.success(res.message);
                }

                this.isShowLoading(false);
            });

            return false;
        },
        getIndex(row) {
            return row.company_id + '_' + row.package_id;
        }
    }
};
