import React from 'react';
import $ from 'jquery/src/ajax';
import 'react-quill/dist/quill.bubble.css';
import moment from 'moment';
import {Form,Icon,Button,Input,Select,Spin,Table,message,DatePicker,Modal,Upload,Popconfirm,Cascader,InputNumber,Radio,TimePicker,Tabs} from 'antd';
import {areaSelect, getProvince} from '@/NewDicProvinceList';//省市区
import { getGameState, splitUrl, getprovince,getBuyAuditType , getStatuslist, getLvl,beforeUploadFile,getSecretType} from '@/tools.js';
import Editors from '@/richTextEditors';
const PicturesWall = React.createClass({
    getInitialState() {
        return {
            previewVisible: false,
            previewImage: '',
            fileList: this.props.pictureUrl,
        }
    },
    getDefaultProps(){
    	return{
    		changeClick:this.modifyChange
    	}
    },
    handleCancel() {
        this.setState({ previewVisible: false })
    },
    handlePreview(file) {
        this.setState({
            previewImage: file.url || file.thumbUrl,
            previewVisible: true,
        });
    },
    handleChange(info) {
        let fileList = info.fileList;
        this.setState({ fileList });
        this.props.fileList(fileList);
    },
    componentWillReceiveProps(nextProps) {
        this.state.fileList = nextProps.pictureUrl; 
    },
    render() {
        const { previewVisible, previewImage, fileList } = this.state;
        const uploadButton = (
            <div>
                <Icon type="plus" />
                <div className="ant-upload-text">点击上传</div>
            </div>
        );
        return (
            <div style={{display:"inline-block"}}>
                <Upload
                	beforeUpload={beforeUploadFile}
                    action={globalConfig.context + "/api/admin/news/upload"}
                    data={{ 'sign': 'news_title_picture' }}
                    listType="picture-card"
                    fileList={fileList}
                    onPreview={this.handlePreview}
                    onChange={this.handleChange} >
					{fileList.length >= 18 ? null : uploadButton}
                </Upload>
                <Modal maskClosable={false} visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                    <img alt="example" style={{ width: '100%' }} src={previewImage} />
                </Modal>
            </div>
        );
    }
});
//主体
const NewList = Form.create()(
	React.createClass({
		loadData(pageNo) {
			this.state.data = [];
			this.setState({
				loading: true,
				page: pageNo
			});
			$.ajax({
				method: 'get',
				dataType: 'json',
				crossDomain: false,
				url: globalConfig.context + '/api/admin/news/list',
				data: {
					pageNo: pageNo || 1,
					pageSize: this.state.pagination.pageSize,
					type: this.state.typeSearch,
					title: this.state.titleSearch,
					releaseStatus: this.state.releaseStatusSearch,
					startCreateTime: this.state.startCreateTimeSearch,
					endCreateTime: this.state.endCreateTimeSearch,
				},
				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,
								title: thisdata.title,
								type: thisdata.type,
								author: thisdata.author,
								releaseStatus: thisdata.releaseStatus,
								topNumber: thisdata.topNumber,
								sortNumber: thisdata.sortNumber,
								hotspot: thisdata.hotspot,
								releaseDate:thisdata.releaseDate,
								userName:thisdata.userName,
							});
						}
						this.state.pagination.current = data.data.pageNo;
						this.state.pagination.total = data.data.totalCount;
					}
					this.setState({
						dataSource: theArr,
						pagination: this.state.pagination
					});
				}.bind(this)
			}).always(
				function() {
					this.setState({
						loading: false
					});
				}.bind(this)
			);
		},
		getInitialState() {
			return {
				loading: false,
				flag: true,
				timesArr:[],
				totalData:{
					mark: false,
					content:"<p></p>",
				},
				classList: [],
				titleImg: [],
				pagination: {
					defaultCurrent: 1,
					defaultPageSize: 10,
					showQuickJumper: true,
					pageSize: 10,
					onChange: function(page) {
						this.loadData(page);
						this.setState({
							selectedRowKeys: []
						});
					}.bind(this),
					showTotal: function(total) {
						return '共' + total + '条数据';
					}
				},
				columns: [
					{
						title: '序号',
						dataIndex: 'key',
						key: 'key'
					},
					{
						title: '标题',
						dataIndex: 'title',
						key: 'title'
					},
					{
						title: '类型',
						dataIndex: 'type',
						key: 'type',
						render:(text,record)=>{
							if (text !== undefined) {
								let value = '';
								this.state.classList.map((obj)=>{
									if (obj.showNumber === text) {
										value = obj.typeName;
									}
								})
								return value;
							}
						}
					},
					{
						title: '发布状态',
						dataIndex: 'releaseStatus',
						key: 'releaseStatus',
						render:text=>{
							return text?'已发布':'未发布';
						}
					},
					{
						title: '发布时间',
						dataIndex: 'releaseDate',
						key: 'releaseDate'
					},
					{
						title: '排序',
						dataIndex: 'sortNumber',
						key: 'sortNumber'
					},
					{
						title: '置顶',
						dataIndex: 'topNumber',
						key: 'topNumber',
						render:text=>{
							return text?'否':'是';
						}
					},
					{
						title: '操作',
						dataIndex: 'a',
						key: 'a',
						render:(text,record,index)=>{
							return <div>
										{<Button type="primary" onClick={(event)=>{
											this.stopPropagation(event)
											this.tableRowClick(record)
										}}>修改</Button>}
										{<Popconfirm okText="确定" cancelText="取消" title="是否确认删除？" onConfirm={()=>{
											this.delete(record.id)
										}}>
											<Button type="primary" style={{marginLeft:"10px"}} onClick={(event)=>{
												this.stopPropagation(event)
											}}>删除</Button>
										</Popconfirm>}
									</div>
						}
					},
				],
				dataSource: []
			};
		},
		
		classList(pageNo) {
			$.ajax({
				method: 'get',
				dataType: 'json',
				crossDomain: false,
				url: globalConfig.context + '/api/admin/news/ListNewsType',
				data: {
					pageNo: 1,
					pageSize: 99,
				},
				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,
								typeName: thisdata.typeName,
								showNumber: thisdata.showNumber,
							});
						}
						this.state.pagination.current = data.data.pageNo;
						this.state.pagination.total = data.data.totalCount;
					}
					this.setState({
						classList: theArr,
					});
				}.bind(this)
			}).always(
				function() {
					this.setState({
						loading: false
					});
				}.bind(this)
			);
		},
		
		componentWillMount() {
			this.loadData()
			this.classList()
		},
		detailes(record) {
			this.setState({
				loading:true
			});
			$.ajax({
				method: 'get',
				dataType: 'json',
				crossDomain: false,
				url: globalConfig.context + '/api/admin/news/detail',
				data: {
					id: record.id,
				},
				success: function(data) {
					let theArr = [];
					let thisdata = data.data;
					if (!data.data || !data.data.list) {
						if (data.error && data.error.length) {
							message.warning(data.error[0].message);
						}
					}
					this.setState({
						titleImg: thisdata.titleImg ? splitUrl(thisdata.titleImg, ',', globalConfig.avatarHost + '/upload') : [],
					})
					Object.assign(this.state.totalData,{
							content:thisdata.content,
							createTimes:thisdata.createTimes,
							editTimes:thisdata.editTimes,
							releaseDates:thisdata.releaseDates,
					},this.state.RowData)
				}.bind(this)
			}).always(
				function() {
					this.setState({
						loading: false
					});
				}.bind(this)
			);
		},
		
		stopPropagation(e){
			e.stopPropagation();
			e.nativeEvent.stopImmediatePropagation();
		},
		
		//项目列表整行点击
		tableRowClick(record, index) {
			this.state.RowData = record;
			this.setState({
				editvisible: true,
			});
			this.detailes(record);
		},
		edithandleCancel(e) {
			this.setState({
				editvisible: false
			},()=>{
				this.addReset()
			});
			this.loadData()
		},
		
		search() {
			this.loadData();
		},
		
		add(){
			this.setState({
				editvisible: true,
				flag: false,
			});
		},
		addNew(){
			let theorgCodeUrl = [];
			if (this.state.titleImg.length) {
			    let picArr = [];
			    this.state.titleImg.map(function (item) {
					if ( item.response && item.response.data && item.response.data.length ){
						picArr.push(item.response.data);
					}
			    });
			    theorgCodeUrl = picArr.join(",");
			};
			this.setState({
				loading:true
			});
			if (!this.state.flag) {
				this.change("auditStatus",2)
			}
			if(theorgCodeUrl.length){
				this.change("titleImg",theorgCodeUrl)
			}else{
				this.change("titleImg",[])
			}
			$.ajax({
				method: 'post',
				dataType: 'json',
				crossDomain: false,
				url: (this.state.flag?'/api/admin/news/update':'/api/admin/news/apply'),
				data:  this.state.totalData,
			}).done(function(data) {
			this.setState({
				loading: false
			});
			if(!data.error.length) {
				message.success('保存成功！');
				this.cancelAdd()
			} else {
				message.warning(data.error[0].message);
			}
		}.bind(this));
		},
		
		saveNew(){
			this.change("releaseStatus",0,()=>{
				this.addNew()
			})
		},
		
		issueNew(){
			this.change("releaseStatus",1,()=>{
				this.addNew()
			})
		},
		
		delete(id){
			this.setState({
					loading:true
				});
				$.ajax({
					method: 'post',
					dataType: 'json',
					crossDomain: false,
					url: "/api/admin/news/deleteById",
					data: {
						id: id,
					},
				}).done(function(data) {
				this.setState({
					loading: false
				});
				if(!data.error.length) {
					message.success('删除成功！');
					this.loadData()
				} else {
					message.warning(data.error[0].message);
				}
			}.bind(this));
		},
		
		cancelAdd(){
			this.setState({
				editvisible: false,
			},()=>{
				this.setState({
					flag:true
				})
				this.addReset()
			});
			this.loadData()
		},
		
		//新增框的清零
		addReset(){
			this.setState({
				titleImg:[],
				totalData:{
					content:"<p></p>",
				},
			})
		},
		//搜索部分的清零
		reset() {
			this.setState({
				releaseStatusSearch: undefined,
				typeSearch: undefined,
				startCreateTimeSearch: undefined,
				endCreateTimeSearch: undefined,
				titleSearch: undefined,
			})
			this.loadData();
		},
		getOrgCodeUrl(e) {
		    this.setState({ titleImg: e });
		},
		
		change(key, e, f){
			if(f === undefined ){
				this.state.totalData[key] = e
				this.setState({
					totalData:this.state.totalData
				})
			}else if(typeof(f) === "function"){
				this.state.totalData[key] = e
				this.setState({
					totalData:this.state.totalData
				},f)
			}
		},
		
		render() {
			const FormItem = Form.Item;
			const rowSelection = {
				selectedRowKeys: this.state.selectedRowKeys,
				onChange: (selectedRowKeys, selectedRows) => {
					this.setState({
						selectedRows: selectedRows.slice(-1),
						selectedRowKeys: selectedRowKeys.slice(-1)
					});
				}
			};
			let data = this.state.totalData;
			const { TextArea } = Input;//文本域
			const { TabPane } = Tabs;//标签页
			const { MonthPicker, RangePicker, WeekPicker } = DatePicker;//日期输入框
			return (
				<div className="user-content">
					<div className="content-title">
						<span>新闻列表管理</span>
						<div className="user-search">
							<Input
								placeholder="企业名称"
								style={{ width: '150px', marginRight: '10px', marginBottom: '10px' }}
								value={this.state.nameSearch}
								onChange={(e) => {
									this.setState({ nameSearch: e.target.value });
								}}
							/>
							<Button type="primary" onClick={this.search} style={{ marginRight: '10px' }}>
								搜索
							</Button>
							<Button onClick={this.reset} style={{ marginRight: '10px' }}>
								重置
							</Button>
							<Button type="primary" onClick={this.add} style={{ marginLeft: '100px'}}>
								新增新闻
							</Button>
						</div>
						<div className="patent-table">
							<Spin spinning={this.state.loading}>
								<Table
									columns={this.state.columns}
									dataSource={this.state.dataSource}
									pagination={this.state.pagination}
									onRowClick={this.tableRowClick}
								/>
							</Spin>
						</div>
					</div>
					<div className="patent-desc">
						<Modal
							className="customeDetails"
							title={this.state.flag?'新闻列表详情':'新增新闻列表'}
							width="1000px"
							visible={this.state.editvisible}
							onOk={this.edithandleCancel}
							onCancel={this.state.flag?this.edithandleCancel:this.cancelAdd}
							footer=""
						>
							<Form layout="horizontal" onSubmit={this.edithandleSubmit} id="demand-form">
								<Spin spinning={this.state.loading}>
									<div className="clearfix">
										<FormItem
											className="half-item"
											labelCol={{ span: 8 }}
											wrapperCol={{ span: 12 }}
											label="新闻标题"
										>
											<Input placeholder="请输入新闻标题" value={data.title}
											    	onChange={(e)=>{
														this.change('title',e.target.value)
													}} style={{width:'240px'}} />
										</FormItem>
										<FormItem
											className="half-item"
											labelCol={{ span: 8 }}
											wrapperCol={{ span: 12 }}
											label="新闻类别"
										>
											<Select value={data.type} style={{ width: 120 }}
														placeholder='请选择新闻类别' onChange={(e)=>{
															this.change('type',e)
														}}>
												{this.state.classList.map((obj)=>{
													return <Option value={obj.showNumber}>{obj.typeName}</Option>
												})}
											</Select>
										</FormItem>
										<FormItem
											className="half-item"
											labelCol={{ span: 8 }}
											wrapperCol={{ span: 12 }}
											label="排序"
										>
											<Input placeholder="请输入排序" value={data.sortNumber}
											    	onChange={(e)=>{
														this.change('sortNumber',e.target.value)
													}} style={{width:'240px'}} />
										</FormItem>
										<FormItem
											className="half-item"
											labelCol={{ span: 8 }}
											wrapperCol={{ span: 12 }}
											label="是否置顶"
										>
											<Radio.Group onChange={(e)=>{
												this.change('topNumber',e.target.value)
											}} value={data.topNumber}>
												<Radio value={0}>是</Radio>
												<Radio value={1}>否</Radio>
											</Radio.Group>
										</FormItem>
									</div>	
										<div className="clearfix">
											<FormItem
											    labelCol={{ span: 4 }}
											    wrapperCol={{ span: 18 }}
											    label='新闻大图'
											    >
											    <PicturesWall
											        fileList={this.getOrgCodeUrl}
											        pictureUrl={this.state.titleImg} />
											        <p>图片建议：要清晰。</p>
											</FormItem>
										</div>
										<div className="clearfix">
											<FormItem
											    labelCol={{ span: 4 }}
											    wrapperCol={{ span: 18 }}
											    label='新闻内容'
											    >
												<Editors textContent={data.content}
													uploadUrl={'/api/admin/militaryEnterprises/uploadPicture'}
													uploadSign={'enterprises_pucture'}
													handleRichText={(value)=>{
															this.change('content',value)
														}}
													visible={data.visible} />
											</FormItem>
										</div>
										<div className="clearfix">
											{!data.releaseStatus?<Button type="primary" size="large" onClick={this.saveNew} style={{float:'right',marginRight:'80px',marginTop:'20px'}}>保存</Button>:
											<Button type="primary" size="large" onClick={this.saveNew} style={{float:'right',marginRight:'80px',marginTop:'20px',background:'coral',border:'none'}}>撤回</Button>}
											<Button type="primary" size="large" onClick={this.issueNew} style={{float:'right',marginRight:'20px',marginTop:'20px'}}>保存并发布</Button>
										</div>
								</Spin>
							</Form>
						</Modal>
					</div>
				</div>
			);
		}
	})
);

export default NewList;
