import React from 'react';
import { Icon, InputNumber, Form, Button, Input, Radio, Select, Spin, Table, message, Cascader, Modal } from 'antd';
import { cognizanceStateList } from '../../dataDic.js';
import { techFieldList } from '../../DicTechFieldList.js';
import { getTime, getCognizanceState } from '../../tools.js';
import ajax from 'jquery/src/ajax/xhr.js';
import $ from 'jquery/src/ajax';
import moment from 'moment';
import './cognizance.less';

const CognizanceDescFrom = Form.create()(React.createClass({
    loadData(theCid, theYear) {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/user/cognizance/cognizanceDetail",
            data: {
                cid: theCid || this.props.data.cid,
                year: theYear || this.props.data.year
            },
            success: function (data) {
                if (data.error.length || !data.data) {
                    message.warning(data.error[0].message);
                    return;
                };
                this.state.data = data.data;
                this.state.cid = this.props.data.cid;
                this.state.year = this.props.data.year;
                this.state.moneyTable = [{
                    key: 1,
                    year: '前一年',
                    netAsset: data.data.netAsset1,
                    salesRevenue: data.data.salesRevenue1,
                    grossProfit: data.data.grossProfit1
                }, {
                    key: 2,
                    year: '前二年',
                    netAsset: data.data.netAsset2,
                    salesRevenue: data.data.salesRevenue2,
                    grossProfit: data.data.grossProfit2
                }, {
                    key: 3,
                    year: '前三年',
                    netAsset: data.data.netAsset3,
                    salesRevenue: data.data.salesRevenue3,
                    grossProfit: data.data.grossProfit3
                }];
                if (data.data.netAsset2 == 0) {
                    this.state.netAssetRate = 0;
                } else if (data.data.netAsset3 == 0) {
                    this.state.netAssetRate = (data.data.netAsset1 / data.data.netAsset2) - 1;
                } else {
                    this.state.netAssetRate = 1 / 2 * (data.data.netAsset2 / data.data.netAsset3 + data.data.netAsset1 / data.data.netAsset2) - 1;
                };
                if (this.state.netAssetRate < 0 || isNaN(this.state.netAssetRate)) {
                    this.state.netAssetRate = 0
                };
                if (data.data.salesRevenue2 == 0) {
                    this.state.salesRevenueRate = 0;
                } else if (data.data.salesRevenue3 == 0) {
                    this.state.salesRevenueRate = (data.data.salesRevenue1 / data.data.salesRevenue2) - 1;
                } else {
                    this.state.salesRevenueRate = 1 / 2 * (data.data.salesRevenue2 / data.data.salesRevenue3 + data.data.salesRevenue1 / data.data.salesRevenue2) - 1;
                };
                if (this.state.salesRevenueRate < 0 || isNaN(this.state.salesRevenueRate)) {
                    this.state.salesRevenueRate = 0
                };
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getStateData(theCid) {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/user/cognizance/cognizanceLog",
            data: {
                cid: theCid || this.props.data.cid
            },
            success: function (data) {
                if (data.error.length || !data.data) {
                    message.warning(data.error[0].message);
                    return;
                };
                this.state.stateTable = [];
                for (let i = 0; i < data.data.length; i++) {
                    this.state.stateTable.push({
                        key: i,
                        recordTimeFormattedDate: data.data[i].recordTimeFormattedDate,
                        state: String(data.data[i].state),
                        principal: data.data[i].principal,
                        operator: data.data[i].operator,
                        comment: data.data[i].comment
                    });
                };
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getInitialState() {
        return {
            loading: false,
            stateOption: [],
            moneyColumns: [{
                title: '',
                dataIndex: 'year',
                key: 'year',
            }, {
                title: '净资产',
                dataIndex: 'netAsset',
                key: 'netAsset',
            }, {
                title: '销售收入',
                dataIndex: 'salesRevenue',
                key: 'salesRevenue',
            }, {
                title: '利润总额',
                dataIndex: 'grossProfit',
                key: 'grossProfit',
            }],
            stateColumns: [{
                title: '状态',
                dataIndex: 'state',
                key: 'state',
                render: (text) => { return getCognizanceState(text) }
            }, {
                title: '处理时间',
                dataIndex: 'recordTimeFormattedDate',
                key: 'recordTimeFormattedDate',
            }, {
                title: '负责人',
                dataIndex: 'principal',
                key: 'principal',
            }, {
                title: '操作人',
                dataIndex: 'operator',
                key: 'operator',
            }, {
                title: '备注',
                dataIndex: 'comment',
                key: 'comment',
            }]
        };
    },
    componentWillMount() {
        let _me = this;
        cognizanceStateList.map(function (item) {
            _me.state.stateOption.push(
                <Select.Option value={item.value} key={item.key}>{item.key}</Select.Option>
            )
        });
        this.loadData();
        this.getStateData();
    },
    handleSubmit(e) {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.props.spinState(true);
                $.ajax({
                    method: "POST",
                    dataType: "json",
                    crossDomain: false,
                    url: globalConfig.context + "/api/user/cognizance/disposeCognizanceDetail",
                    data: {
                        id: this.props.data.cid,
                        technicalField1: values.technicalField[0],
                        technicalField2: values.technicalField[1],
                        technicalField3: values.technicalField[2],
                        basicResearchCost: values.basicResearchCost,
                        accident: values.accident
                    }
                }).done(function (data) {
                    if (!data.error.length) {
                        message.success('保存成功！');
                        this.props.clickOk();
                        this.props.form.resetFields();
                        this.state.targetKeys = [];
                        this.state.selectedKeys = [];
                        this.props.spinState(false);
                    } else {
                        message.warning(data.error[0].message);
                        this.props.spinState(false);
                    }
                }.bind(this));
            }
        });
    },
    componentWillReceiveProps(nextProps) {
        if (!this.props.visible && nextProps.visible) {
            this.getStateData(nextProps.data.cid);
            this.loadData(nextProps.data.cid, nextProps.data.year);
        };
    },
    render() {
        const FormItem = Form.Item;
        const { getFieldDecorator } = this.props.form;
        const theData = this.state.data || {};
        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 12 },
        };
        const _me = this;
        return (
            <Form onSubmit={this.handleSubmit} id="highTechApply-form">
                <div className="clearfix">
                    <div className="half-item">
                        <span className="item-title">公司名称: </span>
                        <span>{theData.unitName}</span>
                    </div>
                    <div className="half-item">
                        <span className="item-title">公司组织机构代码: </span>
                        <span>{theData.orgCode}</span>
                    </div>
                    <div className="half-item">
                        <span className="item-title">公司地址: </span>
                        <span>{theData.postalAddress}</span>
                    </div>
                    <div className="half-item">
                        <span className="item-title">申请年份: </span>
                        <span>{this.state.year}</span>
                    </div>
                    <FormItem className="half-item"
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 14 }}
                    >
                        {getFieldDecorator('contacts', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.contacts
                        })(
                            <Select placeholder='选择一个联系人'>{this.props.contactsOption}</Select>
                            )}
                    </FormItem>
                </div>
                <FormItem style={{ width: '50%' }}
                    labelCol={{ span: 0 }}
                    wrapperCol={{ span: 24 }}
                    label="技术领域"
                >
                    <span className="item-title">技术领域: </span>
                    {getFieldDecorator('technicalField', {
                        rules: [{ type: 'array', required: true, message: '此项为必填项!' }],
                        initialValue: [theData.technicalField1, theData.technicalField2, theData.technicalField3]
                    })(
                        <Cascader options={techFieldList} placeholder="请选择技术领域" />
                        )}
                </FormItem>
                <div className="clearfix">
                    <div>
                        <span className="form-title">获得知识产权数量(件): </span>
                    </div>
                    <div className="half-item">
                        <span className="item-title">一类: </span>
                        <span>{theData.firstCatagory}</span>
                    </div>
                    <div className="half-item">
                        <span className="item-title">二类: </span>
                        <span>{theData.secondCatagory}</span>
                    </div>
                </div>
                <div className="clearfix">
                    <div>
                        <span className="form-title">人力资源状况(人): </span>
                    </div>
                    <div className="half-item">
                        <span className="item-title">职工总数: </span>
                        <span>{theData.firmTotal}</span>
                    </div>
                    <div className="half-item">
                        <span className="item-title">科技人员数: </span>
                        <span>{theData.techTotal}</span>
                    </div>
                </div>
                <div className="form-title">近三年经营状况(万元): </div>
                <Table pagination={false} dataSource={this.state.moneyTable} columns={this.state.moneyColumns} />
                <div className="clearfix">
                    <div className="half-item">
                        <span className="item-title">净资产增长率: </span>
                        <span>{isNaN(this.state.netAssetRate) || this.state.netAssetRate == Infinity ? '数据错误无法计算' : (this.state.netAssetRate * 100).toFixed(2) + '%'}</span>
                    </div>
                    <div className="half-item">
                        <span className="item-title">销售收入增长率: </span>
                        <span>{isNaN(this.state.salesRevenueRate) || this.state.salesRevenueRate == Infinity ? '数据错误无法计算' : (this.state.salesRevenueRate * 100).toFixed(2) + '%'}</span>
                    </div>
                </div>
                <div className="clearfix">
                    <div><span className="form-title">近三年研究开发费用总额(万元): </span></div>
                    <div className="third-item">
                        <div className="item-title">近三年研究开发费用总额</div>
                        <p>{theData.researchCost}</p>
                    </div>
                    <div className="third-item">
                        <div className="item-title">其中: 在中国境内研发费用总和</div>
                        <p>{theData.territory}</p>
                    </div>
                    <div className="third-item">
                        <div className="item-title">其中: 基础研究投入费用总额</div>
                        <div>
                            <FormItem
                                labelCol={{ span: 0 }}
                                wrapperCol={{ span: 24 }}
                            >
                                {getFieldDecorator('basicResearchCost', {
                                    rules: [{ type: 'number', required: true, message: '此项为必填项!' }],
                                    initialValue: theData.basicResearchCost
                                })(
                                    <InputNumber min={0} max={999999} step={0.01} />
                                    )}
                                <span>万元</span>
                            </FormItem>
                        </div>
                    </div>
                </div>
                <div>
                    <span className="item-title">近一年企业总收入(万元): </span>
                    <span>{theData.totalRevenue}</span>
                </div>
                <div>
                    <span className="item-title">近一年高新技术产品收入(万元): </span>
                    <span>{theData.lastYearRevenue}</span>
                </div>
                <div className="item-title">申请认定前一年内是否发生过重大安全、重大质量或严重环境违法行为</div>
                <FormItem
                    labelCol={{ span: 0 }}
                    wrapperCol={{ span: 24 }}
                >
                    {getFieldDecorator('accident', {
                        rules: [{ type: 'number', required: true, message: '此项为必填项!' }],
                        initialValue: theData.accident
                    })(
                        <Radio.Group>
                            <Radio value={0}>否</Radio>
                            <Radio value={1}>是</Radio>
                        </Radio.Group>
                        )}
                </FormItem>
                <div className="form-title">状态流转记录: </div>
                <Table pagination={false} dataSource={this.state.stateTable} columns={this.state.stateColumns} />
                <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 CognizanceDesc = 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='1000px'
                    footer='' >
                    <Spin spinning={this.state.loading} className='spin-box'>
                        <CognizanceDescFrom
                            visible={this.state.visible}
                            contactsOption={this.props.contactsOption}
                            data={this.props.data}
                            spinState={this.spinChange}
                            closeModal={this.handleCancel}
                            clickOk={this.handleOk} />
                    </Spin>
                </Modal>
            </div>
        );
    }
});

