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


if (!Array.prototype.includes) {
    Object.defineProperty(Array.prototype, 'includes', {
        value: function (searchElement, fromIndex) {

            // 1. Let O be ? ToObject(this value).
            if (this == null) {
                throw new TypeError('"this" is null or not defined');
            }

            var o = Object(this);

            // 2. Let len be ? ToLength(? Get(O, "length")).
            var len = o.length >>> 0;

            // 3. If len is 0, return false.
            if (len === 0) {
                return false;
            }

            // 4. Let n be ? ToInteger(fromIndex).
            //    (If fromIndex is undefined, this step produces the value 0.)
            var n = fromIndex | 0;

            // 5. If n ≥ 0, then
            //  a. Let k be n.
            // 6. Else n < 0,
            //  a. Let k be len + n.
            //  b. If k < 0, let k be 0.
            var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

            // 7. Repeat, while k < len
            while (k < len) {
                // a. Let elementK be the result of ? Get(O, ! ToString(k)).
                // b. If SameValueZero(searchElement, elementK) is true, return true.
                // c. Increase k by 1.
                // NOTE: === provides the correct "SameValueZero" comparison needed here.
                if (o[k] === searchElement) {
                    return true;
                }
                k++;
            }

            // 8. Return false
            return false;
        }
    });
}


