import React from 'react';
import { Icon, Button, Input, Spin, Table, message, Modal, Tabs, InputNumber, Checkbox, Select } from 'antd';
import ajax from 'jquery/src/ajax/xhr.js';
import $ from 'jquery/src/ajax';
import './userList.less';

const ListAdd = React.createClass({
    getInitialState () {
        return {
            visible: false,
            loading: false
        };
    },
    showModal () {
        this.setState({
            visible: true,
        });
    },
    handleCancel (e) {
        this.setState({
            visible: false,
        });
    },
    handleOk () {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/member/addGradeName",
            data: {
                gradeName: this.state.lvlName,
                memberRank: this.state.level
            },
            success: function (data) {
                if (data.error && data.error.length) {
                    message.warning(data.error[0].message);
                } else {
                    message.success("添加成功！");
                    this.state.visible = false;
                    this.props.refresh(this.state.level);
                }
                this.setState({
                    loading: false
                })
            }.bind(this),
        });
    },
    render () {
        const Option = Select.Option;
        return (
            <div className="patent-desc" style={{ float: 'right', marginRight: '20px' }}>
                <Button type="primary" onClick={this.showModal}>添加新等级</Button>
                <Modal maskClosable={false}
                    title="新增用户等级"
                    visible={this.state.visible}
                    onCancel={this.handleCancel}
                    afterClose={() => { this.state.lvlName = undefined; this.state.level = undefined }}
                    width='400px'
                    footer={[
                        <Button key="submit" type="primary" loading={this.state.loading} onClick={this.handleOk}>提交</Button>,
                        <Button key="back" onClick={this.handleCancel}>返回</Button>
                    ]}
                    className="admin-desc-content">
                    <div className='orgAdd-input'>
                        <span>会员等级名称：</span>
                        <Input value={this.state.lvlName} style={{ width: '200px' }}
                            onChange={(e) => { this.setState({ lvlName: e.target.value }); }} />
                    </div>
                    <div className='orgAdd-input'>
                        <span>会员等级：</span>
                        <Select value={this.state.level} style={{ width: 120 }}
                            onChange={(e) => { this.setState({ level: e }) }}>
                            <Option value="1">1</Option>
                            <Option value="2">2</Option>
                            <Option value="3">3</Option>
                            <Option value="4">4</Option>
                            <Option value="5">5</Option>
                        </Select>
                    </div>
                </Modal>
            </div>
        );
    }
});

const ListDelete = React.createClass({
    getInitialState () {
        return {
            visible: false,
            loading: false
        };
    },
    showModal () {
        this.setState({
            visible: true,
        });
    },
    handleCancel (e) {
        this.setState({
            visible: false,
        });
    },
    handleOk () {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/member/delGrade",
            data: {
                id: this.props.rid
            },
            success: function (data) {
                if (data.error && data.error.length) {
                    message.warning(data.error[0].message);
                } else {
                    message.success("删除成功！");
                    this.state.visible = false;
                    this.props.refreshForDel();
                }
                this.setState({
                    loading: false
                })
            }.bind(this),
        });
    },
    render () {
        return (
            <div className="patent-desc" style={{ float: 'right', marginRight: '20px' }}>
                <Button type="ghost" onClick={this.showModal}>删除</Button>
                <Modal maskClosable={false}
                    title="删除用户等级"
                    visible={this.state.visible}
                    onCancel={this.handleCancel}
                    width='400px'
                    footer={[
                        <Button key="submit" type="primary" loading={this.state.loading} onClick={this.handleOk}>提交</Button>,
                        <Button key="back" onClick={this.handleCancel}>返回</Button>
                    ]} >
                    <div className="level-tabs-modal">
                        <p>
                            <Icon type="exclamation-circle-o" />
                            <span> 确认要删除该用户等级吗？删除以后不可恢复！</span>
                        </p>
                    </div>
                </Modal>
            </div>
        );
    }
});

