import React from 'react'
import { Form, Select, Cascader, Menu, InputNumber, Dropdown, Tag, message } from 'antd'
import { connect } from 'dva'
import '../../../models/chartDesigner'
import { deepAssign } from '../../../utils/baseUtils'
import GAUGE from './gauge.json'
const FormItem = Form.Item
const { Option } = Select
const formItemLayout = {
	labelCol: { span: 8 },
	wrapperCol: { span: 16 },
}
const IndicatorConfigForm = ({ autoRefresh, chartDesigner, dispatch }) => {
	const { columns, baseConfig, indicatorConfig, defaultIndicatorThreshold } = chartDesigner;

	return (
		<Form hideRequiredMark={true}>
			<FormItem label='标题/维度' {...formItemLayout}>
                <Select
					labelInValue={false}
					placeholder='请选择...'
					showSearch
					filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
					allowClear={true}
					onChange={(value) => {
                        let column = value ? columns.find(c => c.name === value) : null;
                        column = column ? {
							value: column.name,
							label: column.label,
							type: column.type
						} : {};
						dispatch({ type: 'chartDesigner/changeField', name: 'indicatorConfig', value: { ...indicatorConfig, xAxis: { column }, sortColumn: column.value ? { key: column.value, label: column.label } : (indicatorConfig.yAxis.column.value ? {key: indicatorConfig.yAxis.column.value, label:indicatorConfig.yAxis.column.label} : undefined) }, autoRefresh });
					}}
					value={indicatorConfig.xAxis.column.value}
				>
					{columns.filter(c => [indicatorConfig.yAxis.column.value, ].concat(indicatorConfig.otherColumn.map(c => c.value)).indexOf(c.name) === -1).map((c, i)=>{
						return (<Option key={i} value={c.name}>{c.label}</Option>)
					})}
				</Select>
			</FormItem>
			<FormItem label='指标/度量' {...formItemLayout}>
				<Cascader
					className='gauge-item'
					value={[indicatorConfig.yAxis.column.value, indicatorConfig.yAxis.gauge.value]}
					allowClear={true}
					showSearch={{
						filter: (inputValue, path) => {
							let p0 = path[0].label.toLowerCase();
							let v = inputValue.toLowerCase();
							return p0.indexOf(v) !== -1;
						},
						sort: (a, b, inputValue) => {
							return a[0].label.localeCompare(b[0].label,"zh");
						},
						render: (inputValue, path) => {
							const reg = new RegExp('([+ \\- & | ! ( ) { } \\[ \\] ^ \" ~ * ? : ( ) \/])', 'g'); // 需要转义的字符
							let v = inputValue.replace(new RegExp('(\\\\)', 'g'), '\\$1').replace(reg, '\\$1'); // 添加转义符号
							let label0 = (path[0].label.split(new RegExp(`(${v})`, 'i')).map((fragment, i) => {
								return (
									fragment.toLowerCase().replace(new RegExp('(\\\\)', 'g'), '\\$1').replace(reg, '\\$1') === v.toLowerCase() ?
									<span key={i} style={{fontWeight: 'bold', color: 'red'}} className="highlight">{fragment}</span> :
									fragment
								)
							}))
							return <div>{label0}>{path[1].label}</div>
						}
					}}
					options={columns.filter(c => [indicatorConfig.xAxis.column.value, ].concat(indicatorConfig.otherColumn.map(c => c.value)).indexOf(c.name) === -1).map((c, i)=>{
						return {
							value: c.name,
							label: c.label,
							type: c.type,
							children: GAUGE[baseConfig.viewType].filter(g => g.columnType.indexOf(c.type) !== -1)
						}
					})}
					onChange={(value, items) => {
						let column = {};
						let gauge = {};
						if(value.length > 0) {
							column = { type: items[0].type, value: items[0].value, label: items[0].label };
							gauge = { value: items[1].value, label: items[1].label };
						}
						dispatch({ type: 'chartDesigner/changeField', name: 'indicatorConfig', value: { ...indicatorConfig, yAxis: { column, gauge }, sortColumn: indicatorConfig.xAxis.column.value ? { key: indicatorConfig.xAxis.column.value, label: indicatorConfig.xAxis.column.label } : (column.value ? { key: column.value, label: column.label } : undefined) }, autoRefresh });
					}}
					displayRender={(label, selectedOptions) => {
						let menu = selectedOptions.length > 0 ? <Menu
							selectedKeys={[indicatorConfig.yAxis.gauge.value]}
							selectable={true}
						>
							{selectedOptions[0].children.map((c, i) => {
								return <Menu.Item  data-value={c.value} data-label={c.label} key={c.value} onClick={(e) => {
									let value = e.domEvent.target.getAttribute('data-value');
									let label = e.domEvent.target.getAttribute('data-label');
									dispatch({ type: 'chartDesigner/changeField', name: 'indicatorConfig', value: { 
										...indicatorConfig,
										yAxis: {
											column: indicatorConfig.yAxis.column,
											gauge: { value, label }
										}
									}, autoRefresh });
									e.domEvent.stopPropagation();
								}}>{c.label}</Menu.Item>
							})}
						</Menu>: [];
						let tag = selectedOptions.length > 0 ? <Dropdown
							trigger={['click']}
							overlay={menu}
						>
							<Tag size='small' onClick={(e) => {e.stopPropagation()}}>{label[1]}</Tag>
						</Dropdown>
						: null;

						return <div className={`cascader-label ${tag?'full' : 'empty'}-label`}>
							{tag}
							<span>{label[0] || '请选择...'}</span>
						</div>
					}}
				>
				</Cascader>
			</FormItem>
			<FormItem label='备注字段' {...formItemLayout}>
                <Select
					labelInValue={false}
					placeholder='请选择...'
					mode="multiple"
					showSearch
					filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
					allowClear={true}
					onChange={(value) => {
						if(value.length > 4) {
							message.warning('最多支持选择4个备注字段');
							return false;
						}
						let otherColumn = value.map(v => {
							let t = columns.find(c => c.name === v);
							return t ? {
								value: t.name,
								label: t.label,
								type: t.type
							} : null
						}).filter(v => v !== null);
						dispatch({ type: 'chartDesigner/changeField',
							name: 'indicatorConfig', value: { ...indicatorConfig, otherColumn }, autoRefresh });
					}}
					value={indicatorConfig.otherColumn.map(c => c.value)}
				>
					{columns.filter(c => c.name !== indicatorConfig.xAxis.column.value && c.name !== indicatorConfig.yAxis.column.value).map((c, i)=>{
						return (<Option key={i} value={c.name}>{c.label}</Option>)
					})}
				</Select>
			</FormItem>
            <FormItem label='排序列' {...formItemLayout}>
                <Select
                    allowClear
                    value={indicatorConfig.sortColumn}
                    labelInValue={true}
                    placeholder={indicatorConfig.xAxis.column.value ? indicatorConfig.xAxis.column.label : (indicatorConfig.yAxis.column.label || '无')}
                    showSearch
                    filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                    onChange={(value) => {
                        dispatch({ type: 'chartDesigner/changeField', name: 'indicatorConfig', value: { ...indicatorConfig, sortColumn: value }, autoRefresh });
                    }}
                >
                    {[indicatorConfig.xAxis.column, indicatorConfig.yAxis.column].concat(indicatorConfig.otherColumn).filter(x => !!x.value).map((c, i)=>{
                        return <Option key={c.value} value={c.value}>{c.label}</Option>
                    })}
                </Select>
            </FormItem>
            <FormItem label='排序方式' {...formItemLayout}>
                <Select
                    defaultValue='asc'
                    value={indicatorConfig.sortType}
                    placeholder='升序'
                    onChange={(value) => {
                        dispatch({ type: 'chartDesigner/changeField', name: 'indicatorConfig', value: { ...indicatorConfig, sortType: value }, autoRefresh });
                    }}
                >
                    <Option value="asc">升序</Option>
                    <Option value="desc">降序</Option>
                </Select>
            </FormItem>
			<FormItem label='阈值' {...formItemLayout}>
				<InputNumber
					defaultValue={indicatorConfig.threshold}
					placeholder={defaultIndicatorThreshold}
                    onBlur={e => {
						let value = e.target.value;
						if(value !== indicatorConfig.threshold) {
							let fields = [{ name: 'indicatorConfig', value: deepAssign(indicatorConfig, { threshold: value }) }];
							dispatch({ type: 'chartDesigner/changeFields', fields });
						}
                    }}
                    onKeyDown={e => {
                        if(e.keyCode === 13) {
                            let value = e.target.value;
							if(value !== indicatorConfig.threshold) {
								let fields = [{ name: 'indicatorConfig', value: deepAssign(indicatorConfig, { threshold: value }) }];
								dispatch({ type: 'chartDesigner/changeFields', fields });
							}
                        }
                    }}
				/>
			</FormItem>
		</Form>
	);
}

function mapStateToProps({ chartDesigner }) {
    return { chartDesigner: chartDesigner }
}

export default connect(mapStateToProps)(IndicatorConfigForm);