import React, { Fragment, useMemo, useCallback } from 'react';
import moment from 'moment';
import {
	Table,
	Modal,
	Form,
	Select,
	Input,
	DatePicker,
	Cascader,
	Space,
	Button,
	message,
	Row,
	Col,
} from 'antd';
import { FormItemProps } from 'antd/lib/form';
import { ColumnProps } from 'antd/lib/table';
import {
	useUnitList,
	UnitRecordProps,
	useUpdateUnit,
	useAddUnit,
	useRemoveUnit,
} from '../../hooks/uint';
import { useGetAreaTree } from '../../hooks/map';
import { PARTICIPATION_TYPE, PARTICIPATION_TYPE_KEY } from '../../contants';
const unitFormDataConfig: FormItemProps[] = [
	{
		label: '企业名称',
		name: 'name',
		required: true,
		children: <Input placeholder='请输入企业名称'></Input>,
	},
	{
		label: '参建单位类型',
		name: 'corp_type',
		required: true,
		children: (
			<Select placeholder='请选择参建单位类型'>
				{Object.keys(PARTICIPATION_TYPE).map((element) => {
					return (
						<Select.Option value={Number(element)} key={element}>
							{PARTICIPATION_TYPE[element].name}
						</Select.Option>
					);
				})}
			</Select>
		),
	},
	{
		label: '统一社会信用代码',
		name: 'social_code',
		required: true,
		children: <Input placeholder='请输入企业统一社会信用代码'></Input>,
	},
	{
		label: '企业注册时间',
		name: 'register_date',
		required: true,
		children: (
			<DatePicker showToday={false} placeholder='请选择时间'></DatePicker>
		),
	},
];
const colums: ColumnProps<UnitRecordProps & { adress: string }>[] = [
	{
		title: '企业名称',
		dataIndex: 'name',
		key: 'name',
		render: (value) => {
			return value || '-';
		},
	},
	{
		title: '统一社会信用代码',
		dataIndex: 'social_code',
		key: 'social_code',
		render: (value) => {
			return value || '-';
		},
	},
	{
		title: '参建类型',
		dataIndex: 'corp_type',
		key: 'corp_type',
		render: (_, record) => {
			return PARTICIPATION_TYPE[record.corp_type];
		},
	},
	{
		title: '企业注册时间',
		dataIndex: 'register_date',
		key: 'register_date',
		render: (value) => {
			return value ? moment(value * 1000).format('YYYY-MM-DD') : '-';
		},
	},
	{
		title: '行政区域',
		dataIndex: 'adress',
		key: 'adress',
		render: (value) => {
			return value || '-';
		},
	},
];
// 通过[省代码，市代码，区代码] 格式化出地址
function formatArea(areaData: any[], codes: number[]) {
	let area = '';
	areaData.forEach((item) => {
		if (item.value == codes[0]) {
			area += item.label;
			area += formatArea(item.children, codes.slice(1));
		}
	});
	return area;
}
// 通过地区码转换为 [省代码，市代码，区代码]
function getAreaCode(code: number) {
	let provinceCode = +String(code).slice(0, 2) * 10000;
	let cityCode = +String(code).slice(0, 4) * 100;
	let areaeCode = code;
	return [provinceCode, cityCode, areaeCode];
}

