import React from 'react';
import { Form, Select, Checkbox, InputNumber } from 'antd';
import { deepAssign } from '../../../utils/baseUtils';
import { connect } from 'dva';
import XAxisItem from './xAxisItem';
import YAxisItem from './yAxisItem';
import DrillList from './drillList';
import GRANULARITY from './granularity.json';
const FormItem = Form.Item;
const { Option } = Select;
const formItemLayout = {
	labelCol: { span: 8 },
	wrapperCol: { span: 16 },
};
const BarConfigForm = ({ autoRefresh, chartDesigner, dispatch }) => {
	const { columns, baseConfig, barConfig } = chartDesigner;

	return (
		<Form hideRequiredMark={true}>
			<FormItem label='横轴' {...formItemLayout}>
				<XAxisItem value={barConfig.xAxis} options={columns.filter(c =>['ordinal', 'categorical', 'time'].indexOf(c.type) > -1)}
					onChange={({ column, granularity }) => {
						dispatch({ type: 'chartDesigner/changeField', name: 'barConfig', value: {
							...barConfig,
							xAxis: { column, granularity },
							drillable: false,
							drillList: [{ column, granularity }] 
						}, autoRefresh });
					}}
				/>
			</FormItem>
			<FormItem label='纵轴' {...formItemLayout}>
				<YAxisItem value={barConfig.yAxis} options={columns} gaugeType={baseConfig.viewType} onChange={({ column, gauge }) => {
					dispatch({ type: 'chartDesigner/changeField', name: 'barConfig', value: { ...barConfig, yAxis: { column, gauge } }, autoRefresh });
				}}/>
			</FormItem>
			<FormItem label='分组' {...formItemLayout}>
				<Select
					labelInValue={true}
					placeholder='请选择...'
					showSearch
					filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
					allowClear={true}
					onChange={(value) => {
						const column = value ? columns.find(c => c.name === value.key) : null;
						const groupBy = column ? { ...value, type: column.type } : undefined;
						dispatch({ type: 'chartDesigner/changeField', name: 'barConfig', value: { ...barConfig, groupBy }, autoRefresh });
					}}
					value={barConfig.groupBy}
				>
					{columns.filter(c => c.groupable).map((c, i)=>{
						return (<Option key={i} value={c.name}>{c.label}</Option>)
					})}
				</Select>
			</FormItem>
			{(!barConfig.groupBy || !barConfig.groupBy.key) && <FormItem label='排序目标' {...formItemLayout}>
				<Select
					placeholder='横轴名称'
					allowClear={true}
					onChange={(value) => {
						dispatch({ type: 'chartDesigner/changeField', name: 'barConfig', value: { ...barConfig, sortTarget: value }, autoRefresh });
					}}
					value={barConfig.sortTarget}
				>
					<Option value='x'>横轴名称</Option>
					<Option value='y'>纵轴数值</Option>
				</Select>
			</FormItem>}
			{(!barConfig.groupBy || !barConfig.groupBy.key) && <FormItem label='排序方式' {...formItemLayout}>
				<Select
					placeholder='升序'
					allowClear={true}
					onChange={(value) => {
						dispatch({ type: 'chartDesigner/changeField', name: 'barConfig', value: { ...barConfig, sortType: value }, autoRefresh });
					}}
					value={barConfig.sortType}
				>
					<Option value='ASC'>升序</Option>
					<Option value='DESC'>降序</Option>
				</Select>
			</FormItem>}
			<FormItem label='阈值' {...formItemLayout}>
				<InputNumber
					defaultValue={chartDesigner.barConfig.threshold}
					placeholder={chartDesigner.defaultBarThreshold}
                    onBlur={e => {
						let value = e.target.value;
						if(value !== chartDesigner.barConfig.threshold) {
							let fields = [{ name: 'barConfig', value: deepAssign(chartDesigner.barConfig, { threshold: value }) }];
							dispatch({ type: 'chartDesigner/changeFields', fields });
						}
                    }}
                    onKeyDown={e => {
                        if(e.keyCode === 13) {
                            let value = e.target.value;
							if(value !== chartDesigner.barConfig.threshold) {
								let fields = [{ name: 'barConfig', value: deepAssign(chartDesigner.barConfig, { threshold: value }) }];
								dispatch({ type: 'chartDesigner/changeFields', fields });
							}
                        }
                    }}
				/>
			</FormItem>
			{barConfig.xAxis.column.value && <FormItem label='钻取' {...formItemLayout}>
				<Checkbox
					checked={!!barConfig.drillable}
					onChange={e => {
						let checked = e.target.checked;
						let drillList = [{ column: barConfig.xAxis.column, granularity: barConfig.xAxis.granularity }];
						if(barConfig.xAxis.column.type === 'time') { // 如果x轴字段是时间类型，自动生成其维度钻取层级
							const granularitys = GRANULARITY['time'];
							let idx = granularitys.findIndex(g => g.value === barConfig.xAxis.granularity.value);
							for(let i = idx + 1; i < granularitys.length; i++) {
								drillList.push({
									column: barConfig.xAxis.column,
									granularity: granularitys[i]
								});
							}
						}
						dispatch({ type: 'chartDesigner/changeField', name: 'barConfig', value: { ...barConfig, drillable: checked, drillList }, autoRefresh });
					}}
				/>
			</FormItem>}
			{barConfig.xAxis.column.value && barConfig.drillable && <FormItem label='钻取层级' {...formItemLayout}>
				<DrillList
					// 可选钻取字段包括时间、类别类型，且当x轴选择的是时间类型时允许重复作为钻取字段（之后会限制年月周等维度的选择）
					list={columns.filter(c => ['categorical', 'time'].indexOf(c.type) > -1)}
					value={barConfig.drillList || []}
					onChange={list => {
						dispatch({ type: 'chartDesigner/changeField', name: 'barConfig', value: { ...barConfig, drillList: list }, autoRefresh });
					}}
				/>
			</FormItem>}
		</Form>
	);
}

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

export default connect(mapStateToProps)(BarConfigForm);