const CognizanceAdd = React.createClass({
    getInitialState() {
        return {
            visible: false,
            loading: false,
            yearOption: []
        };
    },
    componentWillReceiveProps(nextProps) {
        this.state.visible = nextProps.showAdd
    },
    componentWillMount() {
        let d = new Date();
        let _me = this;
        d = d.getFullYear() - 1;
        this.state.thisYear = d;
        for (let i = d; i < d + 20; i++) {
            _me.state.yearOption.push(
                <Select.Option key={i.toString()} >{i}</Select.Option>
            )
        };
    },
    showModal() {
        this.setState({
            visible: true,
        });
    },
    handleOk() {
        this.setState({
            loading: true
        });
        if (!this.state.year) {
            message.warning('请选择年份！');
            this.setState({
                loading: false
            });
            return;
        };
        if (!this.state.contacts) {
            message.warning('请选择一个联系人！');
            this.setState({
                loading: false
            });
            return;
        };
        $.ajax({
            method: "POST",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/user/cognizance/applyCognizance",
            data: {
                year: this.state.year,
                contacts: this.state.contacts,
                comment: this.state.comment
            }
        }).done(function (data) {
            if (!data.error.length) {
                message.success('保存成功！');
                this.setState({
                    visible: false
                });
                this.props.closeAdd(false, true);
            } else {
                message.warning(data.error[0].message);
                this.setState({
                    loading: false
                });
            }
        }.bind(this));
    },
    handleCancel(e) {
        this.setState({
            visible: false,
        });
        this.props.closeAdd(false);
    },
    spinChange(e) {
        this.setState({
            loading: e
        });
    },
    render() {
        return (
            <div className="cognizance-add">
                <Modal maskClosable={false} title="高企申请" visible={this.state.visible}
                    onOk={this.handleOk} onCancel={this.handleCancel}
                    width='800px'
                    footer={[
                        <Button key="submit" type="primary" loading={this.state.loading} onClick={this.handleOk}>
                            提交
                            </Button>,
                        <Button key="back" onClick={this.handleCancel}>
                            返回
                            </Button>,
                    ]}
                >
                    <Spin spinning={this.state.loading} className='spin-box'>
                        <div className="clearfix">
                            <div className="half-item">
                                <span>选择申请年份: </span>
                                <Select placeholder="请选择年份" style={{ width: 200 }}
                                    onSelect={(e, n) => { this.state.year = e }}>
                                    {this.state.yearOption}
                                </Select>
                            </div>
                            <div className="half-item">
                                <span>选择联系人: </span>
                                <Select placeholder="请选择联系人" style={{ width: 200 }}
                                    onSelect={(e, n) => { this.state.contacts = e }}>
                                    {this.props.contactsOption}
                                </Select>
                            </div>
                        </div>
                        <div>
                            <p>备注: </p>
                            <p>
                                <Input type="textarea" rows={6} onChange={(e) => { this.state.comment = e.target.value; }} />
                            </p>
                        </div>
                    </Spin>
                </Modal>
            </div>
        );
    }
});