const SetContent = React.createClass({
    getInitialState () {
        return {
            visible: false,
            loading: false,
            columns: [
                {
                    title: '会员时长',
                    dataIndex: 'time',
                    key: 'time',
                    render: (text, record, index) => {
                        return <div>
                            <Input style={{ width: '80px' }}
                                value={record.time}
                                onChange={(e) => {
                                    record.time = e.target.value;
                                    this.setState({ dataSource: this.state.dataSource });
                                }} />
                            <span style={{ marginLeft: '10px' }}>个月</span>
                        </div>
                    }
                }, {
                    title: '金额',
                    dataIndex: 'money',
                    key: 'money',
                    render: (text, record, index) => {
                        return <div>
                            <InputNumber step={0.01} min={0}
                                value={record.money}
                                onChange={(e) => {
                                    record.money = e;
                                    this.setState({ dataSource: this.state.dataSource });
                                }} />
                            <span style={{ marginLeft: '10px' }}>元</span>
                        </div>
                    }
                }
            ],
            dataSource: [],
            selectedRowKeys: []
        };
    },
    componentWillMount () {
        this.state.checked01 = this.props.business.checked01;
        this.state.checked02 = this.props.business.checked02;
        this.state.checked03 = this.props.business.checked03;
        this.state.checked04 = this.props.business.checked04;
        this.state.checked05 = this.props.business.checked05;
        this.state.checked06 = this.props.business.checked06;
        this.state.checked07 = this.props.business.checked07;
        this.state.checked08 = this.props.business.checked08;
        for (let item in this.props.cost) {
            this.state.dataSource.push({
                key: this.state.dataSource.length,
                time: item,
                money: this.props.cost[item]
            })
        }
    },
    remove () {
        this.state.selectedRowKeys.sort((a, b) => { return b - a });
        let theArr = this.state.dataSource.concat();
        for (let idx = 0; idx < this.state.selectedRowKeys.length; idx++) {
            let dataIndex = this.state.selectedRowKeys[idx];
            theArr.map((item, index) => {
                if (item.key === dataIndex) {
                    theArr.splice(index, 1);
                }
            })
        };
        this.state.dataSource = [];
        for (let i = 0; i < theArr.length; i++) {
            let item = theArr[i];
            this.state.dataSource.push({
                key: i,
                time: item.time,
                money: item.money
            })
        };
        this.setState({
            dataSource: this.state.dataSource,
            selectedRowKeys: []
        });
    },
    addNew () {
        this.state.dataSource.push({
            key: this.state.dataSource.length,
            time: '',
            money: ''
        });
        this.setState({
            dataSource: this.state.dataSource
        })
    },
    submit () {
        this.setState({ loading: true });
        let theCost = {};
        if (this.state.dataSource.length) {
            for (let i = 0; i < this.state.dataSource.length; i++) {
                let theMoney = this.state.dataSource[i].money;
                let theTime = this.state.dataSource[i].time;
                theCost[theTime] = theMoney;
            }
        };
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/member/addBusinessAndCost",
            data: {
                id: this.props.rid,
                business: JSON.stringify({
                    "1008": this.state.checked08 ? "1" : "0",
                    "1007": this.state.checked07 ? "1" : "0",
                    "1006": this.state.checked06 ? "1" : "0",
                    "1005": this.state.checked05 ? "1" : "0",
                    "1004": this.state.checked04 ? "1" : "0",
                    "1003": this.state.checked03 ? "1" : "0",
                    "1002": this.state.checked02 ? "1" : "0",
                    "1001": this.state.checked01 ? "1" : "0",
                }),
                cost: JSON.stringify(theCost)
            },
            success: function (data) {
                if (data.error && data.error.length) {
                    message.warning(data.error[0].message);
                } else {
                    message.success("保存成功！");
                    this.state.visible = false
                }
                this.setState({
                    loading: false
                })
            }.bind(this),
        });
    },
    render () {
        const rowSelection = {
            type: 'checkbox',
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRows: selectedRows,
                    selectedRowKeys: selectedRowKeys
                });
            }
        };
        const hasSelected = this.state.selectedRowKeys.length > 0;
        return (
            <Spin spinning={this.state.loading}>
                <div className="level-tabs">
                    <div className="level-tabs-title">
                        <span>会员等级费用设置</span>
                        <Button style={{ background: "#ea0862", border: "none", color: "#fff" }}
                            onClick={this.addNew}>添加<Icon type="plus" /></Button>
                        <Button style={{ background: "#3fcf9e", border: "none", color: "#fff" }}
                            disabled={!hasSelected}
                            onClick={this.remove}>删除<Icon type="minus" /></Button>
                    </div>
                    <Table className="level-tabs-table no-all-select"
                        columns={this.state.columns}
                        dataSource={this.state.dataSource}
                        pagination={false}
                        rowSelection={rowSelection} />
                    <div className="level-tabs-title">
                        <span>会员等级增值服务设置</span>
                    </div>
                    <div>
                        <div className="level-checkbox">
                            <Checkbox checked={this.state.checked01}
                                onChange={(e) => { this.setState({ checked01: e.target.checked }) }}>
                                科技成果，专家信息定点推送
                        </Checkbox>
                        </div>
                        <div className="level-checkbox">
                            <Checkbox checked={this.state.checked02}
                                onChange={(e) => { this.setState({ checked02: e.target.checked }) }}>
                                查看专家的联系方式
                        </Checkbox>
                        </div>
                        <div className="level-checkbox">
                            <Checkbox checked={this.state.checked03}
                                onChange={(e) => { this.setState({ checked03: e.target.checked }) }}>
                                任何业务申请，付费业享受会员专属折扣
                        </Checkbox>
                        </div>
                        <div className="level-checkbox">
                            <Checkbox checked={this.state.checked04}
                                onChange={(e) => { this.setState({ checked04: e.target.checked }) }}>
                                一对一的技术经纪人服务，进行技术成果媒合服务
                        </Checkbox>
                        </div>
                        <div className="level-checkbox">
                            <Checkbox checked={this.state.checked05}
                                onChange={(e) => { this.setState({ checked05: e.target.checked }) }}>
                                一对一的科技咨询师服务
                        </Checkbox>
                        </div>
                        <div className="level-checkbox">
                            <Checkbox checked={this.state.checked06}
                                onChange={(e) => { this.setState({ checked06: e.target.checked }) }}>
                                一对一的专业技术顾问，搜集技术情报，提供研发高参
                        </Checkbox>
                        </div>
                        <div className="level-checkbox">
                            <Checkbox checked={this.state.checked07}
                                onChange={(e) => { this.setState({ checked07: e.target.checked }) }}>
                                免费参加现场业务培训会
                        </Checkbox>
                        </div>
                        <div className="level-checkbox">
                            <Checkbox checked={this.state.checked08}
                                onChange={(e) => { this.setState({ checked08: e.target.checked }) }}>
                                免前期费用做科技类扶持资金项目申报
                        </Checkbox>
                        </div>
                    </div>
                    <div className="level-tabs-save">
                        <Button type="primary" onClick={this.submit}>保存</Button>
                        <ListDelete rid={this.props.rid} refreshForDel={this.props.refreshForDel} />
                    </div>
                </div>
            </Spin>
        );
    }
});


