import React from 'react';
import { Switch, Icon, Upload, Form, Button, Radio, Input, Spin, Table, message, Select, Modal, Cascader, Transfer, InputNumber } from 'antd';
import { technicalSourceList } from '../../../../dataDic.js';
import { techFieldList } from '../../../../DicTechFieldList.js';
import { getPreview, getTechField, getTechnicalSource, beforeUploadFile, newDownloadFile, getProportion, saveProportion } from '../../../../tools.js';
import moment from 'moment';
import ajax from 'jquery/src/ajax/xhr.js';
import $ from 'jquery/src/ajax';

const TechProductDescFrom = Form.create()(React.createClass({
    getInitialState() {
        return {
            loading: false,
            targetKeys: [],
            selectedKeys: [],
            technicalSourceOption: [],
        };
    },
    componentWillMount() {
        let _me = this;
        technicalSourceList.map(function (item) {
            _me.state.technicalSourceOption.push(
                <Select.Option value={item.value} key={10000 + item.value}>{item.key}</Select.Option>
            )
        });
        this.state.targetKeys = this.props.data.intellectualPropertyNumber || [];
    },
    componentWillReceiveProps(nextProps) {
        if (!this.props.visible && nextProps.visible && nextProps.data && this.props.resetForm) {
            this.state.targetKeys = nextProps.data.intellectualPropertyNumber || [];
            this.props.form.resetFields();
        };
    },
    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/techProduct",
                    data: {
                        id: this.props.data.id,
                        uid: this.props.uid,
                        serialNumber: values.serialNumber,
                        productName: values.productName,
                        technicalField1: values.techField[0],
                        technicalField2: values.techField[1],
                        technicalField3: values.techField[2],
                        technicalSource: values.technicalSource,
                        lastYearRevenue: values.lastYearRevenue,
                        mainProduct: values.mainProduct,
                        intellectualPropertyNumber: this.state.targetKeys ? this.state.targetKeys.join(",") : '',
                        keyTechnology: values.keyTechnology,
                        competitiveEdge: values.competitiveEdge,
                        conditionEffect: values.conditionEffect,
                        accountUrl: this.state.accountUrl
                    }
                }).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));
            }
        });
    },
    intellectualChange(nextTargetKeys, direction, moveKeys) {
        this.setState({ targetKeys: nextTargetKeys });
    },
    intellectualSelectChange(sourceSelectedKeys, targetSelectedKeys) {
        this.setState({ selectedKeys: [...sourceSelectedKeys, ...targetSelectedKeys] });
    },
    render() {
        const FormItem = Form.Item;
        const { getFieldDecorator } = this.props.form;
        const theData = this.props.data;
        const formItemLayout = {
            labelCol: { span: 10 },
            wrapperCol: { span: 12 },
        };
        const _me = this;
        return (
            <Form onSubmit={this.handleSubmit} id="techProduct-form">
                <div className="clearfix">
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="编号:ps"
                    >
                        {getFieldDecorator('serialNumber', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.serialNumber
                        })(
                            <Input />
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="产品(服务)名称"
                    >
                        {getFieldDecorator('productName', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.productName
                        })(
                            <Input />
                            )}
                    </FormItem>
                </div>
                <div className="clearfix">
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="技术来源"
                    >
                        {getFieldDecorator('technicalSource', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.technicalSource
                        })(
                            <Select placeholder="选择技术来源"
                                onChange={(e) => { this.setState({ technicalSource: e }) }}>
                                {this.state.technicalSourceOption}
                            </Select>
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        labelCol={{ span: 10 }}
                        label="上年度销售收入(万元)"
                    >
                        {getFieldDecorator('lastYearRevenue', {
                            rules: [{ type: "number", required: true, message: '此项为必填项!' }],
                            initialValue: theData.lastYearRevenue ? Number(theData.lastYearRevenue) : 0
                        })(
                            <InputNumber />
                            )}
                    </FormItem>
                </div>
                <FormItem
                    labelCol={{ span: 5 }}
                    wrapperCol={{ span: 16 }}
                    label="技术领域"
                >
                    {getFieldDecorator('techField', {
                        rules: [{ type: "array", required: true, message: '此项为必填项!' }],
                        initialValue: theData.techField
                    })(
                        <Cascader
                            options={techFieldList}
                            onChange={(value, selectedOptions) => { this.setState({ techField: value }); console.log(value) }}
                            placeholder="请选择"
                            showSearch
                        />
                        )}
                </FormItem>
                <div className="clearfix">
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="是否主要产品(服务)"
                    >
                        {getFieldDecorator('mainProduct', {
                            rules: [{ type: "number", required: true, message: '此项为必填项!' }],
                            initialValue: theData.mainProduct
                        })(
                            <Radio.Group>
                                <Radio value={1}>是</Radio>
                                <Radio value={0}>否</Radio>
                            </Radio.Group>
                            )}
                    </FormItem>
                </div>
                <p>知识产权编号:</p>
                <Transfer
                    dataSource={this.props.mockData}
                    listStyle={{
                        width: 200,
                        height: 200,
                    }}
                    titles={['未选择', '已选择']}
                    targetKeys={this.state.targetKeys}
                    selectedKeys={this.state.selectedKeys}
                    onChange={this.intellectualChange}
                    onSelectChange={this.intellectualSelectChange}
                    render={item => `${item.name}-${item.key}`}
                />
                <div className="clearfix">
                    <FormItem className="half-item"
                        labelCol={{ span: 0 }}
                        wrapperCol={{ span: 22 }}
                    >
                        <p>关键技术及主要技术指标(限400字)</p>
                        {getFieldDecorator('keyTechnology', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.keyTechnology
                        })(
                            <Input type='textarea' rows={6} onChange={(e) => { if (e.target.value.length > 400) { return; } }} />
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        labelCol={{ span: 0 }}
                        wrapperCol={{ span: 22 }}
                    >
                        <p>与同类产品(服务)的竞争优势(限400字)</p>
                        {getFieldDecorator('competitiveEdge', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.competitiveEdge
                        })(
                            <Input type='textarea' rows={6} onChange={(e) => { if (e.target.value.length > 400) { return; } }} />
                            )}
                    </FormItem>
                    <p style={{ lineHeight: "32px" }}>知识产权获得情况及其对产品(服务)在技术上发挥的支持作用(限400字)*</p>
                    <FormItem className="half-item"
                        labelCol={{ span: 0 }}
                        wrapperCol={{ span: 22 }}
                    >
                        {getFieldDecorator('conditionEffect', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.conditionEffect
                        })(
                            <Input type='textarea' rows={6} onChange={(e) => { if (e.target.value.length > 400) { return; } }} />
                            )}
                    </FormItem>
                </div>
                <div style={{ width: '50%' }}>
                    <Upload
                        name="ratepay"
                        action={globalConfig.context + "/api/admin/uploadTecProduct"}
                        data={{ 'sign': 'tech_product', 'uid': this.props.uid }}
                        beforeUpload={beforeUploadFile}
                        showUploadList={false}
                        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.accountUrl = info.file.response.data;
                            } else if (info.file.status === 'error') {
                                message.error(`${info.file.name} 文件上传失败。`);
                            }
                        }}
                    >
                        <Button><Icon type="upload" /> 上传高新技术产品台帐 </Button>
                    </Upload>
                    <p style={{ marginTop: '10px' }}>{theData.accountUrl ?
                        <span className="download-file">
                            <a onClick={newDownloadFile.bind(null, this.props.data.id, 'tech_product', '/api/admin/downloadTecProduct')}>{theData.accountDownloadFileName}</a>
                            <a onClick={() => {
                                getPreview(theData.id, 'techProduct', 'tech_product', function (data) { window.open('https://view.officeapps.live.com/op/view.aspx?src=' + encodeURIComponent(location.origin + globalConfig.context + "/open/preview?" + 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 TechProductDesc = React.createClass({
    getInitialState() {
        return {
            visible: false,
            loading: false
        };
    },
    componentWillReceiveProps(nextProps) {
        this.state.visible = nextProps.showDesc
    },
    showModal() {
        this.setState({
            visible: true,
            resetForm: false
        });
    },
    handleOk() {
        this.setState({
            visible: false,
            resetForm: true
        });
        this.props.closeDesc(false, true);
    },
    handleCancel(e) {
        this.setState({
            visible: false,
            resetForm: true
        });
        this.props.closeDesc(false);
    },
    spinChange(e) {
        this.setState({
            loading: e
        });
    },
    render() {
        return (
            <div className="patent-addNew">
                <Spin spinning={this.state.loading} className='spin-box'>
                    <Modal title="上年度高新技术产品(服务)情况表" visible={this.state.visible}
                        onOk={this.handleOk} onCancel={this.handleCancel}
                        width='800px'
                        footer=''
                    >
                        <TechProductDescFrom
                            data={this.props.data}
                            uid={this.props.uid}
                            visible={this.state.visible}
                            resetForm={this.state.resetForm}
                            mockData={this.props.mockData}
                            spinState={this.spinChange} closeModal={this.handleCancel} clickOk={this.handleOk} />
                    </Modal>
                </Spin>
            </div>
        );
    },
});

const TechProduct = React.createClass({
    loadData(pageNo) {
        this.state.data = [];
        this.setState({
            loading: true
        });
        $.when($.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/techProductList",
            data: {
                pageNo: pageNo || 1,
                pageSize: this.state.pagination.pageSize,
                uid: this.props.data.uid
            }
        }), $.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/intellectualList",
            data: {
                pageNo: pageNo || 1,
                pageSize: 99,
                uid: this.props.data.uid
            }
        })).done((data1, data2) => {
            let data = data1[0];
            let intellectualList = data2[0];
            if (data.error.length || !data.data || !data.data.list) {
                message.warning(data.error[0].message);
                return;
            };
            if (intellectualList.error.length || !intellectualList.data || !intellectualList.data.list) {
                message.warning(intellectualList.error[0].message);
                return;
            };
            let theArr = [];
            for (let i = 0; i < intellectualList.data.list.length; i++) {
                theArr.push({
                    key: intellectualList.data.list[i].intellectualPropertyNumber,
                    name: intellectualList.data.list[i].intellectualPropertyName
                });
            };
            this.state.mockData = theArr;
            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,

                    mockData: this.state.mockData,

                    serialNumber: thisdata.serialNumber,
                    productName: thisdata.productName,

                    techField: [Number(thisdata.technicalField1), Number(thisdata.technicalField2), Number(thisdata.technicalField3)],
                    technicalField: getTechField(thisdata.technicalField1, thisdata.technicalField2, thisdata.technicalField3),
                    technicalField1: thisdata.technicalField1,
                    technicalField2: thisdata.technicalField2,
                    technicalField3: thisdata.technicalField3,

                    technicalSource: String(thisdata.technicalSource),
                    lastYearRevenue: thisdata.lastYearRevenue,
                    mainProduct: thisdata.mainProduct,

                    PropertyNumber: thisdata.intellectualPropertyNumber,
                    intellectualPropertyNumber: thisdata.intellectualPropertyNumber ? thisdata.intellectualPropertyNumber.split(",") : [],

                    keyTechnology: thisdata.keyTechnology,
                    competitiveEdge: thisdata.competitiveEdge,
                    conditionEffect: thisdata.conditionEffect,
                    year: thisdata.year,
                    createTime: thisdata.createTime,

                    accountDownloadFileName: thisdata.accountDownloadFileName,
                    accountUrl: thisdata.accountUrl

                });
            };
            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: 'serialNumber',
                    key: 'serialNumber'
                }, {
                    title: '产品(服务)名称',
                    dataIndex: 'productName',
                    key: 'productName'
                }, {
                    title: '技术领域',
                    dataIndex: 'technicalField',
                    key: 'technicalField'
                }, {
                    title: '技术来源',
                    dataIndex: 'technicalSource',
                    key: 'technicalSource',
                    render: (text) => { return getTechnicalSource(text) }
                }, {
                    title: '上年度销售收入(万元)',
                    dataIndex: 'lastYearRevenue',
                    key: 'lastYearRevenue'
                }, {
                    title: '是否主要产品(服务)',
                    dataIndex: 'mainProduct',
                    key: 'mainProduct',
                    render: (text) => { if (text == "1") { return '是' } else { return '否' } }
                }, {
                    title: '知识产权编号',
                    dataIndex: 'PropertyNumber',
                    key: 'PropertyNumber'
                }
            ],
            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/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();
        };
    },
    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.techProject == 1 ? true : false}
                        checkedChildren={'已完成'}
                        unCheckedChildren={'未完成'}
                        onChange={(e) => {
                            e ? this.state.proportion.techProject = 1 : this.state.proportion.techProject = 0;
                            saveProportion(this.state.proportion.id, this.props.data.uid, 'techProject', this.state.proportion.techProject);
                            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>
                <TechProductDesc
                    data={this.state.RowData}
                    uid={this.props.data.uid}
                    mockData={this.state.mockData}
                    showDesc={this.state.showDesc} closeDesc={this.closeDesc} />
            </div >
        );
    }
});

export default TechProduct;