const ActivityForm = Form.create()(React.createClass({
    getInitialState() {
        return {
            loading: false,
            targetKeys: [],
            selectedKeys: []
        };
    },
    loadData(id) {
        this.setState({ loading: true });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/user/cognizance/activityDetail",
            data: {
                id: id || this.props.data.id
            }
        }).done(function (data) {
            if (!data.data) {
                if (data.error && data.error.length) {
                    message.warning(data.error[0].message);
                };
            } else {
                this.setState({
                    data: data.data,
                    targetKeys: data.data.intellectualPropertyNumber ? data.data.intellectualPropertyNumber.split(",") : [],
                    techField: [data.data.technicalField1, data.data.technicalField2, data.data.technicalField3]
                });
            };
        }.bind(this)).always(function (data) {
            this.setState({ loading: false });
        }.bind(this));
    },
    handleSubmit(e) {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.setState({ loading: true });
                $.ajax({
                    method: "POST",
                    dataType: "json",
                    crossDomain: false,
                    url: globalConfig.context + "/api/user/cognizance/activity",
                    data: {
                        id: this.props.data.id,
                        uid: this.props.uid,
                        activityName: values.activityName,
                        activityNumber: values.activityNumber,
                        projectMode: values.projectMode,
                        startDateFormattedDate: values.startDate ? values.startDate.format("YYYY-MM-DD") : null,
                        endDateFormattedDate: values.endDate ? values.endDate.format("YYYY-MM-DD") : null,
                        technicalField1: values.techField[0],
                        technicalField2: values.techField[1],
                        technicalField3: values.techField[2],
                        technicalSource: values.technicalSource,
                        intellectualPropertyNumber: this.state.targetKeys.join(","),
                        budget: values.budget,
                        implement: values.implement,
                        technologyInnovation: values.technologyInnovation,
                        achievement: values.achievement,
                        proofUrl: this.state.proofUrl
                    }
                }).done(function (data) {
                    if (!data.error.length) {
                        message.success('保存成功！');
                        this.props.closeModal(true);
                    } else {
                        message.warning(data.error[0].message);
                    };
                    this.setState({ loading: false });
                }.bind(this));
            }
        });
    },
    componentWillMount() {
        if (this.props.data.id) {
            this.loadData();
        } else {
            this.state.data = {};
            this.state.targetKeys = [];
            this.state.techField = undefined;
        };
    },
    componentWillReceiveProps(nextProps) {
        if (!this.props.visible && nextProps.visible) {
            this.state.mockData = nextProps.data.mockData;
            this.props.form.resetFields();
            this.state.proofUrl = undefined;
            this.state.fileList = [];
            if (nextProps.data.id) {
                this.loadData(nextProps.data.id);
            } else {
                this.state.data = {};
                this.state.targetKeys = [];
                this.state.techField = undefined;
            };
        };
    },
    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.state.data;
        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 12 },
        };
        if (theData) {
            return (
                <SpinContainer spinning={this.state.loading} className='spin-box'>
                    <Form onSubmit={this.handleSubmit} id="admin-desc-content">
                        <div className="clearfix">
                            <FormItem className="half-item"
                                {...formItemLayout}
                                label="研发活动编号"
                            >
                                {getFieldDecorator('activityNumber', {
                                    initialValue: theData.activityNumber
                                })(
                                    <Input />
                                    )}
                            </FormItem>
                            <FormItem className="half-item"
                                {...formItemLayout}
                                label="研发活动名称"
                            >
                                {getFieldDecorator('activityName', {
                                    initialValue: theData.activityName
                                })(
                                    <Input />
                                    )}
                            </FormItem>
                            <FormItem className="half-item"
                                {...formItemLayout}
                                label="开始日期"
                            >
                                {getFieldDecorator('startDate', {
                                    initialValue: theData.startDateFormattedDate ? moment(theData.startDateFormattedDate) : null
                                })(
                                    <DatePicker />
                                    )}
                            </FormItem>
                            <FormItem className="half-item"
                                {...formItemLayout}
                                label="结束日期"
                            >
                                {getFieldDecorator('endDate', {
                                    initialValue: theData.endDateFormattedDate ? moment(theData.endDateFormattedDate) : null
                                })(
                                    <DatePicker />
                                    )}
                            </FormItem>
                        </div>
                        <div className="clearfix">
                            <FormItem className="half-item"
                                {...formItemLayout}
                                label="技术领域"
                            >
                                {getFieldDecorator('techField', {
                                    initialValue: this.state.techField || []
                                })(
                                    <Cascader
                                        style={{ width: 500 }}
                                        options={techFieldList}
                                        placeholder="选择技术领域"
                                        showSearch
                                    />
                                    )}
                            </FormItem>
                        </div>
                        <div className="clearfix">
                            <FormItem className="half-item"
                                {...formItemLayout}
                                label="技术来源"
                            >
                                {getFieldDecorator('technicalSource', {
                                    initialValue: theData.technicalSource ? String(theData.technicalSource) : undefined,
                                })(
                                    <Select placeholder="选择技术来源" style={{ width: 230 }}>
                                        {
                                            technicalSourceList.map(function (item, i) {
                                                return <Select.Option key={1000 + i} value={item.value} >{item.key}</Select.Option>
                                            })
                                        }
                                    </Select>
                                    )}
                            </FormItem>
                            <FormItem className="half-item"
                                {...formItemLayout}
                                label="立项类型"
                            >
                                {getFieldDecorator('projectMode', {
                                    initialValue: theData.projectMode
                                })(
                                    <Select style={{ width: 120 }}>
                                        <Select.Option value='0'>内部立项</Select.Option>
                                        <Select.Option value='1'>外部立项</Select.Option>
                                    </Select>
                                    )}
                            </FormItem>
                        </div>
                        <div style={{ marginBottom: '20px' }}>
                            <p>知识产权编号:</p>
                            <Transfer
                                dataSource={this.props.mockData}
                                listStyle={{
                                    width: 300,
                                    height: 300,
                                }}
                                titles={['未选择', '已选择']}
                                targetKeys={this.state.targetKeys}
                                selectedKeys={this.state.selectedKeys}
                                onChange={this.intellectualChange}
                                onSelectChange={this.intellectualSelectChange}
                                render={item => `${item.name}-${item.number}`}
                            />
                        </div>
                        <FormItem className="half-div"
                            labelCol={{ span: 8 }}
                            wrapperCol={{ span: 12 }}
                            label="研发经费总预算"
                        >
                            {getFieldDecorator('budget', {
                                initialValue: theData.budget
                            })(
                                <InputNumber min={0} max={999999} step={0.01} />
                                )}
                            <span>万元</span>
                        </FormItem>
                        <div className="clearfix" >
                            <p>研发经费近三年总支出:</p>
                            <FormItem className="half-item"
                                labelCol={{ span: 8 }}
                                wrapperCol={{ span: 12 }}
                                label="总计"
                            >
                                <span>{
                                    (theData.firstYearExpenditure || 0) +
                                    (theData.secondYearExpenditure || 0) +
                                    (theData.thirdYearExpenditure || 0)
                                }</span>
                                <span>万元</span>
                            </FormItem>
                            <FormItem className="half-item"
                                labelCol={{ span: 8 }}
                                wrapperCol={{ span: 12 }}
                                label="其中（前一年）"
                            >
                                <span>{theData.firstYearExpenditure}</span>
                                <span>万元</span>
                            </FormItem>
                            <FormItem className="half-item"
                                labelCol={{ span: 8 }}
                                wrapperCol={{ span: 12 }}
                                label="其中（前二年）"
                            >
                                <span>{theData.secondYearExpenditure}</span>
                                <span>万元</span>
                            </FormItem>
                            <FormItem className="half-item"
                                labelCol={{ span: 8 }}
                                wrapperCol={{ span: 12 }}
                                label="其中（前三年）"
                            >
                                <span>{theData.thirdYearExpenditure}</span>
                                <span>万元</span>
                            </FormItem>
                        </div>
                        <div className="clearfix">
                            <div className="half-div">
                                <p>目的及组织实施方式（限400字）:</p>
                                {getFieldDecorator('implement', {
                                    initialValue: theData.implement
                                })(
                                    <Input type="textarea" rows={6} />
                                    )}
                            </div>
                            <div className="half-div">
                                <p>核心技术及创新点（限400字）:</p>
                                {getFieldDecorator('technologyInnovation', {
                                    initialValue: theData.technologyInnovation
                                })(
                                    <Input type="textarea" rows={6} />
                                    )}
                            </div>
                            <div className="half-div">
                                <p>取得的阶段性成果（限400字）:</p>
                                {getFieldDecorator('achievement', {
                                    initialValue: theData.achievement
                                })(
                                    <Input type="textarea" rows={6} />
                                    )}
                            </div>
                        </div>
                        <div style={{ width: '50%' }}>
                            <Upload
                                name="ratepay"
                                action={globalConfig.context + "/api/user/cognizance/uploadProof"}
                                data={{ 'sign': 'proof', '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.proofUrl = 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>{theData.proofUrl ? <a onClick={newDownloadFile.bind(null, theData.id, 'proof', '/api/user/cognizance/downloadProof')}>{theData.proofDownloadFileName}</a> : <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 >
                </SpinContainer >
            )
        } else {
            return (<div></div>)
        };
    }
}));

