// 菜单明细维护/菜单管理
import React from 'react';
import { Divider, Popconfirm, message, Input, Row, Col, Button, Spin, Icon, Tooltip } from 'antd';
import { Util } from 'tools';
import { $http } from '../../containers/config/https';
import store from 'store';
import PubilcTablePagination from '../common/PubilcTablePagination.jsx';
import MenuDetailModal from './component/MenuDetailModal.jsx';
import InterfaceLoading from './component/InterfaceLoading';
import '../../assets/css/system.css';

class MenuDetailMaintenance extends React.Component {
	constructor(props) {
		super(props);
		var userData = JSON.parse(sessionStorage.getItem('userData'));
		this.state = {
			flag: '',
			title: '',
			userInfo: {},
			// 主菜单列表数据
			columns: [],
			totalWidth: 2800,
			data: [],
			// 主菜单-代码
			code: '',
			// 主菜单-描述
			describe: '',
			linkAddress: undefined,
			params: undefined,
			total: 0,
			page: 1,
			pageSize: 20,
			// 是否显示loading
			showLoading: true,
			user: userData,
			loading: false,
			productCatSelectData: [], // 产品分类
		};
		// 表格的表头数据
		this.columns = [{
			key: 1,
			title: '代码',
			dataIndex: 'Code',
			width: 100,
			fixed: 'left',
			align: 'center'
		}, {
			key: 2,
			title: '描述',
			dataIndex: 'Descripts',
			width: 200,
			fixed: 'left',
			align: 'center',
			render: (text, record) => {
				return (
					<Tooltip title={text}>
						<span className="ellipsis" style={{ width: '100%', display: 'block' }}>{text}</span>
					</Tooltip>
				);
			},
		}, {
			key: 3,
			title: '英文描述',
			dataIndex: 'ENDesc',
			width: 300,
			align: 'center',
			render: (text, record) => {
				return (
					<Tooltip title={text}>
						<span className="ellipsis" style={{ width: '100%', display: 'block' }}>{text}</span>
					</Tooltip>
				);
			},
		}, {
			key: 4,
			title: '链接地址',
			dataIndex: 'LinkAddress',
			width: 620,
			align: 'center',
			className: 'personInfo',
			render: (text, record) => {
				return (
					<Tooltip title={text}>
						<span className="ellipsis" style={{ width: '100%', display: 'block' }}>{text}</span>
					</Tooltip>
				);
			},
		}, {
			key: 12,
			title: '参数',
			dataIndex: 'Paras',
			width: 300,
			align: 'center',
			render: (text, record) => {
				return (
					<Tooltip title={text}>
						<span className="ellipsis" style={{ width: '100%', display: 'block' }}>{text}</span>
					</Tooltip>
				);
			},
		}, {
			key: 17,
			title: '产品分类',
			dataIndex: 'productCatDesc',
			width: 100,
			align: 'center'
		}, {
			key: 18,
			title: '产品模块',
			dataIndex: 'productModuleDesc',
			width: 100,
			align: 'center'
		}, {
			key: 116,
			title: '顺序号',
			dataIndex: 'SeqNo',
			width: 80,
			align: 'center'
		}, {
			key: 6,
			title: '菜单组标志',
			dataIndex: 'MenuGroup',
			width: 80,
			align: 'center',
			render(MenuGroup) {
				let config = {
					'Y': '是',
					'N': '否'
				}
				return config[MenuGroup];
			}
		}, {
			key: 7,
			title: '图片地址',
			dataIndex: 'Image',
			width: 200,
			align: 'center',
			render: (text, record) => {
				return (
					<Tooltip title={text}>
						<span className="ellipsis" style={{ width: '100%', display: 'block' }}>{text}</span>
					</Tooltip>
				);
			},
		}, {
			key: 8,
			title: 'tab主菜单id',
			dataIndex: 'MainMenuDr',
			width: 100,
			align: 'center'
		}, {
			key: 9,
			title: '快捷键',
			dataIndex: 'ShortcutKey',
			width: 100,
			align: 'center'
		}, {
			key: 10,
			title: '弹窗位置',
			dataIndex: 'WinPosition',
			width: 200,
			align: 'center'
		}, {
			key: 11,
			title: '执行后台方法',
			dataIndex: 'BackMethod',
			width: 120,
			align: 'center'
		}, {
			key: 13,
			title: '条件表达式',
			dataIndex: 'CondExpress',
			width: 200,
			align: 'center'
		}, {
			key: 14,
			title: 'JS方法',
			dataIndex: 'JSMethod',
			width: 200,
			align: 'center'
		}, {
			key: 15,
			title: '提示信息',
			dataIndex: 'Tooltip',
			width: 100,
			align: 'center'
		}, {
			key: 20,
			title: '记录点击率标志',
			dataIndex: 'ClickRateFlag',
			width: 100,
			align: 'center',
			render(ClickRateFlag) {
				let config = {
					'Y': '是',
					'N': '否'
				}
				return config[ClickRateFlag];
			}
		}];
	}

