import React from 'react';
import { Icon, Button, Upload, Input, Spin, Table, message, Select, Modal, DatePicker, Cascader, Transfer, InputNumber } from 'antd';
import { techFieldList, technicalSourceList } from '../../../../dataDic.js';
import { getTechField, getTechnicalSource, beforeUploadFile, downloadFile } from '../../../../tools.js';
import moment from 'moment';
import ajax from 'jquery/src/ajax/xhr.js';
import $ from 'jquery/src/ajax';

const ActivityDesc = React.createClass({
    getInitialState() {
        return {
            visible: false,
            loading: false,
            targetKeys: [],
            selectedKeys: []
        };
    },
    handleOk() {
        this.setState({
            loading: true,
        });
        $.ajax({
            method: "POST",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/activity",
            data: {
                id: this.props.data.id,
                uid: this.props.uid,
                activityName: this.state.activityName,
                activityNumber: this.state.activityNumber,
                startDateFormattedDate: this.state.startDateFormattedDate,
                endDateFormattedDate: this.state.endDateFormattedDate,
                technicalField1: this.state.techField[0],
                technicalField2: this.state.techField[1],
                technicalField3: this.state.techField[2],
                technicalSource: this.state.technicalSource,
                intellectualPropertyNumber: this.state.targetKeys.join(","),
                budget: this.state.budget,
                firstYearExpenditure: this.state.firstYearExpenditure,
                secondYearExpenditure: this.state.secondYearExpenditure,
                thirdYearExpenditure: this.state.thirdYearExpenditure,
                implement: this.state.implement,
                technologyInnovation: this.state.technologyInnovation,
                achievement: this.state.achievement,
                participant: this.state.participant,
                proofUrl: this.state.proofUrl
            },
            success: function (data) {
                if (data.data) {
                    this.setState({
                        id: this.props.data.id,
                        activityName: this.state.activityName,
                        activityNumber: this.state.activityNumber,
                        startDateFormattedDate: this.state.startDateFormattedDate,
                        endDateFormattedDate: this.state.endDateFormattedDate,
                        techField: this.state.techField,
                        technicalSource: this.state.technicalSource,
                        intellectualPropertyNumber: this.state.targetKeys,
                        budget: this.state.budget,
                        firstYearExpenditure: this.state.firstYearExpenditure,
                        secondYearExpenditure: this.state.secondYearExpenditure,
                        thirdYearExpenditure: this.state.thirdYearExpenditure,
                        implement: this.state.implement,
                        technologyInnovation: this.state.technologyInnovation,
                        achievement: this.state.achievement,
                        projectMode: this.state.projectMode
                    });
                } else if (data.error.length && data.error[0].message) {
                    message.warning(data.error[0].message);
                }
            }.bind(this),
        }).done(function (data) {
            if (!data.error.length) {
                message.success('保存成功!');
                this.setState({
                    loading: false,
                    visible: false
                });
                this.props.closeDesc(false, true);
            } else {
                message.warning(data.error[0].message);
                this.setState({
                    loading: false
                });
            };
        }.bind(this));
    },
    handleCancel(e) {
        this.setState({
            visible: false,
        });
        this.props.closeDesc(false);
    },
    componentWillReceiveProps(nextProps) {
        if (!this.state.showDesc && nextProps.showDesc) {
            this.state.activityName = nextProps.data.activityName;
            this.state.activityNumber = nextProps.data.activityNumber;
            this.state.startDateFormattedDate = nextProps.data.startDateFormattedDate;
            this.state.endDateFormattedDate = nextProps.data.endDateFormattedDate;
            this.state.techField = nextProps.data.techField;
            this.state.technicalSource = nextProps.data.technicalSource;
            this.state.targetKeys = nextProps.data.intellectualPropertyNumber || [];
            this.state.budget = nextProps.data.budget;
            this.state.firstYearExpenditure = nextProps.data.firstYearExpenditure;
            this.state.secondYearExpenditure = nextProps.data.secondYearExpenditure;
            this.state.thirdYearExpenditure = nextProps.data.thirdYearExpenditure;
            this.state.implement = nextProps.data.implement;
            this.state.technologyInnovation = nextProps.data.technologyInnovation;
            this.state.achievement = nextProps.data.achievement;
            this.state.projectMode = nextProps.data.projectMode ? String(nextProps.data.projectMode) : undefined;
            this.state.proofUrl = nextProps.data.proofUrl;
            this.state.proofDownloadFileName = nextProps.data.proofDownloadFileName;
            this.state.mockData = nextProps.data.mockData;
        };
        this.state.visible = nextProps.showDesc;
    },
    intellectualChange(nextTargetKeys, direction, moveKeys) {
        this.setState({ targetKeys: nextTargetKeys });
    },
    intellectualSelectChange(sourceSelectedKeys, targetSelectedKeys) {
        this.setState({ selectedKeys: [...sourceSelectedKeys, ...targetSelectedKeys] });
    },
    render() {
        if (this.props.data) {
            return (
                <div className="admin-desc">
                    <Modal title="企业研究开发活动情况详情" visible={this.state.visible} onCancel={this.handleCancel}
                        width='800px' footer={[
                            <Button key="submit" type="primary" size="large" loading={this.state.loading} onClick={this.handleOk}>保存</Button>,
                            <Button key="back" type="ghost" size="large" onClick={this.handleCancel}>取消</Button>
                        ]}
                        className="admin-desc-content">
                        <div className="clearfix">
                            <div className="half-div">
                                <p>研发活动编号:</p>
                                <Input value={this.state.activityNumber}
                                    onChange={(e) => { this.setState({ activityNumber: e.target.value }); }} />
                            </div>
                            <div className="half-div">
                                <p>研发活动名称:</p>
                                <Input value={this.state.activityName}
                                    onChange={(e) => { this.setState({ activityName: e.target.value }); }} />
                            </div>
                            <div className="half-div">
                                <p>开始日期:</p>
                                <DatePicker
                                    value={this.state.startDateFormattedDate ? moment(this.state.startDateFormattedDate) : null}
                                    onChange={(data, dataString) => { this.setState({ startDateFormattedDate: dataString }); }} />
                            </div>
                            <div className="half-div">
                                <p>结束日期:</p>
                                <DatePicker
                                    value={this.state.endDateFormattedDate ? moment(this.state.endDateFormattedDate) : null}
                                    onChange={(data, dataString) => { this.setState({ endDateFormattedDate: dataString }); }} />
                            </div>
                        </div>
                        <div>
                            <p>技术领域:</p>
                            <Cascader
                                style={{ width: 500 }}
                                options={techFieldList}
                                value={this.state.techField}
                                onChange={(value, selectedOptions) => { this.setState({ techField: value }); console.log(value) }}
                                placeholder="选择技术领域"
                                showSearch
                            />,
                        </div>
                        <div className="half-div">
                            <p>技术来源:</p>
                            <Select placeholder="选择技术来源" style={{ width: 230 }}
                                value={this.state.technicalSource}
                                onChange={(e) => { this.setState({ technicalSource: e }) }}>
                                {
                                    technicalSourceList.map(function (item, i) {
                                        return <Select.Option key={1000 + i} value={item.value} >{item.key}</Select.Option>
                                    })
                                }
                            </Select>
                        </div>
                        <div className="half-div">
                            <p>参与人员:</p>
                            <InputNumber value={this.state.participant}
                                onChange={(e) => { this.setState({ participant: e }); }} />
                        </div>
                        <div style={{ marginTop: '10px' }}>
                            <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.key}`}
                            />
                        </div>
                        <div>
                            <p>研发经费总预算(万元):</p>
                            <InputNumber value={this.state.budget || 0}
                                onChange={(e) => { this.setState({ budget: e }); }} />
                        </div>
                        <div className="clearfix" >
                            <p>研发经费近三年总支出(万元):</p>
                            <div className="half-div">
                                <span>总计(万元):</span>
                                <InputNumber value={
                                    (this.state.firstYearExpenditure || 0) +
                                    (this.state.secondYearExpenditure || 0) +
                                    (this.state.thirdYearExpenditure || 0)
                                } />
                                <span>(自动计算)</span>
                            </div>
                            <div className="half-div">
                                <span>其中(第一年):</span>
                                <InputNumber value={this.state.firstYearExpenditure || 0}
                                    onChange={(e) => { this.setState({ firstYearExpenditure: e || 0 }); }} />
                            </div>
                            <div className="half-div">
                                <span>其中(第二年):</span>
                                <InputNumber value={this.state.secondYearExpenditure || 0}
                                    onChange={(e) => { this.setState({ secondYearExpenditure: e || 0 }); }} />
                            </div>
                            <div className="half-div">
                                <span>其中(第三年):</span>
                                <InputNumber value={this.state.thirdYearExpenditure || 0}
                                    onChange={(e) => { this.setState({ thirdYearExpenditure: e || 0 }); }} />
                            </div>
                        </div>
                        <div className="clearfix">
                            <div className="half-div">
                                <p>目的及组织实施方式(限400字):</p>
                                <Input type="textarea" rows={6}
                                    value={this.state.implement}
                                    onChange={(e) => {
                                        if (e.target.value.length > 400) {
                                            return;
                                        }
                                        this.setState({ implement: e.target.value });
                                    }} />
                            </div>
                            <div className="half-div">
                                <p>核心技术及创新点(限400字):</p>
                                <Input type="textarea" rows={6}
                                    value={this.state.technologyInnovation}
                                    onChange={(e) => {
                                        if (e.target.value.length > 400) {
                                            return;
                                        }
                                        this.setState({ technologyInnovation: e.target.value });
                                    }} />
                            </div>
                            <div className="half-div">
                                <p>取得的阶段性成果(限400字):</p>
                                <Input type="textarea" rows={6}
                                    value={this.state.achievement}
                                    onChange={(e) => {
                                        if (e.target.value.length > 400) {
                                            return;
                                        }
                                        this.setState({ achievement: e.target.value });
                                    }} />
                            </div>
                        </div>
                        <Select style={{ width: 120 }}
                            placeholder='请选择立项类型'
                            value={this.state.projectMode}
                            onChange={(e) => { this.setState({ projectMode: e }); }}>
                            <Select.Option value='1'>内部立项</Select.Option>
                            <Select.Option value='2'>外部立项</Select.Option>
                        </Select>
                        <div style={{ width: '50%' }}>
                            <Upload
                                name="ratepay"
                                action={globalConfig.context + "/techservice/cognizance/upload"}
                                data={{ 'sign': 'proof' }}
                                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.proofUrl = info.file.response.data;
                                    } else if (info.file.status === 'error') {
                                        message.error(`${info.file.name} 文件上传失败。`);
                                    }
                                }}
                            >
                                <Button><Icon type="upload" /> 上传立项证明材料 </Button>
                            </Upload>
                            <p>{this.state.proofUrl ? <a onClick={downloadFile.bind(null, this.state.proofUrl, this.state.proofDownloadFileName)}>{this.state.proofDownloadFileName}</a> : <span><Icon type="exclamation-circle" style={{ color: '#ffbf00', marginRight: '6px' }} />未上传!</span>}</p>
                        </div>
                    </Modal>
                </div>
            );
        } else {
            return <div></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/admin/activityList",
            data: {
                pageNo: pageNo || 1,
                pageSize: this.state.pagination.pageSize,
                uid: this.props.data.uid,
                activityNumber: this.state.activityNumber,
                activityName: this.state.activityName,
                startDateFormattedDate: this.state.startDateFormattedDate,
                endDateFormattedDate: this.state.endDateFormattedDate
            }
        }), $.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/intellectualList",
            data: {
                uid: this.props.data.uid,
                pageNo: pageNo || 1,
                pageSize: 99,
            }
        })).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,
                    activityNumber: thisdata.activityNumber,
                    activityName: thisdata.activityName,
                    startDate: thisdata.startDate,
                    endDate: thisdata.endDate,

                    mockData: this.state.mockData,

                    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: thisdata.technicalSource ? String(thisdata.technicalSource) : undefined,
                    intellectualPropertyNumber: thisdata.intellectualPropertyNumber ? thisdata.intellectualPropertyNumber.split(",") : [],
                    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;
            this.setState({
                dataSource: this.state.data,
                pagination: this.state.pagination
            });
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getInitialState() {
        return {
            mockData: [],
            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: 'intellectualPropertyNumber',
                    key: 'intellectualPropertyNumber'
                }, {
                    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 + "/techservice/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.state.startDateFormattedDate = undefined;
        this.state.endDateFormattedDate = 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 }); }} />
                    <span>开始日期:</span>
                    <DatePicker
                        value={this.state.startDateFormattedDate ? moment(this.state.startDateFormattedDate) : null}
                        onChange={(data, dataString) => { this.setState({ startDateFormattedDate: dataString }); }} />
                    <span>结束日期:</span>
                    <DatePicker
                        value={this.state.endDateFormattedDate ? moment(this.state.endDateFormattedDate) : null}
                        onChange={(data, dataString) => { this.setState({ endDateFormattedDate: dataString }); }} />
                    <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">
                    <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>
                <ActivityDesc data={this.state.RowData}
                    uid={this.props.data.uid}
                    mockData={this.state.mockData}
                    showDesc={this.state.showDesc} closeDesc={this.closeDesc} />
            </div >
        );
    }
});

export default Activity;