import React from 'react';
import $ from 'jquery/src/ajax';
import { citySelect } from '@/NewDicProvinceListAll';
import {
	Form,
	Icon,
	Button,
	Input,
	Table,
	message,
	DatePicker,
	Modal,
	Radio,
	Cascader,
} from 'antd';
import { getGameState, getprovince, getReleaseStateList } from '@/tools.js';
import TechDemandDesc from '@/account/business/businessDesc';
import SpinContainer from "../../SpinContainer";
//主体
const BusinessProject = 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 + '/portal/service/jtProject/list',
				data: {
					pageNo: pageNo || 1,
					pageSize: this.state.pagination.pageSize,
					topId: this.state.typeSearch? this.state.typeSearch[0]:'',
					secondId:this.state.typeSearch?this.state.typeSearch[1]:'',
					name: this.state.nameSearch,
					privateProject: 0
				},
				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],
								ProvinceCityArr = [],
								cname = '',
								superName = '',
								ProvinceS = thisdata.province, //getprovince
								citys = thisdata.city,
								Areas = thisdata.area;
							ProvinceCityArr.push(ProvinceS, citys, Areas);
							(this.state.categoryList).map((item,index) => {
								if((item.children).length){
									(item.children).map((atem,indexT)=>{
										if (thisdata.categoryId == atem.value) {
											console.log()
											cname = item.label;
											superName = atem.label;
											return;
										}
									})
								}
							});
							theArr.push({
								key: i,
								id: thisdata.id, //业务名称
								name: thisdata.name, //业务名称
								categoryId: thisdata.categoryId, //业务品类
								number: thisdata.number,
								price: thisdata.price, //市场价
								superName: superName,
								cname: cname,
								auditStatus: thisdata.auditStatus,
								city: thisdata.city,
								activityPrice: thisdata.activityPrice ? thisdata.activityPrice : '', //最低折扣
								memberPrice: thisdata.memberPrice ? thisdata.memberPrice : '', //会员价
								offset: thisdata.offset ? thisdata.offset : '',
								activityPrice: thisdata.activityPrice ? thisdata.activityPrice : '', //活动价
								activityFlag: thisdata.activityFlag, //活动生效标识
								status: thisdata.status, //项目状态
								province: thisdata.province,
								introduce: thisdata.introduce,
								createTime: thisdata.createTime ? new Date(thisdata.createTime).toLocaleString() : '',
								value: thisdata.value,
								applyConditions: thisdata.applyConditions,
								releaseDate:thisdata.releaseDate?(new Date(thisdata.releaseDate)).toLocaleString():''
							});
						}
						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 {
				tagList:[],
				searchMore: true,
				selectedRowKeys: [],
				selectedRows: [],
				loading: false,
				typeSearch:[],
				orgCodeUrl: [],
				companyLogoUrl: [],
				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: 'name',
						key: 'bname'
					},
					{
						title: '品类名称',
						dataIndex: 'cname',
						key: 'cname'
					},
					{
						title: '上级品类',
						dataIndex: 'superName',
						key: 'superName'
					},
					{
						title: '业务地区',
						dataIndex: 'area',
						key: 'area',
						render: (text, rocard) => {
							return (
								<div>
									{rocard.province != 0 ? (
										<span>{getprovince(rocard.province) + '-' + getprovince(rocard.city)}</span>
									) : (
										'全国'
									)}
								</div>
							);
						}
					},
					{
						title: '市场价(万元)',
						dataIndex: 'price',
						key: 'price'
					},
					{
						title: '最低折扣',
						dataIndex: 'offset',
						key: 'offset'
					},
					{
						title: '会员价(万元)',
						dataIndex: 'memberPrice',
						key: 'memberPrice'
					},
					{
						title: '活动价(万元)',
						dataIndex: 'activityPrice',
						key: 'activityPrice'
					},
					{
						title: '发布状态',
						dataIndex: 'auditStatus',
						key: 'auditStatus',
						render: (text) => {
							return getReleaseStateList(text);
						}
					},
					{
						title: '发布时间',
						dataIndex: 'releaseDate',
						key: 'releaseDate'
					},
					{
						title: '活动生效标识',
						dataIndex: 'activityFlag',
						key: 'activityFlag',
						render: (text) => {
							return getGameState(text);
						}
					},
					{
						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: []
			};
		},
		//提交审核
		submission(record) {
			this.setState({
				showDesc: false,
				loading: true
			});
			$.ajax({
				method: 'get',
				dataType: 'json',
				crossDomain: false,
				url: globalConfig.context + '/api/user/jtBusiness/project/publish',
				data: {
					id: record.id,
					auditStatus:1
				}
			}).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)
			);
		},
		//业务品类列表获取
		topLevel() {
			$.ajax({
				method: 'get',
				dataType: 'json',
				crossDomain: false,
				url: globalConfig.context + '/portal/service/jtBusiness/getCategoryList',
				data: {

				},
				success: function(data) {
					let theArr = [],thisdata=data.data;
					if (!data.data) {
						if (data.error && data.error.length) {
							message.warning(data.error[0].message);
						}
					} else {
						thisdata.map((item,index) => {
							theArr.push({
								'value':item.topLevelId,
								'label':item.topLevel,
								'children':[]
							})
							if (item.children) {
								item.children.map(atem => {
									(theArr[index].children).push({
										'value':atem.id,
										'label':atem.name
									})
								})
							}
						})
					}
					this.setState({
						categoryList: theArr,
					});
					this.loadData();
				}.bind(this)
			}).always(
				function() {
					this.setState({
						loading: false
					});
				}.bind(this)
			);
		},
		//刷新发布
		updateFun(recard){
			this.setState({
				loading:true
			})
			$.ajax({
				method: "get",
				dataType: "json",
				crossDomain: false,
				url: globalConfig.context +'/api/user/jtBusiness/project/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: "get",
				dataType: "json",
				crossDomain: false,
				url: globalConfig.context +  '/api/user/jtBusiness/project/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));
		},
		loadTag(){
			$.ajax({
				method: 'get',
				dataType: 'json',
				crossDomain: false,
				url: globalConfig.context + '/api/user/jtBusiness/tag/list',
				data: {
					pageNo:  1,
					pageSize:9999,
				},
				success:function(data){
					if(!data.data&&data.data.list.length){
						if(data.error&&data.error.length){
							message.error(data.error[0].message)
							return;
						}
					}else{
						let thisdata = data.data.list,theDate=[];
						thisdata.map((item,index)=>{
							theDate.push({
								key:index,
								id:item.id,
								name:item.name
							})
						})
						this.setState({
							tagList:theDate
						})
					}
				}.bind(this)
			})
		},
		componentWillMount() {
			this.loadTag();
			this.topLevel();
		},

		//项目列表整行点击
		tableRowClick(record, index) {
			this.state.RowData = record;
			this.setState({
				showDesc: true
			});
		},
		//新增一个项目，保存
		addhandleSubmit(e) {
			e.preventDefault();
			if (!this.state.categoryName) {
				message.warning('请输入项目名称');
				return false;
			};
			if (this.state.categoryName.length>16) {
				message.warning('项目名称在16个字以内');
				return false;
			};
			if (!this.state.addCid||!this.state.addCid[1]) {
				message.warning('请选择项目二级品类');
				return false;
			}
			this.setState({
				loading: true
			});
			//上级组织字典
			$.ajax({
				method: 'post',
				dataType: 'json',
				crossDomain: false,
				url: globalConfig.context + '/api/user/jtBusiness/project/apply',
				data: {
					name: this.state.categoryName, //项目名称
					categoryId: this.state.addCid[1],
					isHot: this.state.isHot,
					province: this.state.ProvinceCity ? this.state.ProvinceCity[0] : '', //是否全国
					city: this.state.ProvinceCity ? this.state.ProvinceCity[1] : ''
				}
			}).done(
				function(data) {
					this.setState({
						loading: false
					});
					if (!data.error.length) {
						message.success('新增项目成功！');
						this.handleCancel();
						this.loadData(this.state.page);
					} else {
						message.warning(data.error[0].message);
					}
				}.bind(this)
			);
		},
		//项目整行删除
		delectRow() {
			let deletedIds ='';
			let rowItem = this.state.selectedRowKeys[0];
			let data = this.state.dataSource ||[];
			if (data.length) {
				deletedIds=(data[rowItem].id);
			}
			console.log(deletedIds);
			this.setState({
				selectedRowKeys: [],
				loading: deletedIds.length > 0
			});
			$.ajax({
				method: 'get',
				dataType: 'json',
				crossDomain: false,
				url: globalConfig.context + '/api/user/jtBusiness/project/delete',
				data: {
					id: deletedIds
				}
			}).done(
				function(data) {
					if (!data.error.length) {
						message.success('删除成功！');
						this.setState({
							loading: false
						});
					} else {
						message.warning(data.error[0].message);
					}
					if(this.state.pagination.total%10==1){
						this.loadData((this.state.page)-1);
					}else{
						this.loadData(this.state.page);
					}
				}.bind(this)
			);
		},
		addClick() {
			this.state.RowData = {};
			this.setState({
				visible: true,
				isHot: 0
			});
			this.addReset();
		},
		closeDesc(e, s) {
			this.state.showDesc = e;
			if (s) {
				this.loadData(this.state.page);
			};
		},
		handleCancel() {
			this.setState({ visible: false });
		},
		search() {
			this.loadData();
		},
		//搜索部分的清零
		reset() {
			this.state.nameSearch = ''; //项目名称清零
			this.state.cid = undefined; //品类名称清零
			this.state.typeSearch=undefined;
			this.state.ressSearch = undefined; //省市区清零
			this.state.activityFlag = undefined; //活动生效清零
			this.state.status = undefined; //项目状态清零
			this.loadData();
		},
		//新增部分的清零
		addReset() {
			this.state.categoryName = ''; //项目名称清零
			this.state.ProvinceCity = undefined;
			this.state.addCid = undefined;
			this.state.boutique = '';
		},
		//更多搜索的显示与否
		searchSwitch() {
			this.setState({
				searchMore: !this.state.searchMore
			});
		},
		render() {
			const FormItem = Form.Item;
			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;
 			return (
				<div className="user-content">
					<div className="content-title">
						<span>项目业务列表</span>
						<div className="user-search">
							<Button
								type="primary"
								className="addButton"
								onClick={this.addClick}
								style={{ float: 'right', marginRight: '50px' }}
							>
								新增项目<Icon type="plus" />
							</Button>
							<Input
								placeholder="业务项目名称"
								style={{ width: '150px', marginRight: '10px', marginBottom: '10px' }}
								value={this.state.nameSearch}
								onChange={(e) => {
									this.setState({ nameSearch: e.target.value });
								}}
							/>
							<Cascader placeholder='业务项目品类'
								options={this.state.categoryList}
								style={{width:200,marginRight:10}}
								value={this.state.typeSearch} onChange={(e)=>{this.setState({typeSearch:e})}}/>
							<Button type="primary" onClick={this.search} style={{ marginRight: '10px' }}>
								搜索
							</Button>
							<Button onClick={this.reset} style={{ marginRight: '10px' }}>
								重置
							</Button>
							<Button
								type="danger"
								onClick={this.delectRow}
								disabled={!hasSelected}
							>
								删除<Icon type="minus" />
							</Button>
						</div>
						<div className="patent-table">
							<SpinContainer spinning={this.state.loading}>
								<Table
									columns={this.state.columns}
									dataSource={this.state.dataSource}
									rowSelection={rowSelection}
									pagination={this.state.pagination}
									onRowClick={this.tableRowClick}
									current={this.state.aa}
								/>
							</SpinContainer>
						</div>
						<TechDemandDesc
							data={this.state.RowData}
							showDesc={this.state.showDesc}
							closeDesc={this.closeDesc}
							categoryList={this.state.categoryList}
							tagList={this.state.tagList}
						/>
						<div className="patent-desc">
							<Modal
								maskClosable={false}
								visible={this.state.visible}
								onOk={this.checkPatentProcess}
								onCancel={this.handleCancel}
								width="400px"
								title="新增业务项目"
								footer=""
								className="admin-desc-content"
							>
								<Form layout="horizontal" onSubmit={this.addhandleSubmit} id="demand-form">
									<SpinContainer spinning={this.state.loading}>
										<div className="clearfix">
											<FormItem labelCol={{ span: 7 }} wrapperCol={{ span: 12 }} label="业务项目名称">
												<Input
													placeholder="业务项目名称"
													value={this.state.categoryName}
													style={{ width: '94%' }}
													onChange={(e) => {
														this.setState({ categoryName: e.target.value });
													}}
													required="required"
												/>
												<span className="mandatory" style={{ color: 'red', marginLeft: '5px' }}>
													*
												</span>
											</FormItem>
										</div>
										<div className="clearfix">
											<FormItem labelCol={{ span: 7 }} wrapperCol={{ span: 12 }} label="业务品类">
												<Cascader placeholder='业务项目品类'
													options={this.state.categoryList}
													value={this.state.addCid}
													style={{ width: '94%' }}
													onChange={(e)=>{this.setState({addCid:e})}}/>
												<span className="mandatory" style={{ color: 'red', marginLeft: '5px' }}>
													*
												</span>
											</FormItem>
										</div>
										<div className="clearfix">
											<FormItem labelCol={{ span: 7 }} wrapperCol={{ span: 12 }} label="省-市">
												<Cascader
													options={citySelect()}
													value={this.state.ProvinceCity}
													placeholder="选择市"
													style={{ width: '94%' }}
													onChange={(e, pre) => {
														this.setState({ ProvinceCity: e });
													}}
												/>
												<span style={{ color: 'red', marginLeft: '5px' }}>*</span>
											</FormItem>
										</div>
										<div className="clearfix" style={{"display":"none"}}>
											<FormItem labelCol={{ span: 7 }} wrapperCol={{ span: 12 }} label="热点">
												<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>
										<FormItem wrapperCol={{ span: 12, offset: 7 }}>
											<Button className="set-submit" type="primary" htmlType="submit">
												保存
											</Button>
											<Button
												className="set-submit"
												type="ghost"
												onClick={this.handleCancel}
												style={{ marginLeft: '15px' }}
											>
												取消
											</Button>
										</FormItem>
									</SpinContainer>
								</Form>
							</Modal>
						</div>
					</div>
				</div>
			);
		}
	})
);

export default BusinessProject;