const ActivityDesc = React.createClass({
    getInitialState() {
        return {
            visible: false,
            loading: false
        };
    },
    handleCancel(e) {
        this.setState({
            visible: false,
        });
        this.props.closeDesc(false);
        if (e) {
            this.props.closeDesc(false, true);
        };
    },
    componentWillReceiveProps(nextProps) {
        this.state.visible = nextProps.showDesc;
    },
    render() {
        return (
            <div className="admin-desc">
                <Modal maskClosable={false} title="企业研究开发活动情况详情"
                    visible={this.state.visible}
                    onCancel={this.handleCancel}
                    width='800px'
                    footer=''
                    className="admin-desc-content">
                    <ActivityForm
                        visible={this.state.visible}
                        data={this.props.data}
                        uid={this.props.uid}
                        mockData={this.props.mockData}
                        spinState={this.spinChange}
                        closeModal={this.handleCancel} />
                </Modal>
            </div>
        );
    },
});

const Activity = React.createClass({
    loadData(pageNo) {
        this.state.data = [];
        this.setState({
            loading: true
        });
        $.when($.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/user/cognizance/activityList",
            data: {
                pageNo: pageNo || 1,
                pageSize: this.state.pagination.pageSize,
                activityNumber: this.state.activityNumber,
                activityName: this.state.activityName
            }
        }), $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/user/cognizance/intellectualList",
            data: {
                pageNo: pageNo || 1,
                pageSize: 99,
            }
        })).done((data1, data2) => {
            let data = data1[0];
            let intellectualList = data2[0];
            let theArr = [], theObj = {};
            if (data.error.length || !data.data || !data.data.list) {
                message.warning(data.error[0].message);
            } else {
                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,
                        activityNumber: thisdata.activityNumber,
                        activityName: thisdata.activityName,
                        startDate: thisdata.startDate,
                        endDate: thisdata.endDate,

                        mockData: this.state.mockData,

                        techField: [thisdata.technicalField1, thisdata.technicalField2, thisdata.technicalField3],
                        technicalField: getTechField(thisdata.technicalField1, thisdata.technicalField2, thisdata.technicalField3),
                        technicalField1: thisdata.technicalField1,
                        technicalField2: thisdata.technicalField2,
                        technicalField3: thisdata.technicalField3,
                        technicalSource: thisdata.technicalSource ? String(thisdata.technicalSource) : undefined,
                        intellectualPropertyNumber: thisdata.intellectualPropertyNumber ? thisdata.intellectualPropertyNumber.split(",") : [],
                        intellectualPropertyNumberText: thisdata.intellectualPropertyNumber,
                        budget: thisdata.budget,
                        firstYearExpenditure: thisdata.firstYearExpenditure,
                        secondYearExpenditure: thisdata.secondYearExpenditure,
                        thirdYearExpenditure: thisdata.thirdYearExpenditure,
                        implement: thisdata.implement,
                        technologyInnovation: thisdata.technologyInnovation,
                        achievement: thisdata.achievement,
                        internalLaborCost: thisdata.internalLaborCost,
                        internalDirectCost: thisdata.internalDirectCost,
                        internalDepreciationCost: thisdata.internalDepreciationCost,
                        internalAmortizationCost: thisdata.internalAmortizationCost,
                        internalDesignCost: thisdata.internalDesignCost,
                        internalEquipmentCost: thisdata.internalEquipmentCost,
                        internalOtherCost: thisdata.internalOtherCost,
                        externalTotalCost: thisdata.externalTotalCost,
                        externalAbroadCost: thisdata.externalAbroadCost,
                        enterpriseFiller: thisdata.enterpriseFiller,
                        signDate: thisdata.signDate,
                        sortNumber: thisdata.sortNumber,
                        startDateFormattedDate: thisdata.startDateFormattedDate,
                        endDateFormattedDate: thisdata.endDateFormattedDate,
                        projectMode: thisdata.projectMode,
                        proofUrl: thisdata.proofUrl,
                        proofDownloadFileName: thisdata.proofDownloadFileName
                    });
                };
                this.state.pagination.current = data.data.pageNo;
                this.state.pagination.total = data.data.totalCount;
            };
            if (intellectualList.error.length || !intellectualList.data || !intellectualList.data.list) {
                message.warning(intellectualList.error[0].message);
            } else {
                for (let i = 0; i < intellectualList.data.list.length; i++) {
                    theArr.push({
                        key: intellectualList.data.list[i].id,
                        number: intellectualList.data.list[i].intellectualPropertyNumber,
                        name: intellectualList.data.list[i].intellectualPropertyName
                    });
                    theObj[intellectualList.data.list[i].id] = intellectualList.data.list[i].intellectualPropertyNumber;
                };
            };
            this.setState({
                dataSource: this.state.data,
                pagination: this.state.pagination,
                mockData: theArr,
                mockDataObj: theObj
            });
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getInitialState() {
        return {
            mockData: [],
            mockDataObj: {},
            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: 'activityNumber',
                    key: 'activityNumber'
                }, {
                    title: '研发活动名称',
                    dataIndex: 'activityName',
                    key: 'activityName'
                }, {
                    title: '技术领域',
                    dataIndex: 'technicalField',
                    key: 'technicalField'
                }, {
                    title: '技术来源',
                    dataIndex: 'technicalSource',
                    key: 'technicalSource',
                    render: (text) => { return getTechnicalSource(text) }
                }, {
                    title: '知识产权编号',
                    dataIndex: 'intellectualPropertyNumberText',
                    key: 'intellectualPropertyNumberText',
                    render: (text) => {
                        let arr = [], _me = this;
                        if (text && text.split(',').length) {
                            text.split(',').map((item) => {
                                arr.push(_me.state.mockDataObj[item]);
                            });
                        };
                        return arr.join(',');
                    }
                }, {
                    title: '开始时间',
                    dataIndex: 'startDateFormattedDate',
                    key: 'startDateFormattedDate'
                }, {
                    title: '结束时间',
                    dataIndex: 'endDateFormattedDate',
                    key: 'endDateFormattedDate'
                }
            ],
            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/user/cognizance/deleteActivity",
            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.state.activityName = undefined;
        this.state.activityNumber = undefined;
        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">
                    <Input placeholder="研发活动名称" value={this.state.activityName}
                        onChange={(e) => { this.setState({ activityName: e.target.value }); }} />
                    <Input placeholder="研发活动编号" value={this.state.activityNumber}
                        onChange={(e) => { this.setState({ activityNumber: e.target.value }); }} />
                    <Button type="primary" onClick={this.search}>搜索</Button>
                    <Button onClick={this.reset}>重置</Button>
                    <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">
                    <SpinContainer spinning={this.state.loading}>
                        <Table columns={this.state.columns}
                            dataSource={this.state.dataSource}
                            pagination={this.state.pagination}
                            rowSelection={rowSelection}
                            onRowClick={this.tableRowClick} />
                    </SpinContainer>
                </div>
                <ActivityDesc data={this.state.RowData}
                    mockData={this.state.mockData}
                    showDesc={this.state.showDesc} closeDesc={this.closeDesc} />
            </div >
        );
    }
});

export default Activity;