	componentDidMount() {
		// 初始化列表数据
		this.handleQuery()
		this.getSelectData();
		this.getTableColumns();
		// 数据异步请求，请求成功之后setState
		this.setState({
			showLoading: false
		})
	}

	componentWillUnmount() {
		// 组件销毁前将静止让setState修改state的状态
		this.setState = (state, callback) => { return; }
	}

	// 获取表头数据
	getTableColumns = async () => {
		try {
			let data = {
				params: [{
					compontName: 'MenuDetailMaintenance',
					type: 'C',
				}]
			}
			let res = await React.$asyncPost(this, '01040073', data);
			let columns = res.result && res.result.C && res.result.C.length > 0 ? res.result.C.map(item => {
				return {
					...item,
					tooltip: item.dataIndex === 'MenuGroup' || item.dataIndex === 'ClickRateFlag' ? 'N' : 'Y',
					render: (text, record) => {
						if (item.dataIndex === 'MenuGroup' || item.dataIndex === 'ClickRateFlag') { // 菜单组标志
							let config = {
								'Y': '是',
								'N': '否'
							}
							return config[text];
						} else {
							return text;
						}
					},
				}
			}) : [];
			if (columns && columns.length > 0) {
				this.setState({
					columns,
					totalWidth: res.totalWidth
				})
			}
		} catch (error) {
			console.log(error)
		}
	}

	/**
	* @ByShizi: 查看界面轮廓
	* Create 2022-12-08
	* */
	handleLookUp = (record) => {
		let linkAddress = record?.LinkAddress || '';
		let linkAddressSplit = linkAddress && linkAddress.indexOf('/') > -1 ? linkAddress.split('/') : [];
		let componentName = linkAddressSplit && linkAddressSplit.length > 0 ? linkAddressSplit[linkAddressSplit.length - 1] : '';
		let sessionKey = componentName && componentName.indexOf('.') > -1 ? componentName.split('.')[0] : componentName;
		React.$setSessionData(sessionKey, record.Paras, false);
		this.setState({ lookUpSessionkey: sessionKey });
		linkAddress = linkAddress.indexOf('../') > -1 ? linkAddress.split('../')[1] : linkAddress;
		this.interfaceRef && this.interfaceRef.modifyVisible(true, linkAddress, record?.Descripts || '', record?.Paras || '');
	}

	// 清除查看数据
	clearLookUpSessionData = () => {
		const { lookUpSessionkey } = this.state;
		React.$removeSessionData(lookUpSessionkey);
	}

	/**
	 * @ByShizi: 获取下拉框数据 - 添加产品分类及产品模块
	 * Create 2022-10-17
	 * */
	getSelectData = async () => {
		try {
			let res = await React.$asyncPost(this, '2308');
			this.setState({ productCatSelectData: res.result });
		} catch (error) {
			this.setState({ productCatSelectData: [] });
		}
	}

	// 调用子组件的连接事件
	onRef = (ref) => {
		this.child = ref
	}

	handleOnRef = (ref) => {
		this.commonChild = ref
	}

	// 提供修改page和pageSize的回调函数
	compilePage(page, pageSize) {
		// 修改page，或者pageSize
		this.setState({ page: page, pageSize: pageSize }, () => {
			// 重新调用查询方法
			this.getTableData();
		})
	}

	// 重置userInfo
	resetUserInfo() {
		this.setState({ userInfo: {} })
	}

	modifyInputValue = (dataIndex, e) => {
		this.state[dataIndex] = e.target.value;
		this.setState({});
	}

	// 新增
	handleAdd = () => {
		// 打开抽屉
		this.child.showDrawer();
		// 初始化数据
		this.setState({ flag: 'add', title: '新增' })
	}

