import {getDetailList, delDetail, getDetail, getPointByUuid} from '../../../services/measure/analysis'
import { useState, useEffect } from 'react'
import  {message, Button, type TableColumnsType, type TableProps, Modal, Table, Pagination, Input  } from 'antd';

import { useNavigate } from 'react-router-dom';
import type { DetailTable, SearchParams } from "../../../services/measure/type";
import { ExclamationCircleFilled } from '@ant-design/icons';

export default function MeasureDetail() {
	const navigate = useNavigate();
	const { Search } = Input;
	function onToMeasure(){
		navigate('/measure/config')
	}

	useEffect(()=>{
		const params = {
			pageSize,
			pageNum,
		}
		getDetailDataList(params)
	}, [])

	const [selectRows, setSelectedRow] = useState<DetailTable[]>([])
	const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
	const rowSelection = {
		selectedRowKeys,
		onChange: (selectedRowKeys: React.Key[], selectedRows: DetailTable[]) => {
			console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
			setSelectedRow(selectedRows)
			setSelectedRowKeys(selectedRowKeys)
		},
		getCheckboxProps: (record: DetailTable) => ({
			name: record.name,
		}),
	};

	const columns: TableColumnsType<DetailTable> = [
		{
			title: '序号',
			dataIndex: 'seq',
			render:(_, record, index)=>{
				return index + 1
			}
		},
		{
			title: '测量名称',
			dataIndex: 'name',
		},
		{
			title: '线路名称',
			dataIndex: 'lineName',
		},
		{
			title: '位置',
			dataIndex: 'location',
		},
		{
			title: '轨型',
			dataIndex: 'trackShapeCode',
			render:(_, record)=>{
				const trackShapeCode = record.trackShapeCode
				return trackShapeCode ? trackShapeCode : '无'
			}
		},
		{
			title: '方向',
			dataIndex: 'direction',
			render:(_, record)=>{
				const direction = record.direction
				return direction ? direction : '无'
			}
		},
		{
			title: '创建者',
			dataIndex: 'operatorName',
		},
		{
			title: '时间',
			dataIndex: 'createTime',
		},
		// {
		// 	title: '操作',
		// 	dataIndex: 'op',
		// 	width:180,
		// 	align:'center',
		// 	render:(_, record)=>{
		// 		return <div>
		// 			<Button type="link" onClick={()=>onDel(record)}>删除</Button>
		// 			<br/>
		// 			<Button type="link" onClick={()=>onShowDetail(record)}>导出测量数据</Button>
		// 			<br/>
		// 			<Button type="link" onClick={()=>onDetaiResult(record)}>导出分析结果</Button>
		// 		</div>
		// 	}
		// },
	];

	const [tableData, setTableData] = useState<DetailTable[]>([])
	const [total, setTotal] = useState(0)
	const getDetailDataList = (params:SearchParams) => {
		setLoading(true)
		getDetailList(params).then(res => {
			if(res.success){
				setLoading(false)
				//@ts-ignore
				setTableData(res.data.list)
				setTotal(res.data.total)
			}else{
				// setTableData(detailList)
			}
		}).catch(e=>{
			//如果接口异常，则使用mock数据
			// setTableData(detailList)
		}).finally(()=>{
			setLoading(false)
		})
	}
	
	const [selectionType, setSelectionType] = useState<'checkbox'>('checkbox');
	const { confirm } = Modal;
	const onBatchDel = () => {
		confirm({
			title: '提示',
			icon: <ExclamationCircleFilled />,
			content: '请确认是否删除选中的数据',
			okText:'确认',
			cancelText:'取消',
			onOk() {
				onHandelDelData()
			},
			onCancel() {
				console.log('Cancel');
			},
		});
	}
	
	const onDel = (item:DetailTable) => {
		confirm({
			title: '提示',
			icon: <ExclamationCircleFilled />,
			content: '请确认是否删除选中的数据',
			okText:'确认',
			cancelText:'取消',
			onOk() {
				doDel({ids:item.id})
			},
			onCancel() {
				console.log('Cancel');
			},
		});
	}

	const onShowDetail = (item:DetailTable)=> {
		message.warning('正在开发中')
		return;
		getDetail({id:item.id}).then(res=>{
			console.log('res==测量记录详情=', res)
			if(res){
				//@ts-ignore
				getRecordByUuid(res.data.uuid)
			}
		})
	}

	const onDetaiResult = (item:DetailTable) => {
		message.warning('正在开发中')
		return;
	}

	const getRecordByUuid = (uuid:string) => {
		getPointByUuid({uuid}).then(res=>{
			console.log('=========================', res)
		})
	}

	type DelParams = {
		ids: string | number;
	}
	const onHandelDelData = () =>{
		let list = [...selectRows]
		const ids = list.map(item => item.id)
		if(!ids ||  !ids.length){
			return;
		}
		const params = {
			ids:ids.join(',')
		}
		doDel(params)
		
	}

	const doDel = (params:DelParams) => {
		delDetail(params).then(res => {
			if(res.success){
				message.success('删除成功')	
				const params = {
					pageSize,
					pageNum,
				}
				getDetailDataList(params)
				setSelectedRowKeys([])
				setSelectedRow([])
				
			}
		}).catch(e=> {
			//删除mock的数据
			// const filterList = tableData && tableData.filter(item => !ids.includes(item.id))
			// setTableData(filterList)
			// message.success('删除成功')
			// setSelectedRow([])
		})
	}

	const [pageNum, setPageNum] = useState(1)
	const [pageSize, setPageSize] = useState(5)
	const onPageChange = (pageNumValue:number, pageSizeValue:number) => {
		setPageNum(pageNumValue)
		setPageSize(pageSizeValue)
		searchParams = {
			...searchParams,
			pageSize:pageSizeValue,
			pageNum:pageNumValue,
		}
		getDetailDataList(searchParams)
	}

	const [name, setName] = useState<string>()
	const [lineName, setLineName] = useState<string>()
	let searchParams:SearchParams = {
		pageNum,
		pageSize,
	}
	const onSearch = ()=> {
		setPageNum(1)
		setPageSize(5)
		searchParams = {
			pageSize,
			pageNum: 1,
			name,
			lineName
		}
		getDetailDataList(searchParams)
	}
	let [loading, setLoading] = useState(false)
	return (
		<div>
			<div className="p-[15px]">
				<Button 
				disabled={!selectRows.length}
				type="primary" 
				onClick={onBatchDel}>
					删除
				</Button>
				<Input className='ml-[2rem]' placeholder="测量名称" onChange={(e)=>setName(e.target.value)} style={{ width: 200 }}/>
				<Input className='ml-[2rem]' placeholder="线路名称" onChange={(e)=>setLineName(e.target.value)} style={{ width: 200 }}/>
				<Button type="primary" className='ml-[2rem]' onClick={onSearch}>搜索</Button>
			</div>
			<div>
				<Table<DetailTable>
					locale={{
						emptyText: '无数据',
					}}
					loading={loading}
					rowSelection={{ type: selectionType, ...rowSelection }}
					columns={columns}
					rowKey="id"
					dataSource={tableData && tableData.map(item => ({ ...item, key: item.name }))}
					pagination={false}
					scroll={{ y: 550 }} 

				/>
				<div className="float-right">
					<Pagination  onChange={onPageChange} current={pageNum} pageSizeOptions={[5,10,20,30]} defaultCurrent={pageNum} defaultPageSize={pageSize} total={total}/>
				</div>
			</div>

		</div>
	);
}
