import React from 'react';
import { Switch, Icon, Form, Button, Input, Spin, Table, message, Select, Modal, InputNumber, Upload } from 'antd';
import './techProduct.less';
import { beforeUploadFile, newDownloadFile, getProportion, saveProportion, getPreview } from '../../../../tools.js';
import ajax from 'jquery/src/ajax/xhr.js';
import $ from 'jquery/src/ajax';

const RatepayDescFrom = Form.create()(React.createClass({
    loadData(uid, year) {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/ratepayDetail",
            data: {
                uid: uid != undefined ? uid : this.props.data.uid,
                year: year != undefined ? year : this.props.data.year
            }
        }).done((data) => {
            if (!data.data) {
                if (data.error && data.error.length) {
                    message.warning(data.error[0].message);
                };
                return;
            };
            this.setState({
                managementCost: data.data.managementCost,
                researchCost: data.data.researchCost,
                grossProfit: data.data.grossProfit,
                operatingProfit: data.data.operatingProfit
            });
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getInitialState() {
        return {
            loading: false,
            yearOption: [],
        };
    },
    componentWillMount() {
        let d = new Date();
        let _me = this;
        d = d.getFullYear();
        for (let i = d; i > d - 20; i--) {
            _me.state.yearOption.push(
                <Select.Option value={i.toString()} key={i}>{i}</Select.Option>
            )
        };
        if (this.props.data.uid) {
            this.loadData();
        };
    },
    handleSubmit(e) {
        e.preventDefault();
        if (!this.state.year && !this.props.data.year) {
            message.warning("请选择一个年份!")
            return;
        };
        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.props.spinState(true);
                $.ajax({
                    method: "POST",
                    dataType: "json",
                    crossDomain: false,
                    url: globalConfig.context + "/api/admin/disposeRatepay",
                    data: {
                        id: this.props.data.id,
                        uid: this.props.uid,
                        operatingIncome: values.operatingIncome,
                        managementCost: values.managementCost,
                        operatingProfit: values.operatingProfit,
                        nonOperatingIncome: values.nonOperatingIncome,
                        nonTaxableIncome: values.nonTaxableIncome,
                        taxExemptIncome: values.taxExemptIncome,
                        subsidyIncome: values.subsidyIncome,
                        grossProfit: values.grossProfit,
                        researchCost: values.researchCost,
                        year: this.state.year || this.props.data.year,
                        taxReturnUrl: this.state.taxReturnUrl
                    }
                }).done(function (data) {
                    if (!data.error.length) {
                        message.success('保存成功!');
                        this.props.clickOk();
                        this.props.spinState(false);
                        this.props.form.resetFields();
                    } else {
                        message.warning(data.error[0].message);
                        this.props.spinState(false);
                    }
                }.bind(this));
            }
        });
    },
    componentWillReceiveProps(nextProps) {
        if (!this.props.visible && nextProps.visible) {
            if (nextProps.data.uid) {
                this.loadData(nextProps.data.uid, nextProps.data.year);
            };
            this.props.form.resetFields();
            this.state.fileList = [];
            this.state.managementCost = undefined;
            this.state.researchCost = undefined;
            this.state.grossProfit = undefined;
            this.state.operatingProfit = undefined;
            this.state.taxReturnUrl = undefined;
        };
    },
    render() {
        const FormItem = Form.Item;
        const { getFieldDecorator } = this.props.form;
        const theData = this.props.data;
        const formItemLayout = {
            labelCol: { span: 8 },
            wrapperCol: { span: 16 },
        };
        const _me = this;
        return (
            <Form onSubmit={this.handleSubmit} className="activityCost-form">
                <div className="activityCost-title"><span>年份: </span>
                    {
                        theData.year ? <span>{theData.year}</span> :
                            <Select placeholder="请选择年份" style={{ width: 200 }}
                                onSelect={(e, n) => { this.state.year = e }}>
                                {this.state.yearOption}
                            </Select>
                    }
                </div>
                <div className="clearfix">
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="营业收入(万元)"
                    >
                        {getFieldDecorator('operatingIncome', {
                            rules: [{ type: 'number', required: true, message: '此项为必填项!' }],
                            initialValue: theData.operatingIncome
                        })(
                            <InputNumber min={0} max={999999} step={0.01} />
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="管理费用(万元)"
                    >
                        {getFieldDecorator('managementCost', {
                            rules: [{ type: 'number', required: true, message: '此项为必填项!' }],
                            initialValue: theData.managementCost
                        })(
                            <InputNumber min={0} max={999999} step={0.01} />
                            )}
                        {this.state.managementCost && this.state.managementCost != this.props.form.getFieldValue('managementCost') ? <span style={{ color: '#f50' }}>与财务报表不一致!</span> : <span></span>}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="营业利润(万元)"
                    >
                        {getFieldDecorator('operatingProfit', {
                            rules: [{ type: 'number', required: true, message: '此项为必填项!' }],
                            initialValue: theData.operatingProfit
                        })(
                            <InputNumber min={0} max={999999} step={0.01} />
                            )}
                        {this.state.operatingProfit && this.state.operatingProfit != this.props.form.getFieldValue('operatingProfit') ? <span style={{ color: '#f50' }}>与财务报表不一致!</span> : <span></span>}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="营业外收入(万元)"
                    >
                        {getFieldDecorator('nonOperatingIncome', {
                            rules: [{ type: 'number', required: true, message: '此项为必填项!' }],
                            initialValue: theData.nonOperatingIncome
                        })(
                            <InputNumber min={0} max={999999} step={0.01} />
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="不征税收入(万元)"
                    >
                        {getFieldDecorator('nonTaxableIncome', {
                            rules: [{ type: 'number', required: true, message: '此项为必填项!' }],
                            initialValue: theData.nonTaxableIncome
                        })(
                            <InputNumber min={0} max={999999} step={0.01} />
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="免税收入(万元)"
                    >
                        {getFieldDecorator('taxExemptIncome', {
                            rules: [{ type: 'number', required: true, message: '此项为必填项!' }],
                            initialValue: theData.taxExemptIncome
                        })(
                            <InputNumber min={0} max={999999} step={0.01} />
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="政府补助收入(万元)"
                    >
                        {getFieldDecorator('subsidyIncome', {
                            rules: [{ type: 'number', required: true, message: '此项为必填项!' }],
                            initialValue: theData.subsidyIncome
                        })(
                            <InputNumber min={0} max={999999} step={0.01} />
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="利润总额(万元)"
                    >
                        {getFieldDecorator('grossProfit', {
                            rules: [{ type: 'number', required: true, message: '此项为必填项!' }],
                            initialValue: theData.grossProfit
                        })(
                            <InputNumber min={0} max={999999} step={0.01} />
                            )}
                        {this.state.grossProfit && this.state.grossProfit != this.props.form.getFieldValue('grossProfit') ? <span style={{ color: '#f50' }}>与财务报表不一致!</span> : <span></span>}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="研发费用(万元)"
                    >
                        {getFieldDecorator('researchCost', {
                            rules: [{ type: 'number', required: true, message: '此项为必填项!' }],
                            initialValue: theData.researchCost
                        })(
                            <InputNumber min={0} max={999999} step={0.01} />
                            )}
                        {this.state.researchCost && this.state.researchCost != this.props.form.getFieldValue('researchCost') ? <span style={{ color: '#f50' }}>与财务报表不一致!</span> : <span></span>}
                    </FormItem>
                </div>
                <div className="hrSituation-roster">
                    <Upload
                        name="ratepay"
                        action={globalConfig.context + "/api/admin/uploadRatepay"}
                        data={{ 'sign': 'ratepay', 'year': (this.state.year || theData.year), 'uid': this.props.uid }}
                        beforeUpload={beforeUploadFile}
                        fileList={this.state.fileList}
                        onChange={(info) => {
                            if (info.file.status !== 'uploading') {
                                console.log(info.file, info.fileList);
                            }
                            if (info.file.status === 'done') {
                                if (!info.file.response.error.length) {
                                    message.success(`${info.file.name} 文件上传成功!`);
                                } else {
                                    message.warning(info.file.response.error[0].message);
                                    return;
                                };
                                this.state.taxReturnUrl = info.file.response.data;
                            } else if (info.file.status === 'error') {
                                message.error(`${info.file.name} 文件上传失败。`);
                            };
                            this.setState({ fileList: info.fileList.slice(-1) });
                        }}
                    >
                        <Button><Icon type="upload" /> 上传企业所得税纳税申报表 </Button>
                    </Upload>
                    <p style={{ marginTop: '10px' }}>{theData.taxReturnUrl ?
                        <span className="download-file">
                            <a onClick={newDownloadFile.bind(null, this.props.data.id, 'ratepay', '/api/admin/downloadRatepay')}>{theData.taxReturnDownloadFileName}</a>
                            <a onClick={() => {
                                var newTab = window.open('about:blank'); getPreview(theData.id, 'ratepay', 'ratepay', function (data) { newTab.location.href = data; });
                            }}><Icon style={{ fontSize: '16px' }} type="eye-o" /></a>
                        </span>
                        : <span><Icon type="exclamation-circle" style={{ color: '#ffbf00', marginRight: '6px' }} />未上传!</span>}</p>
                </div>
                <FormItem style={{ marginTop: '20px' }}>
                    <Button className="set-submit" type="primary" htmlType="submit">保存</Button>
                    <Button type="ghost" style={{ marginLeft: '20px' }} onClick={this.props.closeModal}>取消</Button>
                </FormItem>
            </Form >
        );
    },
}));

const RatepayDesc = React.createClass({
    getInitialState() {
        return {
            visible: false,
            loading: false
        };
    },
    componentWillReceiveProps(nextProps) {
        this.state.visible = nextProps.showDesc
    },
    showModal() {
        this.setState({
            visible: true,
        });
    },
    handleOk() {
        this.setState({
            visible: false,
        });
        this.props.closeDesc(false, true);
    },
    handleCancel(e) {
        this.setState({
            visible: false,
        });
        this.props.closeDesc(false);
    },
    spinChange(e) {
        this.setState({
            loading: e
        });
    },
    render() {
        return (
            <div className="patent-addNew">
                <Modal maskClosable={false} title="企业所得税纳税申报信息" visible={this.state.visible}
                    onOk={this.handleOk} onCancel={this.handleCancel}
                    width='800px'
                    footer='' >
                    <Spin spinning={this.state.loading} className='spin-box'>
                        <RatepayDescFrom
                            uid={this.props.uid}
                            data={this.props.data}
                            visible={this.state.visible}
                            spinState={this.spinChange} closeModal={this.handleCancel} clickOk={this.handleOk} />
                    </Spin>
                </Modal>
            </div>
        );
    },
});

const Ratepay = React.createClass({
    loadData(pageNo) {
        this.state.data = [];
        this.setState({
            loading: true
        });
        $.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/ratepay",
            data: {
                pageNo: pageNo || 1,
                pageSize: this.state.pagination.pageSize,
                uid: this.props.data.uid
            }
        }).done((data) => {
            if (data.error.length || !data.data || !data.data.list) {
                message.warning(data.error[0].message);
                return;
            };
            for (let i = 0; i < data.data.list.length; i++) {
                let thisdata = data.data.list[i];
                this.state.data.push({
                    key: i,
                    id: thisdata.id,
                    uid: thisdata.uid,
                    operatingIncome: thisdata.operatingIncome,
                    managementCost: thisdata.managementCost,
                    operatingProfit: thisdata.operatingProfit,
                    nonOperatingIncome: thisdata.nonOperatingIncome,
                    nonTaxableIncome: thisdata.nonTaxableIncome,
                    taxExemptIncome: thisdata.taxExemptIncome,
                    subsidyIncome: thisdata.subsidyIncome,
                    researchCost: thisdata.researchCost,
                    grossProfit: thisdata.grossProfit,
                    year: thisdata.year,
                    taxReturnUrl: thisdata.taxReturnUrl,
                    taxReturnDownloadFileName: thisdata.taxReturnDownloadFileName,
                    taxReturn: [thisdata.id, thisdata.taxReturnDownloadFileName]
                });
            };
            this.state.pagination.current = data.data.pageNo;
            this.state.pagination.total = data.data.totalCount;
            this.setState({
                dataSource: this.state.data,
                pagination: this.state.pagination
            });
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
        let _me = this;
        getProportion(this.props.data.uid, function (data) { _me.setState({ proportion: data }); });
    },
    getInitialState() {
        return {
            selectedRowKeys: [],
            selectedRows: [],
            loading: false,
            pagination: {
                defaultCurrent: 1,
                defaultPageSize: 10,
                showQuickJumper: true,
                pageSize: 10,
                onChange: function (page) {
                    this.loadData(page);
                }.bind(this),
                showTotal: function (total) {
                    return '共' + total + '条数据';
                }
            },
            columns: [
                {
                    title: '年份',
                    dataIndex: 'year',
                    key: 'year'
                }, {
                    title: '营业收入(万元)',
                    dataIndex: 'operatingIncome',
                    key: 'operatingIncome'
                }, {
                    title: '管理费用(万元)',
                    dataIndex: 'managementCost',
                    key: 'managementCost'
                }, {
                    title: '营业利润(万元)',
                    dataIndex: 'operatingProfit',
                    key: 'operatingProfit',
                }, {
                    title: '营业外收入(万元)',
                    dataIndex: 'nonOperatingIncome',
                    key: 'nonOperatingIncome',
                }, {
                    title: '相关附件',
                    dataIndex: 'taxReturn',
                    key: 'taxReturn',
                    render: (text) => {
                        return <a onClick={newDownloadFile.bind(null, text[0], 'ratepay', '/api/admin/downloadRatepay')}>{text[1]}</a>
                    }
                }
            ],
            dataSource: []
        };
    },
    componentWillMount() {
        this.loadData();
    },
    tableRowClick(record, index) {
        this.state.RowData = record;
        this.setState({
            showDesc: true
        });
    },
    delectRow() {
        let deletedIds = [];
        for (let idx = 0; idx < this.state.selectedRows.length; idx++) {
            let rowItem = this.state.selectedRows[idx];
            if (rowItem.id) {
                deletedIds.push(rowItem.id)
            }
        }
        this.setState({
            selectedRowKeys: [],
            loading: deletedIds.length > 0
        });
        $.ajax({
            method: "POST",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/deleteRatepay",
            data: {
                ids: deletedIds
            }
        }).done(function (data) {
            if (!data.error.length) {
                message.success('删除成功!');
                this.setState({
                    loading: false,
                });
            } else {
                message.warning(data.error[0].message);
            };
            this.loadData();
        }.bind(this));
    },
    closeDesc(e, s) {
        this.state.showDesc = e;
        if (s) {
            this.loadData();
        };
    },
    search() {
        this.loadData();
    },
    reset() {
        this.loadData();
    },
    render() {
        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRows: selectedRows,
                    selectedRowKeys: selectedRowKeys
                });
            }
        };
        const hasSelected = this.state.selectedRowKeys.length > 0;
        return (
            <div className="user-content" >
                <div className="content-title">
                    <span>企业所得税纳税申信息</span>
                    <span className="proportion"> 是否已完成:</span>
                    <Switch
                        checked={this.state.proportion && this.state.proportion.ratepay == 1 ? true : false}
                        checkedChildren={'已完成'}
                        unCheckedChildren={'未完成'}
                        onChange={(e) => {
                            e ? this.state.proportion.ratepay = 1 : this.state.proportion.ratepay = 0;
                            saveProportion(this.state.proportion.id, this.props.data.uid, 'ratepay', this.state.proportion.ratepay);
                            this.setState({ proportion: this.state.proportion });
                        }} />
                </div>
                <div className="user-search">
                    <p>
                        <Button style={{ background: "#ea0862", border: "none", color: "#fff" }}
                            onClick={this.tableRowClick}>添加<Icon type="plus" /></Button>
                        <Button style={{ background: "#3fcf9e", border: "none", color: "#fff" }}
                            disabled={!hasSelected}
                            onClick={this.delectRow}>删除<Icon type="minus" /></Button>
                    </p>
                </div>
                <div className="patent-table">
                    <Spin spinning={this.state.loading}>
                        <Table columns={this.state.columns}
                            dataSource={this.state.dataSource}
                            pagination={this.state.pagination}
                            rowSelection={rowSelection}
                            onRowClick={this.tableRowClick} />
                    </Spin>
                </div>
                <RatepayDesc
                    uid={this.props.data.uid}
                    data={this.state.RowData}
                    showDesc={this.state.showDesc} closeDesc={this.closeDesc} />
            </div >
        );
    }
});

export default Ratepay;