import React from 'react';
import $ from 'jquery/src/ajax';
import {
	Icon,
	Tooltip,
	Modal,
	message,
	Spin,
	Upload,
	Input,
	Select,
	Button,
	Radio,
	Form,
	Cascader,
	Checkbox,
	Tag,
	Row,Col,
	InputNumber
} from 'antd';
import { citySelect } from '@/NewDicProvinceListAll';
import { splitUrl ,getReleaseStateList} from '@/tools.js';
import Editors from '@/richTextEditors';
import './business.less';

//图片组件
const PicturesWall = React.createClass({
	getInitialState() {
		return {
			previewVisible: false,
			previewImage: '',
			fileList: []
		};
	},
	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
					action={globalConfig.context + '/api/user/jtBusiness/project/uploadPicture'}
					data={{ sign: 'jt_project_picture' }}
					listType="picture-card"
					fileList={fileList}
					onPreview={this.handlePreview}
					onChange={this.handleChange}
				>
					{fileList.length >= 1 ? null : uploadButton}
				</Upload>
				<Modal maskClosable={false} visible={previewVisible} footer={null} onCancel={this.handleCancel}>
					<img alt="example" style={{ width: '100%' }} src={previewImage} />
				</Modal>
			</div>
		);
	}
});

const DemandDetailForm = Form.create()(
	React.createClass({
		getInitialState() {
			return {
				tagArr:[],
				visible: false,
				loading: false,
				auditStatus: 0,
				textFileList: [],
				videoFileList: [],
				pictureUrl: [],
				orgCodeUrl: [],
				companyLogoUrl: [],
				tags: [],
				introduce:{},
			};
		},
		//左侧图片地址
		getOrgCodeUrl(e) {
			this.setState({ orgCodeUrl: e });
		},
		//右侧图片地址
		getCompanyLogoUrl(e) {
			this.setState({ companyLogoUrl: e });
		},
		//编辑部门，保存
		handleSubmit(e,index) {
			e.preventDefault();
			if (!this.state.name) {
				message.warning('请输入项目名称');
				return;
			}
			if ((this.state.name).length>50) {
				message.warning('项目名称在50个字以内');
				return false;
			};
			if (!this.state.categoryId||!this.state.categoryId[1]) {
				message.warning('请选择项目二级业务品类');
				return;
			}
			if (!this.state.ProvinceCity.length) {
				message.warning('请选择省份');
				return;
			}
			if (!this.state.price) {
				message.warning('请输入正确的市场价');
				return;
			}
			if(this.state.advertisement&&(this.state.advertisement).length>30){
				message.warning('项目营销说明字数不得超过30个字。');
				return;
			}
			if(this.state.introduce&&(this.state.introduce.length)>10000){
				message.warning('业务项目服务内容不大于10000字')
				return;
			}
			this.setState({
				loading: true
			});
			let minPictureUrl = [];
			if (this.state.orgCodeUrl.length) {
				let picArr = [];
				this.state.orgCodeUrl.map(function(item) {
					if (item.response && item.response.data && item.response.data.length) {
						picArr.push(item.response.data);
					}
				});
				minPictureUrl = picArr.join(',');
			}
			let maxPictureUrl = [];
			if (this.state.companyLogoUrl.length) {
				let picArr = [];
				this.state.companyLogoUrl.map(function(item) {
					if (item.response && item.response.data && item.response.data.length) {
						picArr.push(item.response.data);
					}
				});
				maxPictureUrl = picArr.join(',');
			}
			$.ajax({
				method: 'post',
				dataType: 'json',
				crossDomain: false,
				url: globalConfig.context + '/api/user/jtBusiness/project/update',
				data: {
					auditStatus:index,
					id: this.state.id, //业务名称
					name: this.state.name, //业务名称
					categoryId: this.state.categoryId[1], //业务品类
					price: this.state.price, //市场价
					advertisement:this.state.advertisement,//项目营销说明
					activityPrice: this.state.activityPrice ? this.state.activityPrice : '0', //最低折扣
					memberPrice: this.state.memberPrice ? this.state.memberPrice : '0', //会员价
					offset: this.state.offset ? this.state.offset : '0',
					activityFlag: this.state.activityFlag, //活动生效标识
					province: this.state.ProvinceCity ? this.state.ProvinceCity[0] : '', //是否全国
					city: this.state.ProvinceCity ? this.state.ProvinceCity[1] : '',
					introduce: this.state.introduce,
					value: this.state.value,
					isHot: this.state.isHot,
					minImgUrl: minPictureUrl.length ? minPictureUrl : '',
					maxImgUrl: maxPictureUrl.length ? maxPictureUrl : '',
					applyConditions: this.state.applyConditions,
					tag:this.state.tagArr.join(',')
				}
			}).done(
				function(data) {
					if (!data.error.length) {
						this.setState({
							loading: false,
							editvisible: false
						});
						if(index){
							this.submission();
						}else{
							message.success('保存成功！');
						}
					} else {
						message.warning(data.error[0].message);
					}
					this.props.handOk();
				}.bind(this)
			);
		},
		loadData(ids) {
			$.ajax({
				method: 'get',
				dataType: 'json',
				crossDomain: false,
				url: globalConfig.context + '/api/user/jtBusiness/project/detail',
				data: {
					id: ids
				},
				success: function(data) {
					if (!data.data) {
						if (data.error && data.error.length) {
							message.warning(data.error[0].message);
						}
					} else {
						let categoryIdArr=[];
						let thisdata = data.data;
						let ProvinceCityArr = [];
						ProvinceCityArr.push(thisdata.province, thisdata.city);
						(this.props.categoryList).map(item=>{
							if(item.children.length){
								(item.children).map(atem=>{
									if(atem.value==thisdata.categoryId){
										categoryIdArr.push(item.value,atem.value)
									}
								})
							}
						})
						let tagFirst =thisdata.tags,tagTxt=[],tagArr=[];
						tagFirst.map(item=>{
							tagTxt.push(item.name);
							tagArr.push(item.id)
						})
						this.setState({
							id: thisdata.id, //业务名称
							name: thisdata.name, //业务名称
							tagTxt:tagTxt.join(' - '),
							tagArr:tagArr,
							categoryId: categoryIdArr, //业务品类
							number: thisdata.number,
							auditInfo:thisdata.auditInfo,
							price: thisdata.price, //市场价
							advertisement:thisdata.advertisement,
							activityPrice: thisdata.activityPrice ? thisdata.activityPrice : '', //最低折扣
							memberPrice: thisdata.memberPrice ? thisdata.memberPrice : '', //会员价
							offset: thisdata.offset ? thisdata.offset : '',
							activityFlag: thisdata.activityFlag ? thisdata.activityFlag.toString() : '', //活动生效标识
							ProvinceCity: ProvinceCityArr,
							introduce: thisdata.introduce,
							createTime: thisdata.createTime ? new Date(thisdata.createTime).toLocaleString() : '',
							value: thisdata.value,
							isHot:thisdata.isHot,
							auditStatus:thisdata.auditStatus,
							applyConditions: thisdata.applyConditions,
							orgCodeUrl: thisdata.minImgUrl
								? splitUrl(thisdata.minImgUrl, ',', globalConfig.avatarHost + '/upload')
								: [],
							companyLogoUrl: thisdata.maxImgUrl
								? splitUrl(thisdata.maxImgUrl, ',', globalConfig.avatarHost + '/upload')
								: []
						});
					}
				}.bind(this)
			}).always(
				function() {
					this.setState({
						loading: false
					});
				}.bind(this)
			);
		},
		submission(e) {
			$.ajax({
				method: 'get',
				dataType: 'json',
				crossDomain: false,
				async: true,
				url: globalConfig.context + '/api/user/jtBusiness/project/publish',
				data: {
					id: this.state.id,
					auditStatus:1
				}
			}).done(
				function(data) {
					if (!data.error.length) {
						message.success('提交成功,请耐心等待审核结果.')
						this.setState({
							loading: false
						});
					} else {
						message.warning(data.error[0].message);
					}
				}.bind(this)
			);
		},
		cancelFun() {
			this.props.closeDesc();
		},
		componentWillMount() {
			if (this.props.data.id) {
				this.state.introduce='<p><br></p>';
				this.loadData(this.props.data.id);
			}
		},
		//标签
		tagOk(){
			this.setState({
				visibleTag:false
			})
		},
		tagCancel(){
			this.setState({
				visibleTag:false
			})
		},
		selTag(){
			this.setState({
				visibleTag:true
			})
			this.state.tagArr=this.state.tagArr;
		},
		onChange(e){
			this.setState({
				tagArr:e
			})
		},
		tagSubmit(e){
			e.preventDefault();
			let tags =[];
			(this.props.tagList).map(item=>{
				for(let i=0;i<(this.state.tagArr).length;i++){
					if(item.id==(this.state.tagArr[i])){
						tags.push(item.name)
					}
				}
			})
			this.tagCancel();
			this.setState({
				tagTxt:tags.join(' - ')
			})
		},
		//发布后查看效果
		lookSee(e){
			e.preventDefault();
			if (!this.state.name) {
				message.warning('请输入项目名称');
				return;
			}
			if ((this.state.name).length>16) {
				message.warning('项目名称在16个字以内');
				return false;
			};
			if (!this.state.categoryId||!this.state.categoryId[1]) {
				message.warning('请选择项目二级业务品类');
				return;
			}
			if (!this.state.ProvinceCity.length) {
				message.warning('请选择省份');
				return;
			}
			if (!this.state.price) {
				message.warning('请输入正确的市场价');
				return;
			}
			if(this.state.advertisement&&(this.state.advertisement).length>30){
				message.warning('项目营销说明字数不得超过30个字.');
				return;
			}
			this.setState({
				loading: true
			});
			let minPictureUrl = [];
			if (this.state.orgCodeUrl.length) {
				let picArr = [];
				this.state.orgCodeUrl.map(function(item) {
					if (item.response && item.response.data && item.response.data.length) {
						picArr.push(item.response.data);
					}
				});
				minPictureUrl = picArr.join(',');
			}
			let maxPictureUrl = [];
			if (this.state.companyLogoUrl.length) {
				let picArr = [];
				this.state.companyLogoUrl.map(function(item) {
					if (item.response && item.response.data && item.response.data.length) {
						picArr.push(item.response.data);
					}
				});
				maxPictureUrl = picArr.join(',');
			}
			$.ajax({
				method: 'post',
				dataType: 'json',
				crossDomain: false,
				url: globalConfig.context + '/api/user/jtBusiness/project/update',
				data: {
					id: this.state.id, //业务名称
					name: this.state.name, //业务名称
					categoryId: this.state.categoryId[1], //业务品类
					price: this.state.price, //市场价
					advertisement:this.state.advertisement,//项目营销说明
					activityPrice: this.state.activityPrice ? this.state.activityPrice : '0', //最低折扣
					memberPrice: this.state.memberPrice ? this.state.memberPrice : '0', //会员价
					offset: this.state.offset ? this.state.offset : '0',
					activityFlag: this.state.activityFlag, //活动生效标识
					province: this.state.ProvinceCity ? this.state.ProvinceCity[0] : '', //是否全国
					city: this.state.ProvinceCity ? this.state.ProvinceCity[1] : '',
					introduce: this.state.introduce,
					value: this.state.value,
					isHot: this.state.isHot,
					minImgUrl: minPictureUrl.length ? minPictureUrl : '',
					maxImgUrl: maxPictureUrl.length ? maxPictureUrl : '',
					applyConditions: this.state.applyConditions,
					tag:this.state.tagArr.join(',')
				}
			}).done(
				function(data) {
					if (!data.error.length) {
						this.setState({
							loading: false,
						});
						message.success('提交预览请求成功,即将跳转预览页面');
						setTimeout(()=>{
							window.open(globalConfig.context+'/portal/service/patentDetail?id='+this.state.id)
						},1000)
					} else {
						message.warning(data.error[0].message);
					}
				}.bind(this)
			);
		},
		componentWillReceiveProps(nextProps) {
			if (!this.props.visible && nextProps.visible) {
				this.state.textFileList = [];
				this.state.videoFileList = [];
				if (nextProps.data.id) {
					    this.state.introduce='<p><br></p>';
						this.loadData(nextProps.data.id);
					}
				}
			},
		render() {
			const FormItem = Form.Item;
			const formItemLayout = {
				labelCol: { span: 6 },
				wrapperCol: { span: 16 },
			};
			let categoryList = this.props.categoryList||[];
			let plainOptions= this.props.tagList||[];
			return (
				<div className="patent-desc">
					<Form layout="horizontal" onSubmit={(e)=>{this.handleSubmit(e,0)}} id="demand-form">
						<Spin spinning={this.state.loading}>
							<div className="clearfix" style={{ paddingLeft: '86px' }}>
								<FormItem
									className="half-item"
									labelCol={{ span: 4 }}
									wrapperCol={{ span: 12 }}
									label={
										<span>
											<strong style={{ color: 'red' }}>*</strong>项目名称
										</span>
									}
								>
									<Input
										placeholder="项目名称"
										value={this.state.name}
										onChange={(e) => {
											this.setState({ name: e.target.value });
										}}
									/>
								</FormItem>
								<FormItem
									className="half-item"
									labelCol={{ span: 4 }}
									wrapperCol={{ span: 12 }}
									label={
										<span>
											<strong style={{ color: 'red' }}>*</strong>业务品类
										</span>
									}
								>
									<Cascader
										options={categoryList}
										value={this.state.categoryId}
										placeholder="业务品类"
										onChange={(e, pre) => {
											this.setState({ categoryId: e });
										}}
									/>
								</FormItem>
							</div>
							<div className="clearfix" style={{ paddingLeft: '86px' }}>
								<FormItem
									className="half-item"
									labelCol={{ span: 4 }}
									wrapperCol={{ span: 12 }}
									label={
										<span>
											<strong style={{ color: 'red' }}>*</strong>省-市
										</span>
									}
								>
									<Cascader
										options={citySelect()}
										value={this.state.ProvinceCity}
										placeholder="选择市"
										onChange={(e, pre) => {
											this.setState({ ProvinceCity: e });
										}}
									/>
								</FormItem>
								<FormItem
									className="half-item"
									labelCol={{ span: 4 }}
									wrapperCol={{ span: 12 }}
									label={
										<span>
											<strong style={{ color: 'red' }}>*</strong>热点
										</span>
									}
								>
									<Radio.Group
										onChange={(e) => {
											this.setState({ isHot: e.target.value });
										}}
										value={this.state.isHot}
									>
										<Radio value={0}>否</Radio>
										<Radio value={1}>是</Radio>
									</Radio.Group>
								</FormItem>
							</div>
							<div className="clearfix" style={{ paddingLeft: '86px' }}>
								<FormItem
									className="half-item"
									labelCol={{ span: 4 }}
									wrapperCol={{ span: 12 }}
									label={
										<span>
											<strong style={{ color: 'red' }}>*</strong>市场价
										</span>
									}
								>
									<InputNumber
										placeholder="市场价"
										value={this.state.price}
										style={{ width: 120 }}
										onChange={(e) => {
											this.setState({ price: e });
										}}
										required="required"
									/>
									<span style={{ marginLeft: 10 }}>万元</span>
								</FormItem>
								<FormItem
									className="half-item"
									labelCol={{ span: 4 }}
									wrapperCol={{ span: 12 }}
									label="活动价"
								>
									<InputNumber
										placeholder="活动价"
										value={this.state.activityPrice}
										style={{ width: 120 }}
										onChange={(e) => {
											this.setState({ activityPrice: e });
										}}
										min={0}
										max={999999}
										step={0.01}
									/>
									<span style={{ marginLeft: 10 }}>万元</span>
								</FormItem>
								<FormItem
									className="half-item"
									labelCol={{ span: 4 }}
									wrapperCol={{ span: 12 }}
									label="最低折扣"
								>
									<InputNumber
										placeholder="最低折扣(如:0.5)"
										value={this.state.offset}
										style={{ width: '50%' }}
										onChange={(e) => {
											this.setState({ offset: e });
										}}
										min={0}
										max={1}
										step={0.01}
									/>
								</FormItem>
								<FormItem
									className="half-item"
									labelCol={{ span: 4 }}
									wrapperCol={{ span: 12 }}
									label="会员价"
								>
									<InputNumber
										placeholder="会员价"
										value={this.state.memberPrice}
										style={{ width: '120px' }}
										onChange={(e) => {
											this.setState({ memberPrice: e });
										}}
										min={0}
										max={999999}
										step={0.01}
									/>
									<span style={{ marginLeft: 10 }}>万元</span>
								</FormItem>
								<FormItem
									className="half-item"
									labelCol={{ span: 4 }}
									wrapperCol={{ span: 12 }}
									label="活动生效"
								>
									<Select
										placeholder="活动生效"
										value={this.state.activityFlag}
										style={{ width: '94%' }}
										onChange={(e) => {
											this.setState({ activityFlag: e });
										}}
									>
										<Select.Option key="0">无效</Select.Option>
										<Select.Option key="1">有效</Select.Option>
									</Select>
								</FormItem>
								<FormItem
									className="half-item"
									labelCol={{ span: 4 }}
									wrapperCol={{ span: 12 }}
									label="创建时间"
								>
									<span style={{ width: '94%' }}>{this.state.createTime}</span>
								</FormItem>
							</div>	
							<div className="clearfix">
								<FormItem
									labelCol={{ span: 4 }}
									wrapperCol={{ span: 12 }}
									label="标签">
										<div>
											<span style={{marginRight:10}}>{this.state.tagTxt}</span>
											<Button onClick={this.selTag}>选择</Button>
										</div>
								</FormItem>
							</div>	
							<div>
								<FormItem
									labelCol={{ span: 4 }}
									wrapperCol={{ span: 12 }}
									label="发布状态">
										<span>{getReleaseStateList(this.state.auditStatus)}</span>
								</FormItem>
							</div>
							<div className="clearfix">
								{this.state.auditInfo?<FormItem
									labelCol={{ span: 4 }}
									wrapperCol={{ span: 12 }}
									label="拒绝原因">
										<span>{this.state.auditInfo}</span>
								</FormItem>:''}
							</div>
							<div className="clearfix">
								<FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 12 }} label="项目营销说明">
									<Input
										type="textarea"
										rows={4}
										placeholder="项目营销说明"
										value={this.state.advertisement}
										onChange={(e) => {
											this.setState({ advertisement: e.target.value });
										}}
									/>
								</FormItem>
							</div>
							<div className="clearfix">
								<FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 12 }} label="业务项目价值及作用">
									<Input
										type="textarea"
										rows={4}
										placeholder="业务项目价值及作用"
										value={this.state.value}
										onChange={(e) => {
											this.setState({ value: e.target.value });
										}}
									/>
								</FormItem>
							</div>
							<div className="clearfix">
								<FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 12 }} label="业务项目客户基本条件">
									<Input
										type="textarea"
										rows={4}
										placeholder="业务项目客户基本条件"
										value={this.state.applyConditions}
										onChange={(e) => {
											this.setState({ applyConditions: e.target.value });
										}}
									/>
								</FormItem>
							</div>
							<div className="clearfix">
								<FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 16 }} label='业务项目服务内容'>
									<Editors textContent={this.state.introduce}
										uploadUrl={'/api/user/demand/uploadPicture'}
										uploadSign={'demand_picture'}
										handleRichText={(value) => { this.state.introduce = value;  }}
										visible={this.state.visible} />
										<Button type="dashed" onClick={this.lookSee} style={{marginTop:10}}>预览发布后效果</Button>
								</FormItem>
							</div>
							<div className="clearfix pictures">
								<FormItem
									className="half-item"
									labelCol={{ span: 8 }}
									wrapperCol={{ span: 10 }}
									label="业务项目图标(小)"
								>
									<PicturesWall
										pictureSign="business_project_min_picture"
										fileList={this.getOrgCodeUrl}
										pictureUrl={this.state.orgCodeUrl}
									/>
									<p>图片建议：图片要清晰。(72*72)</p>
								</FormItem>
								<FormItem
									className="half-item"
									labelCol={{ span: 8 }}
									wrapperCol={{ span: 12 }}
									label="业务项目图标(大)"
								>
									<PicturesWall
										pictureSign="business_project_max_picture"
										fileList={this.getCompanyLogoUrl}
										pictureUrl={this.state.companyLogoUrl}
									/>
									<p>图片建议：图片要清晰。(330*230)</p>
								</FormItem>
							</div>
							<Button
								className="set-submit"
								type="primary"
								htmlType="submit"
								style={{ marginLeft: '160px', marginBottom: '20px', marginTop: '20px' }}
							>
								保存
							</Button>
							<Button
								className="set-submit"
								type="ghost"
								onClick={(e) => {
									this.handleSubmit(e,1)
								}}
							>
								提交审核
							</Button>
							<Button
								className="set-submit"
								type="ghost"
								onClick={this.cancelFun}
							>
								取消
							</Button>
						</Spin>
					</Form>
					<Modal
						maskClosable={false}
						visible={this.state.visibleTag}
						onOk={this.tagOk}
						onCancel={this.tagCancel}
						width="450px"
						title="新建标签"
						footer=""
					>
						<Form layout="horizontal" onSubmit={(e)=>{this.tagSubmit(e)}} id="demand-form">
							<Form.Item  {...formItemLayout} label={<span><strong style={{color:'#f00'}}> * </strong>标签</span>}>
								<Checkbox.Group 
									value={this.state.tagArr}
									onChange={this.onChange}>
									<Row>
										{plainOptions.map((item)=>{
											return <Col span={8} key={item.id} ><Checkbox  value={item.id}>{item.name}</Checkbox></Col>
										})}
									</Row>
								</Checkbox.Group>
							</Form.Item>
							<div className="clearfix">
								<Form.Item wrapperCol={{ span: 12, offset: 6 }}>
									<Button className="set-submit" type="primary" htmlType="submit">
										选定
									</Button>
									<Button className="set-submit" type="ghost" onClick={this.tagCancel}>
										取消
									</Button>
								</Form.Item>
							</div>
						</Form>
					</Modal>
				</div>
			);
		}
	})
);
export default DemandDetailForm;
