import React from 'react';
import { Icon, Form, Button, Input, Spin, message, InputNumber, DatePicker, Select, Checkbox, Cascader, Table, Radio } from 'antd';
import './techProduct.less';
import { provinceSelect } from '../../../../tools';
import { industryList, scaleList, companyType } from '../../../../dataDic';
import { techFieldList } from '../../../../DicTechFieldList';
import ajax from 'jquery/src/ajax/xhr.js';
import $ from 'jquery/src/ajax';

const CompanyDetail = Form.create()(React.createClass({
    loadData() {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/user/cognizance/cognizanceDetail",
            data: {
            }
        }).done(function (data) {
            if (!data.data) {
                if (data.error && data.error.length) {
                    message.warning(data.error[0].message);
                };
                return;
            };
        }.bind(this)).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getInitialState() {
        return {
            loading: false,
            industryOption: [],
            scaleOption: [],
            humanTableData: [],
            legalTableData: [],
            humanColumns: [
                {
                    title: '公民类型',
                    dataIndex: 'type',
                    key: 'type',
                    width: '130px',
                    render: (text, record, index) => {
                        return <Select value={record.type} onChange={(e) => { record.type = e; this.setState({ humanTableData: this.state.humanTableData }); }}>
                            <Select.Option value="china">中国公民</Select.Option>
                            <Select.Option value="other">外籍公民</Select.Option>
                        </Select>
                    }
                }, {
                    title: '姓名',
                    dataIndex: 'name',
                    key: 'name',
                    render: (text, record, index) => {
                        return <Input value={record.url} onChange={(e) => { record.name = e.target.value; this.setState({ humanTableData: this.state.humanTableData }); }} />
                    }
                }, {
                    title: '身份证(护照)号',
                    dataIndex: 'IdNumber',
                    key: 'IdNumber',
                    render: (text, record, index) => {
                        return <Input value={record.IdNumber} onChange={(e) => { record.IdNumber = e.target.value; this.setState({ humanTableData: this.state.humanTableData }); }} />
                    }
                }, {
                    title: '投资额（万元）',
                    dataIndex: 'money',
                    key: 'money',
                    render: (text, record, index) => {
                        return <InputNumber value={record.money} onChange={(e) => { record.money = e.target.value; this.setState({ humanTableData: this.state.humanTableData }); }} />
                    }
                }
            ],
            legalColumns: [
                {
                    title: '法人类型',
                    dataIndex: 'type',
                    key: 'type',
                    width: '130px',
                    render: (text, record, index) => {
                        return <Select value={record.type} onChange={(e) => { record.type = e; this.setState({ legalTableData: this.state.legalTableData }); }}>
                            <Select.Option value="china">中国企业法人</Select.Option>
                            <Select.Option value="other">外观企业法人</Select.Option>
                        </Select>
                    }
                }, {
                    title: '名称',
                    dataIndex: 'name',
                    key: 'name',
                    render: (text, record, index) => {
                        return <Input value={record.url} onChange={(e) => { record.name = e.target.value; this.setState({ legalTableData: this.state.legalTableData }); }} />
                    }
                }, {
                    title: '组织机构代码或统一社会信用代码',
                    dataIndex: 'IdNumber',
                    key: 'IdNumber',
                    render: (text, record, index) => {
                        return <Input value={record.IdNumber} onChange={(e) => { record.IdNumber = e.target.value; this.setState({ legalTableData: this.state.legalTableData }); }} />
                    }
                }, {
                    title: '投资额（万元）',
                    dataIndex: 'money',
                    key: 'money',
                    render: (text, record, index) => {
                        return <Input value={record.money} onChange={(e) => { record.money = e.target.value; this.setState({ legalTableData: this.state.legalTableData }); }} />
                    }
                }
            ],
            humanSelectedRowKeys: [],
            humanSelectedRows: [],
            legalSelectedRowKeys: [],
            legalSelectedRows: []
        };
    },
    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/admin/disposeRatepay",
                    data: {
                    }
                }).done(function (data) {
                    if (!data.error.length) {
                        message.success('保存成功！');
                    } else {
                        message.warning(data.error[0].message);
                    }
                }.bind(this));
            }
        });
    },
    componentWillMount() {
        let _me = this;
        industryList.map(function (item) {
            _me.state.industryOption.push(
                <Select.Option value={item.value} key={item.key}>{item.key}</Select.Option>
            )
        });
        scaleList.map(function (item) {
            _me.state.scaleOption.push(
                <Select.Option value={item.value} key={item.key}>{item.key}</Select.Option>
            )
        });
        this.loadData();
    },
    componentWillReceiveProps(nextProps) {
    },
    humanRemove() {
        let deletedIds = [];
        for (let idx = 0; idx < this.state.humanSelectedRows.length; idx++) {
            let rowItem = this.state.humanSelectedRows[idx];
            if (rowItem.id) {
                deletedIds.push(rowItem.id)
            }
        };
        this.setState({
            loading: deletedIds.length > 0
        });
        if (deletedIds.length) {
            $.ajax({
                url: globalConfig.context + '/api/permission/delete',
                method: 'post',
                data: {
                    data: JSON.stringify(deletedIds)
                }
            }).done((res) => {
                if (!res.error.length) {
                    Message.success("删除成功");
                    this.state.humanSelectedRowKeys.sort((a, b) => { return b - a });
                    for (let idx = 0; idx < this.state.humanSelectedRowKeys.length; idx++) {
                        let dataIndex = this.state.humanSelectedRowKeys[idx];
                        this.state.humanTableData.splice(dataIndex, 1);
                    };
                    this.setState({
                        humanTableData: this.state.humanTableData,
                        humanSelectedRowKeys: []
                    });
                } else {
                    Message.error(res.error[0].message);
                }
            }).always(() => {
                this.setState({
                    loading: false
                });
            })
        }
    },
    humanAdd() {
        this.state.humanTableData.push({
            id: null,
            type: null,
            name: '',
            IdNumber: '',
            money: 0
        });
        this.setState({
            humanTableData: this.state.humanTableData
        })
    },
    humanSave() {
        this.setState({
            loading: true
        });
        $.ajax({
            url: globalConfig.context + '/api/permission',
            method: 'post',
            data: {
                data: JSON.stringify(this.state.data)
            }
        }).done((res) => {
            if (!res.error.length) {
                Message.success("保存成功");
                this.loadData();
            } else {
                Message.error(res.error[0].message);
            }
        }).always(() => {
            this.setState({
                loading: false
            });
        })
    },
    legalRemove() {
        let deletedIds = [];
        for (let idx = 0; idx < this.state.legalSelectedRows.length; idx++) {
            let rowItem = this.state.legalSelectedRows[idx];
            if (rowItem.id) {
                deletedIds.push(rowItem.id)
            }
        };
        this.setState({
            loading: deletedIds.length > 0
        });
        if (deletedIds.length) {
            $.ajax({
                url: globalConfig.context + '/api/permission/delete',
                method: 'post',
                data: {
                    data: JSON.stringify(deletedIds)
                }
            }).done((res) => {
                if (!res.error.length) {
                    Message.success("删除成功");
                    this.state.legalSelectedRowKeys.sort((a, b) => { return b - a });
                    for (let idx = 0; idx < this.state.legalSelectedRowKeys.length; idx++) {
                        let dataIndex = this.state.legalSelectedRowKeys[idx];
                        this.state.legalTableData.splice(dataIndex, 1);
                    };
                    this.setState({
                        legalTableData: this.state.legalTableData,
                        legalSelectedRowKeys: []
                    });
                } else {
                    Message.error(res.error[0].message);
                }
            }).always(() => {
                this.setState({
                    loading: false
                });
            })
        }
    },
    legalAdd() {
        this.state.legalTableData.push({
            id: null,
            type: null,
            name: '',
            IdNumber: '',
            money: 0
        });
        this.setState({
            legalTableData: this.state.legalTableData
        })
    },
    legalSave() {
        this.setState({
            loading: true
        });
        $.ajax({
            url: globalConfig.context + '/api/permission',
            method: 'post',
            data: {
                data: JSON.stringify(this.state.data)
            }
        }).done((res) => {
            if (!res.error.length) {
                Message.success("保存成功");
                this.loadData();
            } else {
                Message.error(res.error[0].message);
            }
        }).always(() => {
            this.setState({
                loading: false
            });
        })
    },
    render() {
        const FormItem = Form.Item;
        const { getFieldDecorator } = this.props.form;
        //const theData = this.props.data;
        const theData = {};
        const formItemLayout = {
            labelCol: { span: 8 },
            wrapperCol: { span: 16 },
        };
        const humanRowSelection = {
            type: 'checkbox',
            selectedRowKeys: this.state.humanSelectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    humanSelectedRows: humanSelectedRows,
                    humanSelectedRowKeys: humanSelectedRowKeys
                });
            }
        };
        const humanHasSelected = this.state.humanSelectedRowKeys.length > 0;
        const legalRowSelection = {
            type: 'checkbox',
            selectedRowKeys: this.state.legalSelectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    legalSelectedRows: legalSelectedRows,
                    legalSelectedRowKeys: legalSelectedRowKeys
                });
            }
        };
        const legalHasSelected = this.state.legalSelectedRowKeys.length > 0;
        return (
            <Form onSubmit={this.handleSubmit} className="company-detail-form">
                <div className="content-title">
                    <span>企业基本信息</span>
                </div>
                <div className="clearfix">
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="企业名称"
                    >
                        {getFieldDecorator('operatingProfit', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.operatingProfit
                        })(
                            <Input />
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="行政区域"
                    >
                        {getFieldDecorator('operatingProfit', {
                            rules: [{ type: 'array', required: true, message: '此项为必填项!' }],
                            initialValue: theData.operatingProfit
                        })(
                            <Cascader options={provinceSelect()} />
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="通信地址"
                    >
                        {getFieldDecorator('operatingProfit', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.operatingProfit
                        })(
                            <Input />
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="邮编"
                    >
                        {getFieldDecorator('operatingProfit', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.operatingProfit
                        })(
                            <Input />
                            )}
                    </FormItem>
                </div>
                <div className="clearfix">
                    <p className="content-title">联系人信息</p>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="姓名"
                    >
                        {getFieldDecorator('operatingIncome', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.operatingIncome
                        })(
                            <Input />
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="手机"
                    >
                        {getFieldDecorator('managementCost', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.managementCost
                        })(
                            <Input />
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="电话"
                    >
                        {getFieldDecorator('operatingProfit', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.operatingProfit
                        })(
                            <Input />
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="传真"
                    >
                        {getFieldDecorator('operatingProfit', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.operatingProfit
                        })(
                            <Input />
                            )}
                    </FormItem>
                </div>
                <div className="clearfix">
                    <p className="content-title">企业法人信息</p>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="电话"
                    >
                        {getFieldDecorator('operatingProfit', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.operatingProfit
                        })(
                            <Input />
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="传真"
                    >
                        {getFieldDecorator('operatingProfit', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.operatingProfit
                        })(
                            <Input />
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="E-mail"
                    >
                        {getFieldDecorator('operatingProfit', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.operatingProfit
                        })(
                            <Input />
                            )}
                    </FormItem>
                </div>
                <div className="content-title">
                    <span>企业重要信息</span>
                </div>
                <div className="clearfix">
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="注册资金"
                    >
                        {getFieldDecorator('operatingIncome', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.operatingIncome
                        })(
                            <InputNumber />
                            )}
                        <span>万元</span>
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="注册时间"
                    >
                        {getFieldDecorator('managementCost', {
                            rules: [{ type: 'object', required: true, message: '此项为必填项!' }],
                            initialValue: theData.managementCost
                        })(
                            <DatePicker />
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="法人代表姓名"
                    >
                        {getFieldDecorator('operatingProfit', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.operatingProfit
                        })(
                            <Input />
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="身份证号"
                    >
                        {getFieldDecorator('operatingProfit', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.operatingProfit
                        })(
                            <Input />
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="组织机构代码/统一社会信用代码"
                    >
                        {getFieldDecorator('operatingProfit', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.operatingProfit
                        })(
                            <Input />
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="税务登记号/统一社会信用代码"
                    >
                        {getFieldDecorator('operatingProfit', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.operatingProfit
                        })(
                            <Input />
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="所属行业"
                    >
                        {getFieldDecorator('operatingProfit', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.operatingProfit
                        })(
                            <Select>{this.state.industryOption}</Select>
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="企业规模（注册资金）"
                    >
                        {getFieldDecorator('operatingProfit', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.operatingProfit
                        })(
                            <Select>{this.state.scaleOption}</Select>
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="注册类型"
                    >
                        {getFieldDecorator('operatingProfit', {
                            rules: [{ type: 'array', required: true, message: '此项为必填项!' }],
                            initialValue: theData.operatingProfit
                        })(
                            <Cascader options={companyType} />
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="外资来源地"
                    >
                        {getFieldDecorator('operatingProfit', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.operatingProfit
                        })(
                            <Input />
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="领域"
                    >
                        {getFieldDecorator('operatingProfit', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.operatingProfit
                        })(
                            <Cascader options={techFieldList} />
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="企业所得税主管税务机关"
                    >
                        {getFieldDecorator('operatingProfit', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.operatingProfit
                        })(
                            <Radio.Group>
                                <Radio value="1">国税</Radio>
                                <Radio value="2">地税</Radio>
                            </Radio.Group>
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="企业所得税征收方式"
                    >
                        {getFieldDecorator('operatingProfit', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.operatingProfit
                        })(
                            <Radio.Group>
                                <Radio value="1">查账征收</Radio>
                                <Radio value="2">核定征收</Radio>
                            </Radio.Group>
                            )}
                    </FormItem>
                </div>
                <div className="clearfix">
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="是否上市"
                    >   {getFieldDecorator('listed', {
                        initialValue: this.state.listed || "0"
                    })(
                        <Radio.Group>
                            <Radio value="0">否</Radio>
                            <Radio value="1">是</Radio>
                        </Radio.Group>
                        )}
                    </FormItem>
                </div>
                <div className="clearfix" style={{ display: this.props.form.getFieldValue('listed') == 0 ? 'none' : 'block' }}>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="上市时间"
                    >
                        {getFieldDecorator('listedDate', {
                            initialValue: this.state.listedDate ? moment(this.state.listedDate) : null
                        })(
                            <DatePicker />
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="上市类型"
                    >   {getFieldDecorator('listedType', {
                        initialValue: this.state.listedType
                    })(
                        <Select placeholder="请选择上市类型">
                            <Select.Option value='0'>股票型上市公司</Select.Option>
                            <Select.Option value='1'>债券型上市公司</Select.Option>
                        </Select>
                        )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="股票代码"
                    >   {getFieldDecorator('stockCode', {
                        initialValue: this.state.stockCode
                    })(
                        <Input />
                        )}
                    </FormItem>
                </div>
                <div className="clearfix">
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="是否属于国家级高新区内企业"
                    >   {getFieldDecorator('highTechZone', {
                        initialValue: this.state.highTechZone || "0"
                    })(
                        <Radio.Group>
                            <Radio value="0">否</Radio>
                            <Radio value="1">是</Radio>
                        </Radio.Group>
                        )}
                    </FormItem>
                </div>
                <div className="clearfix" style={{ display: this.props.form.getFieldValue('highTechZone') == 0 ? 'none' : 'block' }}>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="国家级高新区名称"
                    >   {getFieldDecorator('zoneName', {
                        initialValue: this.state.listed || "0"
                    })(
                        <Input />
                        )}
                    </FormItem>
                </div>
                <div className="content-title">
                    <span>股权结构</span>
                </div>
                <div className="clearfix">
                    <div className="half-item">
                        <div className="table-title">
                            <span>自然人股权</span>
                            <Button style={{ background: "#ea0862", border: "none", color: "#fff" }}
                                onClick={this.humanAdd}>添加<Icon type="plus" /></Button>
                            <Button style={{ background: "#3fcf9e", border: "none", color: "#fff" }}
                                disabled={!humanHasSelected}
                                onClick={this.humanRemove}>删除<Icon type="minus" /></Button>
                            <Button type="primary" onClick={this.humanSave}>保存修改</Button>
                        </div>
                        <Table className="company-table" style={{ padding: '10px 20px' }}
                            columns={this.state.humanColumns}
                            dataSource={this.state.humanTableData}
                            pagination={false}
                            rowSelection={humanRowSelection} />
                    </div>
                    <div className="half-item">
                        <div className="table-title">
                            <span>法人股权</span>
                            <Button style={{ background: "#ea0862", border: "none", color: "#fff" }}
                                onClick={this.legalAdd}>添加<Icon type="plus" /></Button>
                            <Button style={{ background: "#3fcf9e", border: "none", color: "#fff" }}
                                disabled={!legalHasSelected}
                                onClick={this.legalRemove}>删除<Icon type="minus" /></Button>
                            <Button type="primary" onClick={this.legalSave}>保存修改</Button>
                        </div>
                        <Table className="company-table" style={{ padding: '10px 20px' }}
                            columns={this.state.legalColumns}
                            dataSource={this.state.legalTableData}
                            pagination={false}
                            rowSelection={legalRowSelection} />
                    </div>
                </div>
                <FormItem style={{ width: '50%' }}
                    {...formItemLayout}
                    label="是否引入风险投资"
                >
                    {getFieldDecorator('operatingProfit', {
                        rules: [{ required: true, message: '此项为必填项!' }],
                        initialValue: theData.operatingProfit
                    })(
                        <Radio.Group>
                            <Radio value="1">是</Radio>
                            <Radio value="2">否</Radio>
                        </Radio.Group>
                        )}
                </FormItem>
                <FormItem style={{ width: '50%' }}
                    {...formItemLayout}
                    label="经营范围(限400字)"
                >
                    {getFieldDecorator('operatingProfit', {
                        rules: [{ required: true, message: '此项为必填项!' }],
                        initialValue: theData.operatingProfit
                    })(
                        <Input type='textarea' rows={6} />
                        )}
                </FormItem>
                <div className="content-title">
                    <span>员工情况</span>
                </div>
                <div className="clearfix">
                    <FormItem className="half-item" style={{ width: '25%' }}
                        {...formItemLayout}
                        label="企业职工"
                    >
                        {getFieldDecorator('firmTotal', {
                            initialValue: theData.firmTotal || 0
                        })(
                            <InputNumber />
                            )}
                    </FormItem>
                    <FormItem className="half-item" 
                        {...formItemLayout}
                        label="科技人员"
                    >
                        {getFieldDecorator('techTotal', {
                            initialValue: theData.techTotal || 0
                        })(
                            <InputNumber />
                            )}
                        <span>其中科技人员占比
                        {(() => {
                                if (!this.props.form.getFieldValue('techTotal') || !this.props.form.getFieldValue('firmTotal')) {
                                    return 0
                                }
                                return (this.props.form.getFieldValue('techTotal') / this.props.form.getFieldValue('firmTotal') * 100).toFixed(2)
                            })()}
                            %</span>
                    </FormItem>
                </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 >
        );
    },
}));

export default CompanyDetail;