const LevelSet = React.createClass({
    loadData (pageNo) {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/member/selectMemberGrade",
            data: {
            },
            success: function (data) {
                let theArr = [];
                if (data.error && data.error.length) {
                    message.warning(data.error[0].message);
                } else {
                    for (let i = 0; i < data.data.length; i++) {
                        let item = data.data[i];
                        let theBusiness = {};
                        theBusiness['checked01'] = (item.business && item.business['1001'] == 1 ? true : false);
                        theBusiness['checked02'] = (item.business && item.business['1002'] == 1 ? true : false);
                        theBusiness['checked03'] = (item.business && item.business['1003'] == 1 ? true : false);
                        theBusiness['checked04'] = (item.business && item.business['1004'] == 1 ? true : false);
                        theBusiness['checked05'] = (item.business && item.business['1005'] == 1 ? true : false);
                        theBusiness['checked06'] = (item.business && item.business['1006'] == 1 ? true : false);
                        theBusiness['checked07'] = (item.business && item.business['1007'] == 1 ? true : false);
                        theBusiness['checked08'] = (item.business && item.business['1008'] == 1 ? true : false);
                        theArr.push(
                            <Tabs.TabPane tab={item.gradeName + '( Lv.' + item.memberRank + ' )'} key={item.memberRank}>
                                <SetContent business={theBusiness} cost={item.cost || []} rid={item.id} refreshForDel={this.refreshForDel} />
                            </Tabs.TabPane>
                        )
                    };
                    this.setState({ tabPane: theArr })
                }
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getInitialState () {
        return {
            tabPane: [],
            activeKey: '1',
            loading: false
        };
    },
    componentWillMount () {
        this.loadData();
    },
    refresh (e) {
        this.state.activeKey = e;
        this.loadData()
    },
    refreshForDel () {
        this.state.activeKey = '1';
        this.loadData();
    },
    tabChange (e) {
        this.setState({ activeKey: e });
    },
    render () {
        return (
            <div className="user-content" >
                <div className="content-title clearfix">
                    <span>会员等级管理</span>
                    <ListAdd refresh={this.refresh} />
                </div>
                <div>
                    <Tabs activeKey={this.state.activeKey} onChange={this.tabChange}>
                        {this.state.tabPane}
                    </Tabs>
                </div>
            </div >
        );
    }
});

export default LevelSet;