import React from 'react';
import {Icon, Button, Input, Select, Spin, Popconfirm, Table, Switch, message, DatePicker, Modal, Upload} from 'antd';
import ajax from 'jquery/src/ajax/xhr.js';
import $ from 'jquery/src/ajax';
import moment from 'moment';
import './techDemand.less';
import TechDemandDesc from './demandDesc.jsx';
import { demandTypeList } from '@/dataDic.js';
import { getDemandType,getReleaseStateList } from '@/tools.js';
const DemandList = React.createClass({
    loadData(pageNo) {
        this.state.data = [];
        this.setState({
            page:pageNo,
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/user/demand/list",
            data: {
                pageNo: pageNo || 1,
                pageSize: this.state.pagination.pageSize,
                name: this.state.name, //需求名称
                startDate: this.state.releaseDate[0],
                endDate: this.state.releaseDate[1],
            },
            success: function (data) {
                let theArr = [];
                if (!data.data || !data.data.list) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    };
                } else {
                    for (let i = 0; i < data.data.list.length; i++) {
                        let thisdata = data.data.list[i];
                        theArr.push({
                            key: i,
                            id: thisdata.id,
                            serialNumber: thisdata.serialNumber, //编号
                            name: thisdata.name,
                            demandType: thisdata.demandType,
                            auditStatus: thisdata.auditStatus, //审核状态
                            createTime:thisdata.createTime?(new Date(thisdata.createTime)).toLocaleString():'',
                            status:thisdata.status, //需求状态
                            releaseDate:thisdata.releaseDate?(new Date(thisdata.releaseDate)).toLocaleString():''
                        });
                    };
                };
                this.state.pagination.current = data.data.pageNo;
                this.state.pagination.total = data.data.totalCount;
                if(data.data&&data.data.list&&!data.data.list.length){
					this.state.pagination.current=0
					this.state.pagination.total=0
				};
                this.setState({
                    total:data.data.totalCount,
                    dataSource: theArr,
                    pagination: this.state.pagination
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getInitialState() {
        return {
            uploadFileLoading:false,
            searchMore: true,
            validityPeriodDate: [],
            releaseDate: [],
            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: 'name',
                    key: 'name',
                },  {
                    title: '需求类型',
                    dataIndex: 'demandType',
                    key: 'demandType',
                    render: text => { return getDemandType(text); }
                },
                {
                    title: '发布状态',
                    dataIndex: 'auditStatus',
                    key: 'auditStatus',
                    render: text => { return getReleaseStateList(text) }
                }, {
                    title: '创建时间',
                    dataIndex: 'createTime',
                    key: 'createTime'
                },
                {
                    title: '发布时间',
                    dataIndex: 'releaseDate',
                    key: 'releaseDate'
                },
                {
                    title: '需求状态',
                    dataIndex: 'status',
                    key: 'status',
                    render: text => {
                        return  <div>
                                    {text=='0'&&<span>进行中</span>}
                                    {text=='1'&&<span>未解决</span>}
                                    {text=='2'&&<span>已解决</span>}
                                </div>

                     }
                },
                {
                    title: '操作',
                    dataIndex: 'caozuo',
                    key: 'caozuo',
                    render:(text,recard) => {
                        return  <div className="btnRight">
                                   {recard.auditStatus!='1'&&recard.auditStatus!='2'&&<Button type="primary" style={{ background: "#3fcf9e", border: "none", color: "#fff" }} onClick={(e)=>{e.stopPropagation(),this.submission(recard)}}>提交审核</Button>}
                                   {recard.auditStatus!='1'&&recard.auditStatus=='2'&&<Button type="success" onClick={(e)=>{ e.stopPropagation(),this.updateFun(recard)}}>刷新发布</Button>}
                                   {recard.auditStatus!='1'&&recard.auditStatus=='2'&&<Button type="danger" onClick={(e)=>{e.stopPropagation(),this.revokeFun(recard)}}>撤销发布</Button>}
                                </div>
                    }
                }
            ],
            dataSource: [],
            searchTime: [,]
        };
    },
    //提交审核
    submission(record){
        this.setState({
            showDesc:false,
            loading:true
        });
        $.ajax({
            method: "POST",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/user/demand/publishDemand",
            data: {
				id:record.id,
				auditStatus:record.auditStatus
            }
        }).done(function (data) {
            if (!data.error.length) {
                message.success('提交成功.');
                this.setState({
                    loading: false,
                });
                this.loadData(this.state.page)
            } else {
                message.warning(data.error[0].message);
            };
        }.bind(this));
    },
    //刷新发布
    updateFun(recard){
        this.setState({
            loading:true
        })
        $.ajax({
            method: "POST",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context +'/api/user/demand/refreshPublish',
            data: {
                id: recard.id,
                auditStatus:recard.auditStatus
            }
        }).done(function (data) {
            if (!data.error.length) {
                message.success('刷新成功！');
                this.setState({
                    loading: false,
                });
            } else {
                message.warning(data.error[0].message);
            };
            this.loadData(this.state.page);
        }.bind(this));
    },
    //撤销发布
    revokeFun(recard){
        this.setState({
            loading:true
        })
        $.ajax({
            method: "POST",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context +  '/api/user/demand/offShelf',
            data: {
                id: recard.id,
                auditStatus:recard.auditStatus 
            }
        }).done(function (data) {
            if (!data.error.length) {
                message.success('撤销成功！');
                this.setState({
                    loading: false,
                });
                this.loadData(this.state.page);
            } else {
                message.warning(data.error[0].message);
            };
        }.bind(this));
    },
    componentWillMount() {
        let theArr = [];
        demandTypeList.map(function (item) {
            theArr.push(
                <Select.Option value={item.value} key={item.key}>{item.key}</Select.Option>
            )
        });
        this.state.demandTypeOption = theArr;
        this.loadData();
    },
    tableRowClick(record, index) {
        this.state.RowData = record;
        this.setState({
            showDesc: true
        });
    },
    delectRow(recard) {
        let deletedIds =[];
        let rowItem = this.state.selectedRowKeys[0];
        let data = this.state.dataSource ||[];
        if (data.length) {
            deletedIds.push(data[rowItem].id);
        }
        this.setState({
            selectedRowKeys: [],
            loading: deletedIds.length > 0
        });
        $.ajax({
            method: "POST",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/user/demand/delete",
            data: {
                ids: deletedIds
            }
        }).done(function (data) {
            if (!data.error.length) {
                message.success('删除成功！');
                this.setState({
                    loading: false
                });
                if((this.state.total)%10==1){
                    this.loadData((this.state.page)-1);
                }else{
                    this.loadData(this.state.page);
                }
            } else {
                message.warning(data.error[0].message);
            };
        }.bind(this));
    },
    addClick() {
        this.state.RowData = {};
        this.setState({
            showDesc: true
        });
    },
    closeDesc(e, s) {
        this.state.showDesc = e;
        if (s) {
            this.loadData(this.state.page);
        };
    },
    search() {
        this.loadData();
    },
    reset() {
        this.state.name = '';
        this.state.releaseDate = [];
        this.loadData();
    },
    searchSwitch() {
        this.setState({
            searchMore: !this.state.searchMore
        });
    },
    downLoadFile() {
        window.open(globalConfig.context + '/api/user/demand/downloadTemplate?sign=demand_template')
    },
    render() {
        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRows: selectedRows.slice(-1),
                    selectedRowKeys: selectedRowKeys.slice(-1)
                });
            }
        };
        const hasSelected = this.state.selectedRowKeys.length > 0;
        const { RangePicker } = DatePicker;
        return (
            <div className="user-content" >
                <div className="content-title">
                    <span>科技需求列表</span>
                    <div className="patent-addNew">
                        <Button type="primary" onClick={this.addClick}>发布需求<Icon type="plus" /></Button>
                        <Button type="primary" onClick={this.downLoadFile}>下载批量导入模板</Button>
                        <Upload
                            action={globalConfig.context + "/api/user/demand/importDemand"}
                            data={{ 'sign': '' }}
                            showUploadList={false}
                            multiple={true}
                            onChange={(info) => {
                                message.config({
                                    top: 80,
                                });
                                if (info.file.status === 'uploading') {
                                    this.setState({
                                        uploadFileLoading: true,
                                    })
                                    if(!this.uploadFileHide){
                                        this.uploadFileHide = message.loading('文件上传中..', 0);
                                    }
                                }
                                if (info.file.status === 'done') {
                                    this.setState({
                                        uploadFileLoading: false,
                                    })
                                    this.uploadFileHide();
                                    this.uploadFileHide = null;
                                    if (!info.file.response.error.length) {
                                        message.success(`${info.file.name} 文件上传成功！`);
                                        this.loadData()
                                    } else {
                                        message.warning(info.file.response.error[0].message);
                                        return;
                                    };
                                } else if (info.file.status === 'error') {
                                    this.setState({
                                        uploadFileLoading: false,
                                    });
                                    this.uploadFileHide();
                                    this.uploadFileHide = null;
                                    message.error(`${info.file.name} 文件上传失败。`);
                                };
                            }} >
                            <Button type="primary" loading={this.state.uploadFileLoading}>上传批量导入文件</Button>
                        </Upload>
                    </div>
                </div>
                <div className="user-search">
                    <Input placeholder="需求名称"
                        value={this.state.name}
                        onChange={(e) => { this.setState({ name: e.target.value }); }} />
                    <Button type="primary" onClick={this.search}>搜索</Button>
                    <Button onClick={this.reset}>重置</Button>
                    <Button
                        type="danger"
                        disabled={!hasSelected}
                        onClick={this.delectRow}
                    >
                        删除<Icon type="minus" />
                    </Button>
                    <span>更多搜索<Switch defaultChecked={false} onChange={this.searchSwitch} /></span>
                    <div className="search-more" style={this.state.searchMore ? { display: 'none' } : {}}>
                        <span>发布时间 :</span>
                        <RangePicker
                            value={[this.state.releaseDate[0] ? moment(this.state.releaseDate[0]) : null,
                            this.state.releaseDate[1] ? moment(this.state.releaseDate[1]) : null]}
                            onChange={(data, dataString) => { this.setState({ releaseDate: dataString }); }} />
                    </div>
                </div>
                <div className="patent-table">
                    <Spin spinning={this.state.loading}>
                        <Table columns={this.state.columns}
                            dataSource={this.state.dataSource}
                            rowSelection={rowSelection}
                            pagination={this.state.pagination}
                            onRowClick={this.tableRowClick} />
                    </Spin>
                </div>
                <TechDemandDesc
                    data={this.state.RowData}
                    demandTypeOption={this.state.demandTypeOption}
                    showDesc={this.state.showDesc}
                    closeDesc={this.closeDesc} />
            </div >
        );
    }
});

export default DemandList;