import React from 'react';
import $ from 'jquery/src/ajax';
import { Form, Icon, Radio, Button, Input, Select, Spin, Table, message, Modal, Upload, Popconfirm } from 'antd';
import { typeModule } from '@/dataDic.js';
import { splitUrl, getTypeModule } from '@/tools.js';
//图片组件
const PicturesWall = React.createClass({
	getInitialState() {
		return {
			previewVisible: false,
			previewImage: '',
			fileList: [],
			tags: []
		};
	},
	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 className="clearfix">
				<Upload
					action={globalConfig.context + '/api/admin/jtBusiness/uploadPicture'}
					data={{ sign: 'jt_business_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 BusinessCategory = 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/jtBusiness/category/list',
				data: {
					pageNo: pageNo || 1,
					pageSize: this.state.pagination.pageSize,
					name: this.state.nameSearch, //品类名称
					layer: this.state.layerSearch, //组织层级
					module: this.state.moduleSearch
				},
				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, //品类ID
								sort: thisdata.sort, //品类序号
								number: thisdata.number, //品类编号
								module: thisdata.module ? thisdata.module.toString() : undefined,
								name: thisdata.name, //品类名称
								layer: thisdata.layer,
								superId: thisdata.superId,
								layerName: thisdata.layerName, //品类层级
								superNameId: thisdata.superId, //上级品类
								superName: thisdata.superName
							});
						}
						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)
			);
		},
		loadMenu() {
			this.state.data = [];
			$.ajax({
				method: 'get',
				dataType: 'json',
				crossDomain: false,
				url: globalConfig.context + '/api/admin/jtBusiness/category/list',
				data: {
					pageNo: 1,
					pageSize: 9999,
					layer: 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, //品类ID
								name: thisdata.name //品类名称
							});
						}
					}
					this.setState({
						dataMenu: theArr
					});
				}.bind(this)
			}).always(
				function() {
					this.setState({
						loading: false
					});
				}.bind(this)
			);
		},
		getInitialState() {
			return {
				searchMore: true,
				selectedRowKeys: [],
				pictureUrl: [],
				selectedRows: [],
				loading: false,
				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: 'number',
						key: 'number'
					},
					{
						title: '品类名称',
						dataIndex: 'name',
						key: 'name'
					},
					{
						title: '品类层级',
						dataIndex: 'layerName',
						key: 'layerName'
					},
					{
						title: '序号',
						dataIndex: 'sort',
						key: 'sort'
					},
					{
						title: '所属模块',
						dataIndex: 'module',
						key: 'module',
						render: (text) => {
							return getTypeModule(text);
						}
					},
					{
						title: '上级品类',
						dataIndex: 'superName',
						key: 'superName',
						render: (text) => {
							return text ? text : '超级品类';
						}
					},
					{
						title: '操作',
						dataIndex: 'superName1',
						key: 'superName1',
						render: (text, recard) => {
							return (
								<div>
									{recard.layer < 2 && (
										<Button
											style={{ background: '#51a351', color: '#fff' }}
											onClick={(e) => {
												e.stopPropagation();
												this.nextAdd(recard);
											}}
										>
											新建下级品类
										</Button>
									)}
									<Button
										type="primary"
										style={{ margin: 10 }}
										onClick={(e) => {
											e.stopPropagation();
											this.movePre(recard);
										}}
									>
										上移
									</Button>
									<Button
										type="primary"
										onClick={(e) => {
											e.stopPropagation();
											this.moveTop(recard);
										}}
									>
										置顶
									</Button>
								</div>
							);
						}
					}
				],
				dataSource: []
			};
		},
		//上移动
		movePre(recard) {
			this.setState({
				loading: false
			});
			$.ajax({
				method: 'POST',
				url: globalConfig.context + '/api/admin/jtBusiness/project/moveUp',
				data: {
					id: recard.id
				}
			}).done((data) => {
				if (data && data.error.length) {
					message.error(data.error[0].message);
				}
				this.setState({ loading: false });
				this.loadData(this.state.page);
			});
		},
		//置顶
		moveTop(recard) {
			this.setState({
				loading: false
			});
			$.ajax({
				method: 'POST',
				url: globalConfig.context + '/api/admin/jtBusiness/project/setTop',
				data: {
					id: recard.id
				}
			}).done((data) => {
				if (data && data.error.length) {
					message.error(data.error[0].message);
				}
				this.setState({ loading: false });
				this.loadData(this.state.page);
			});
		},
		componentWillMount() {
			this.loadData();
			this.loadMenu();
		},
		//新建下级
		nextAdd(recard) {
			this.setState({
				recrdAdd: recard,
				visible: true,
				name: '',
				addFirst: 1,
				index: undefined,
				appIndex: undefined,
				superId: recard.id,
				module: recard.module ? recard.module.toString() : 'undefined'
			});
		},
		//编辑保存
		edithandleSubmit(e) {
			e.preventDefault();
			let thePictureUrl = [];
			if (this.state.pictureUrl.length) {
				let picArr = [];
				this.state.pictureUrl.map(function(item) {
					if (item.response && item.response.data && item.response.data.length) {
						picArr.push(item.response.data);
					}
				});
				thePictureUrl = picArr.join(',');
			}
			let dataList = {};
			if (this.state.layer == '1') {
				dataList.id = this.state.id;
				dataList.name = this.state.name;
				dataList.summary = this.state.summary;
				dataList.imgUrl = thePictureUrl.length ? thePictureUrl : '';
				dataList.module = this.state.moduleNumber ? this.state.moduleNumber : '0';
				dataList.nextModule = this.state.modules;
			} else {
				dataList.id = this.state.id;
				dataList.name = this.state.name;
				dataList.summary = this.state.summary;
				dataList.imgUrl = thePictureUrl.length ? thePictureUrl : '';
				dataList.oldSuperId = this.state.superId;
                dataList.superId = this.state.superNameId;
                dataList.pcIndex =this.state.index,  
                dataList.appIndex=this.state.appIndex
			}
			$.ajax({
				method: 'post',
				dataType: 'json',
				crossDomain: false,
				url: globalConfig.context + '/api/admin/jtBusiness/category/update',
				data: dataList
			}).done(
				function(data) {
					if (!data.error.length) {
						message.success('保存成功！');
						this.setState({
							loading: false,
							editvisible: false
						});
					} else {
						message.warning(data.error[0].message);
					}
					this.loadData(this.state.page);
				}.bind(this)
			);
		},
		//整行删除
		delectRow() {
			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/admin/jtBusiness/category/delete',
				data: {
					id: deletedIds[0]
				}
			}).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);
					this.loadMenu();
				}.bind(this)
			);
		},
		addClick() {
			this.state.RowData = {};
			this.setState({
				visible: true,
				addFirst: 0,
				name: '',
				superId: '',
				module: '1',
				index: undefined,
				appIndex: undefined
			});
		},
		//新增保存
		addhandleSubmit(e) {
			e.preventDefault();
			this.setState({
				loading: true
			});
			$.ajax({
				method: 'post',
				dataType: 'json',
				crossDomain: false,
				url: globalConfig.context + '/api/admin/jtBusiness/category/apply',
				data: {
					name: this.state.name,
					superId: this.state.superId,
					layer: this.state.addFirst ? this.state.recrdAdd.layer + 1 : '1',
					module: this.state.module,
					pcIndex : this.state.index,
					appIndex: this.state.appIndex
				}
			}).done(
				function(data) {
					if (!data.error.length) {
						message.success('新增成功！');
						this.setState({
							loading: false,
							visible: false
						});
					} else {
						message.warning(data.error[0].message);
					}
					this.loadData(this.state.page);
					this.loadMenu();
				}.bind(this)
			);
		},
		editClick() {
			this.state.RowData = {};
			this.setState({
				editvisible: true
			});
		},
		detailes(recard) {
			this.setState({
				loading: true
			});
			$.ajax({
				method: 'get',
				dataType: 'json',
				crossDomain: false,
				url: globalConfig.context + '/api/admin/jtBusiness/category/detail',
				data: {
					id: recard.id
				},
				success: function(data) {
					if (!data.data) {
						if (data.error && data.error.length) {
							message.warning(data.error[0].message);
						}
					} else {
                        let thisdata = data.data;
						this.setState({
							id: thisdata.id, //品类id
							name: thisdata.name, //品类名称
							createTime: thisdata.createTime ? new Date(thisdata.createTime).toLocaleString() : '',
							superId: thisdata.superId, //父类id
							modules: thisdata.module ? thisdata.module.toString() : undefined,
							pictureUrl: thisdata.imgUrl
								? splitUrl(thisdata.imgUrl, ',', globalConfig.avatarHost + '/upload')
								: [],
							number: thisdata.number,
							layer: thisdata.layer,
                            superNameId: thisdata.superId,
                            index:thisdata.pcIndex ,
                            appIndex:thisdata.appIndex,
							moduleNumber: thisdata.module ? thisdata.module.toString() : undefined
						});
					}
				}.bind(this)
			}).always(
				function() {
					this.setState({
						loading: false
					});
				}.bind(this)
			);
		},
		handleCancel() {
			this.setState({ visible: false });
		},
		edithandleCancel() {
			this.setState({ editvisible: false });
		},
		search() {
			this.loadData();
		},
		reset() {
			this.state.nameSearch = ''; //品类名称清零
			this.state.moduleSearch = undefined;
			this.state.layerSearch = undefined; //品类层级清零
			this.loadData();
		},
		searchSwitch() {
			this.setState({
				searchMore: !this.state.searchMore
			});
		},
		getPictureUrl(e) {
			this.setState({ pictureUrl: e });
		},
		tableRowClick(record, index) {
			this.setState({
				editvisible: true,
				visible: false,
				theData: record
			});
			this.detailes(record);
		},
		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;
			const theData = this.state.theData || {};
			const recrdAdd = this.state.recrdAdd || {};
			const dataMenu = this.state.dataMenu || {};
			return (
				<div className="user-content">
					<div className="content-title">
						<div className="content-title">
							<span>项目业务管理</span>
						</div>
						<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 });
								}}
							/>
							<Select
								placeholder="品类层级"
								style={{ width: '200px', marginRight: '10px' }}
								value={this.state.layerSearch}
								onChange={(e) => {
									this.setState({ layerSearch: e });
								}}
							>
								<Select.Option value="1">一级</Select.Option>
								<Select.Option value="2">二级</Select.Option>
							</Select>
							<Select
								style={{ width: '200px', marginRight: '10px' }}
								value={this.state.moduleSearch}
								placeholder="模块"
								onChange={(e) => {
									this.setState({ moduleSearch: e });
								}}
							>
								{typeModule.map((item) => {
									return (
										<Select.Option key={item.value} value={item.value}>
											{item.key}
										</Select.Option>
									);
								})}
							</Select>
							<Button type="primary" onClick={this.search} style={{ marginRight: '10px' }}>
								搜索
							</Button>
							<Button onClick={this.reset} style={{ marginRight: '10px' }}>
								重置
							</Button>
							<Popconfirm title="是否删除?" onConfirm={this.delectRow} okText="是" cancelText="否">
								<Button
									style={{ marginRight: '10px', marginLeft: '10px' }}
									type="danger"
									disabled={!hasSelected}
								>
									删除<Icon type="minus" />
								</Button>
							</Popconfirm>
							<Popconfirm title="是否停用?" onConfirm={this.blockRow} okText="是" cancelText="否">
								<Button
									style={{
										background: '#ea0862',
										border: 'none',
										color: '#fff',
										marginRight: '10px',
										marginLeft: '10px',
										display: 'none'
									}}
									disabled={!hasSelected}
								>
									停用<Icon type="minus" />
								</Button>
							</Popconfirm>
							<Button
								type="primary"
								className="addButton"
								onClick={this.addClick}
								style={{ float: 'right', marginRight: '200px' }}
							>
								新增品类<Icon type="plus" />
							</Button>
						</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>

						<div className="patent-desc">
							<Modal
								maskClosable={false}
								visible={this.state.visible}
								onOk={this.checkPatentProcess}
								onCancel={this.handleCancel}
								width="420px"
								title="新增品类"
								footer=""
								className="admin-desc-content"
							>
								<Form
									layout="horizontal"
									onSubmit={(e) => {
										this.addhandleSubmit(e, {});
									}}
									id="demand-form"
								>
									<Spin spinning={this.state.loading}>
										<div className="clearfix">
											<FormItem labelCol={{ span: 7 }} wrapperCol={{ span: 12 }} label="品类名称">
												<Input
													placeholder="品类名称"
													value={this.state.name}
													style={{ width: '94%' }}
													onChange={(e) => {
														this.setState({ name: 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="所属模块">
												{!this.state.addFirst ? (
													<Select
														value={this.state.module}
														onChange={(e) => {
															this.setState({ module: e });
														}}
													>
														{typeModule.map((item) => {
															return (
																<Select.Option key={item.value} value={item.value}>
																	{item.key}
																</Select.Option>
															);
														})}
													</Select>
												) : (
													<span>{getTypeModule(recrdAdd.module)}</span>
												)}
											</FormItem>
										</div>
										<div className="clearfix">
											<FormItem labelCol={{ span: 7 }} wrapperCol={{ span: 12 }} label="上级品类">
												<span>{this.state.addFirst ? recrdAdd.name : '超级品类'}</span>
											</FormItem>
										</div>
										{this.state.addFirst ? (
											<div>
												<div className="clearfix">
													<FormItem
														labelCol={{ span: 7 }}
														wrapperCol={{ span: 12 }}
														label="发布到项目首页"
													>
														<Radio.Group
															onChange={(e) => {
																this.setState({ index: e.target.value });
															}}
															value={this.state.index}
														>
															<Radio value={1}>是</Radio>
															<Radio value={0}>否</Radio>
														</Radio.Group>
													</FormItem>
												</div>
												<div className="clearfix">
													<FormItem
														labelCol={{ span: 7 }}
														wrapperCol={{ span: 12 }}
														label="发布到APP首页"
													>
														<Radio.Group
															onChange={(e) => {
																this.setState({ appIndex: e.target.value });
															}}
															value={this.state.appIndex}
														>
															<Radio value={1}>是</Radio>
															<Radio value={0}>否</Radio>
														</Radio.Group>
													</FormItem>
												</div>
											</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>
									</Spin>
								</Form>
							</Modal>
						</div>

						<div className="patent-desc">
							<Modal
								maskClosable={false}
								visible={this.state.editvisible}
								onOk={this.checkPatentProcess}
								onCancel={this.edithandleCancel}
								width="600px"
								title="编辑品类"
								footer=""
								className="admin-desc-content"
							>
								<Form layout="horizontal" onSubmit={this.edithandleSubmit} id="demand-form">
									<Spin spinning={this.state.loading}>
										<div className="clearfix">
											<FormItem labelCol={{ span: 7 }} wrapperCol={{ span: 12 }} label="品类名称">
												<Input
													placeholder="组织名称"
													value={this.state.name}
													onChange={(e) => {
														this.setState({ name: e.target.value });
													}}
												/>
											</FormItem>
										</div>
										{theData.layer == '2' ? (
											<div className="clearfix">
												<FormItem labelCol={{ span: 7 }} wrapperCol={{ span: 12 }} label="上级品类">
													<Select
														onChange={(e) => {
															this.setState({ superNameId: e });
														}}
														value={this.state.superNameId}
													>
														{dataMenu.map((item) => {
															return (
																<Select.Option key={item.key} value={item.id}>
																	{item.name}
																</Select.Option>
															);
														})}
													</Select>
												</FormItem>
											</div>
										) : (
											''
                                        )}
                                        {this.state.layer=='2'?<div>
                                            <div className="clearfix">
                                                <FormItem labelCol={{ span: 7 }} wrapperCol={{ span: 12 }} label="发布到项目首页">
                                                    <Radio.Group
                                                        onChange={(e) => {
                                                            this.setState({ index: e.target.value });
                                                        }}
                                                        value={this.state.index}
                                                    >
                                                        <Radio value={1}>是</Radio>
                                                        <Radio value={0}>否</Radio>
                                                    </Radio.Group>
                                                </FormItem>
                                            </div>
                                            <div className="clearfix">
                                                <FormItem labelCol={{ span: 7 }} wrapperCol={{ span: 12 }} label="发布到APP首页">
                                                    <Radio.Group
                                                        onChange={(e) => {
                                                            this.setState({ appIndex: e.target.value });
                                                        }}
                                                        value={this.state.appIndex}
                                                    >
                                                        <Radio value={1}>是</Radio>
                                                        <Radio value={0}>否</Radio>
                                                    </Radio.Group>
                                                </FormItem>
										</div>
                                        </div>:''}
										<div className="clearfix">
											<FormItem labelCol={{ span: 7 }} wrapperCol={{ span: 12 }} label="业务品类图标">
												<PicturesWall
													fileList={this.getPictureUrl}
													pictureUrl={this.state.pictureUrl}
													visible={this.props.visible}
												/>
											</FormItem>
										</div>
										<div className="clearfix">
											<FormItem labelCol={{ span: 7 }} wrapperCol={{ span: 12 }} label="品类序号">
												<span>{theData.sort}</span>
											</FormItem>
										</div>
										<div className="clearfix">
											<FormItem labelCol={{ span: 7 }} wrapperCol={{ span: 12 }} label="品类层级">
												<span>{theData.layerName}</span>
											</FormItem>
										</div>
										<FormItem labelCol={{ span: 7 }} wrapperCol={{ span: 12 }} label="所属模块">
											{theData.layer == '1' ? (
												<Select
													value={this.state.modules}
													onChange={(e) => {
														this.setState({ modules: e });
													}}
													style={{ width: 160 }}
												>
													{typeModule.map((item) => {
														return (
															<Select.Option key={item.value} value={item.value}>
																{item.key}
															</Select.Option>
														);
													})}
												</Select>
											) : (
												<span>{getTypeModule(this.state.modules)}</span>
											)}
										</FormItem>
										<div className="clearfix">
											<FormItem labelCol={{ span: 7 }} wrapperCol={{ span: 12 }} label="品类编号">
												<span>{theData.number}</span>
											</FormItem>
										</div>
										<div className="clearfix">
											<FormItem labelCol={{ span: 7 }} wrapperCol={{ span: 12 }} label="创建人">
												<span>超级管理员</span>
											</FormItem>
										</div>
										<div className="clearfix">
											<FormItem labelCol={{ span: 7 }} wrapperCol={{ span: 12 }} label="创建时间">
												<span>{this.state.createTime}</span>
											</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.edithandleCancel}
												style={{ marginLeft: '100px' }}
											>
												取消
											</Button>
										</FormItem>
									</Spin>
								</Form>
							</Modal>
						</div>
					</div>
				</div>
			);
		}
	})
);

export default BusinessCategory;