const Cognizance = React.createClass({
    loadData(pageNo) {
        this.state.data = [];
        this.setState({
            loading: true
        });
        $.when($.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/user/cognizance/getContacts"
        }), $.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/user/cognizance/listCognizance",
            data: {
                pageNo: pageNo || 1,
                pageSize: this.state.pagination.pageSize
            }
        })).done((data1, data2) => {
            this.state.data = [];
            if (data1[0].error || !data1[0].data) {
                if (data1[0].error.length) {
                    message.warning(data1[0].error[0].message);
                    return;
                };
            };
            if (data2[0].error || !data2[0].data || !data2[0].data.list) {
                if (data2[0].error.length) {
                    message.warning(data2[0].error[0].message);
                    this.state.ButtonDisabled = true;
                    return;
                };
            };
            let _me = this;
            for (let item in data1[0].data) {
                let theData = data1[0].data[item];
                _me.state.contactsOption.push(
                    <Select.Option value={item} key={theData}>{theData}</Select.Option>
                );
            };
            for (let i = 0; i < data2[0].data.list.length; i++) {
                let thisdata = data2[0].data.list[i];
                this.state.data.push({
                    key: i,
                    uid: thisdata.uid,
                    cid: thisdata.cid,
                    year: thisdata.year,
                    serialNumber: thisdata.serialNumber,
                    locationProvince: thisdata.locationProvince,
                    unitName: thisdata.unitName,
                    contacts: [thisdata.contacts, {
                        '1': thisdata.firstContacts,
                        '2': thisdata.secondContacts,
                        '3': thisdata.thirdContacts
                    }],
                    createTime: thisdata.createTime,
                    comment: thisdata.comment,
                    state: thisdata.state,
                    certificateNumber: thisdata.certificateNumber,
                    issuingDate: thisdata.issuingDate,
                    consultant: thisdata.consultant,
                    createTimeFormattedDate: thisdata.createTimeFormattedDate,
                    issuingDateFormattedDate: thisdata.issuingDateFormattedDate
                });
            };
            this.state.pagination.current = data2[0].data.pageNo;
            this.state.pagination.total = data2[0].data.totalCount;
            this.setState({
                dataSource: this.state.data,
                pagination: this.state.pagination
            });
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getInitialState() {
        return {
            contactsOption: [],
            selectedRowKeys: [],
            selectedRows: [],
            loading: false,
            showAdd: false,
            showDesc: 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: 'serialNumber',
                    key: 'serialNumber'
                }, {
                    title: '年份',
                    dataIndex: 'year',
                    key: 'year'
                }, {
                    title: '联系人',
                    dataIndex: 'contacts',
                    key: 'contacts',
                    render: (text) => {
                        for (let item in text[1]) {
                            if (text[0] == item) {
                                return text[1][item];
                            };
                        };
                    }
                }, {
                    title: '派单日',
                    dataIndex: 'createTimeFormattedDate',
                    key: 'createTimeFormattedDate'
                }, {
                    title: '状态',
                    dataIndex: 'state',
                    key: 'state',
                    render: (text) => { return getCognizanceState(text) }
                }, {
                    title: '证书编号',
                    dataIndex: 'certificateNumber',
                    key: 'certificateNumber'
                }, {
                    title: '发证日',
                    dataIndex: 'issuingDateFormattedDate',
                    key: 'issuingDateFormattedDate'
                }, {
                    title: '到期日',
                    dataIndex: 'issuingDate',
                    key: 'issuingDate',
                    render: (text) => { return getTime(text, 36) }
                }, {
                    title: '负责人',
                    dataIndex: 'consultant',
                    key: 'consultant'
                }
            ],
            dataSource: []
        };
    },
    componentWillMount() {
        this.loadData();
    },
    tableRowClick(record, index) {
        this.state.RowData = record;
        this.setState({
            showDesc: true
        });
    },
    addClick() {
        this.setState({
            showAdd: 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/user/cognizance/deleteTechProduct",
    //         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();
        };
    },
    closeAdd(e, s) {
        this.state.showAdd = 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>
                </div>
                <div className="user-search">
                    <p>
                        <Button style={{ background: "#3fcf9e", border: "none", color: "#fff", display: 'none' }}
                            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>
                <CognizanceDesc
                    data={this.state.RowData}
                    contactsOption={this.state.contactsOption}
                    showDesc={this.state.showDesc}
                    closeDesc={this.closeDesc} />
                <CognizanceAdd
                    contactsOption={this.state.contactsOption}
                    showAdd={this.state.showAdd}
                    closeAdd={this.closeAdd} />
            </div >
        );
    }
});

export default Cognizance;

// <Button style={{ background: "#ea0862", border: "none", color: "#fff", float: "right" }}
//                         disabled={this.state.ButtonDisabled}
//                         onClick={this.addClick}>申请高企认定<Icon type="plus" /></Button>