	// 请求列表数据
	getTableData = () => {
		this.setState({ loading: true })
		let { page, pageSize, code, describe, linkAddress, params } = this.state;
		let data = {
			params: [{
				Code: code,
				Descripts: describe,
				LinkAddress: linkAddress,
				Paras: params
			}],
			pagination: [{
				pageSize: pageSize,
				currentPage: page,
				sortColumn: 'Code',
				sortOrder: 'asc'
			}]
		};
		$http.post('urlS', this, {
			code: '2301',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0 && res.result) {
					this.setState({ data: Util.addKeyValueToDataSource(res.result?.Data || []), total: res.result.TotalCount, loading: false })
					this.commonChild.handleLoading()
				} else {
					this.setState({ data: [], total: 0, loading: false }, () => {
						// 关闭loading
						this.commonChild.handleLoading();
					})
				}
			}
		})
	}

	// 查询
	handleQuery = () => {
		this.setState({ page: 1 }, () => {
			this.getTableData();
		})
	}

	// 编辑
	handleCompile(record) {
		// 重置表单
		this.child.resetFields()
		// 打开抽屉
		this.child.showDrawer();
		// 将值赋值给抽屉
		this.setState({ userInfo: record, flag: 'compile', title: '编辑' });
	}

	// 删除
	handleDelete(record) {
		// console.log(record)
		let data = {
			params: [{
				ID: record.ID,
				userID: this.state.user && this.state.user.userID ? this.state.user.userID : ''
			}]
		}
		$http.post('urlADS', this, {
			code: '2304',
			data: data,
			success: function (res) {
				// console.log(res)
				if (+res.errorCode === 0) {
					message.success('删除成功');
					this.getTableData();
				}
			}
		})
	}

	render() {
		const { productCatSelectData, columns, totalWidth } = this.state;
		const operationObj = {
			title: '操作',
			key: 'operation',
			fixed: 'right',
			align: 'left',
			width: 230,
			render: (text, record) => (
				<span style={{ paddingLeft: '12px' }}>
					<Icon type="edit" style={{ color: '#108EE9' }}></Icon>
					<span className='span' onClick={() => this.handleCompile(record)}>编辑</span>
					{/* 分割线 */}
					<Divider type="vertical" />
					<Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
					<Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDelete(record)} >
						<span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
					</Popconfirm>
					{record?.LinkAddress ? (
						<>
							<Divider type="vertical" />
							<span className='span' style={{ color: '#999', fontWeight: 'normal' }} onClick={() => this.handleLookUp(record)}>查看界面轮廓</span>
						</>
					) : ''}
				</span>
			),
		}
		// 组件所需参数
		const param = {
			componentName: 'MenuDetailMaintenance',
			// 表头配置
			columns: columns && columns.length > 0 ? [...columns, operationObj] : [...this.columns, operationObj],
			// 表格数据
			data: this.state.data,
			// 数据总条数
			total: this.state.total,
			// 当前页数
			page: this.state.page,
			pageSize: '20',
			loading: this.state.loading,
			y: store.getState().tableHeight.y + 114 - 75,
			height: store.getState().tableHeight.y + 158 - 75 + 'px',
			// 表格的宽度
			x: totalWidth,
		}
		return (
			<Spin tip="加载中..." spinning={this.state.showLoading}>
				<div>
					<div className="table-operations">
						<Row style={{ height: '75px', lineHeight: '75px', padding: '0 24px' }}>
							<Col span={18}>
								代码：<Input
									title="输入内容后可回车检索"
									placeholder="请输入( Enter )"
									defaultValue={this.state.code}
									style={{ width: '150px', marginRight: '15px' }}
									onChange={(e) => this.modifyInputValue('code', e)}
									onPressEnter={this.handleQuery}
								/>
								描述：<Input
									title="输入内容后可回车检索"
									placeholder="请输入( Enter )"
									defaultValue={this.state.describe}
									style={{ width: '150px', marginRight: '15px' }}
									onChange={(e) => this.modifyInputValue('describe', e)}
									onPressEnter={this.handleQuery}
								/>
								链接地址：<Input
									title="输入内容后可回车检索"
									placeholder="请输入( Enter )"
									defaultValue={this.state.linkAddress}
									style={{ width: '250px', marginRight: '15px' }}
									onChange={(e) => this.modifyInputValue('linkAddress', e)}
									onPressEnter={this.handleQuery}
								/>
								参数：<Input
									title="输入内容后可回车检索"
									placeholder="请输入( Enter )"
									defaultValue={this.state.params}
									style={{ width: '250px', marginRight: '15px' }}
									onChange={(e) => this.modifyInputValue('params', e)}
									onPressEnter={this.handleQuery}
								/>
								<Button style={{ marginRight: '15px', background: 'rgba(255,255,255,1)' }} onClick={this.handleQuery}>查询</Button>
							</Col>
							<Col span={6} style={{ textAlign: 'right' }}>
								<Button icon="plus" onClick={this.handleAdd} style={{ background: 'rgba(247,128,93,1)', color: '#fff' }}>新增菜单明细</Button>
							</Col>
						</Row>
					</div>
					<div style={{ widht: '100%', height: '10px', background: '#f0f2f5' }}></div>
					<div style={{ padding: '24px 24px 12px 24px' }} className="table-body-height">
						{/* handelThis将夫组件的属性与方法给子组件访问 */}
						<PubilcTablePagination
							param={param}
							handelThis={this}
							onRef={this.handleOnRef}
							getColumns={this.getTableColumns}
						/>
					</div>

					{/* 新增编辑弹框 */}
					<MenuDetailModal onRef={this.onRef} userInfo={this.state.userInfo} handelThis={this} flag={this.state.flag} title={this.state.title} productCatSelectData={productCatSelectData} />

					{/* 查看界面轮廓 */}
					<InterfaceLoading onRef={ref => this.interfaceRef = ref} clearSessionData={this.clearLookUpSessionData} />
				</div>
			</Spin>
		)
	}
};

export default MenuDetailMaintenance;