const seeUnit: React.FC = (props) => {
	const [form] = Form.useForm();
	const [modalState, handleChangeModalState] = React.useState({
		visible: false,
	});
	const { state: uintlistState, request: requestUnitList } = useUnitList();
	const { state: updateState, request: requestUpdateUnit } = useUpdateUnit();
	const { state: addState, request: requestAddUnit } = useAddUnit();
	const { state: removeState, request: requestRemove } = useRemoveUnit();
	const { state: areaState, request: requestAreaTree } = useGetAreaTree();

	React.useEffect(() => {
		requestUnitList();
		requestAreaTree();
	}, []);
	// 表单数据添加地图
	const seeUnitFormData = useMemo(() => {
		return unitFormDataConfig.concat({
			label: '行政区域',
			name: 'area_code',
			required: true,
			children: (
				<Cascader
					options={areaState.dataSource.map((area) => {
						return {
							value: area.adcode,
							label: area.name,
							children: area.children,
						};
					})}></Cascader>
			),
		});
	}, [areaState.dataSource]);

	// 表格colum 添加
	const tableColums = useMemo(() => {
		return colums.concat({
			title: '操作',
			render: (_, record) => {
				const {
					name,
					social_code,
					register_date,
					area_code,
					corp_type,
				} = record;
				return (
					<Space>
						<Button
							type='primary'
							onClick={() => {
								handleChangeModalState((preState) => ({
									...preState,
									visible: true,
								}));
								form.setFieldsValue({
									name,
									social_code,
									corp_type,
									id: record.id,
									area_code: area_code
										? getAreaCode(+area_code).map(String)
										: '',
									register_date: register_date ? moment() : '',
								});
							}}>
							更新
						</Button>
						<Button danger onClick={() => handleRemoveUnit(record)}>
							删除
						</Button>
					</Space>
				);
			},
		});
	}, [areaState.dataSource]);
	// 提交表单
	const handleSubmitForm = useCallback(() => {
		form.validateFields().then(async (formdata: any) => {
			try {
				if (formdata.id ?? false) {
					await requestUpdateUnit({
						...formdata,
						area_code: formdata.area_code[2],
						register_date: formdata.register_date.unix(),
					});
				} else {
					await requestAddUnit({
						...formdata,
						corp_type: Number(formdata.corp_type),
						area_code: formdata.area_code[2],
						register_date: formdata.register_date.unix(),
					});
				}
			} catch (error) {
				message.error(error.message);
				return;
			}
			message.success('新增建设单位成功');
			handleChangeModalState((preState) => ({
				...preState,
				visible: false,
			}));
			requestUnitList();
			form.resetFields();
		});
	}, []);
	const handleSwitchModalVisible = () => {
		handleChangeModalState((preState) => {
			if (preState.visible) {
				form.resetFields();
			}
			return {
				...preState,
				visible: !preState.visible,
			};
		});
	};
	const handleRemoveUnit = (record: UnitRecordProps) => {
		Modal.confirm({
			title: '确认删除',
			content: `确认删除${record.name}建设单位吗?`,
			onOk: () => {
				return requestRemove({ id: record.id })
					.then(() => {
						requestUnitList();
						message.success('删除建设单位成功');
					})
					.catch((error) => {
						message.error(error.message);
					});
			},
			okButtonProps: {
				loading: removeState.loading,
			},
		});
	};
	// 计算行政区域值
	const tableDataSource = useMemo(() => {
		return uintlistState.dataSource.map((element) => {
			return {
				...element,
				adress: formatArea(
					areaState.dataSource,
					getAreaCode(+element.area_code)
				),
			};
		});
	}, [uintlistState.dataSource, areaState.dataSource]);
	return (
		<Fragment>
			<Row gutter={[0, 22]}>
				<Button type='primary' onClick={handleSwitchModalVisible}>
					新增
				</Button>
			</Row>
			<Table
				loading={uintlistState.loading}
				pagination={false}
				rowKey={(record) => record.id}
				columns={tableColums}
				dataSource={tableDataSource}></Table>
			<Modal
				okButtonProps={{ loading: updateState.loading || addState.loading }}
				onOk={handleSubmitForm}
				onCancel={handleSwitchModalVisible}
				visible={modalState.visible}
				title='参建单位'>
				<Form form={form} labelCol={{ span: 7 }}>
					{seeUnitFormData.map((formItem) => {
						return (
							<Form.Item
								key={formItem.name as string}
								rules={[{ required: true, message: `请填写${formItem.label}` }]}
								{...formItem}></Form.Item>
						);
					})}
					<Form.Item noStyle name='id'></Form.Item>
				</Form>
			</Modal>
		</Fragment>
	);
};
export default seeUnit;
