/*
 * @Author: 吴永生#A02208 yongsheng.wu@wholion.com
 * @Date: 2022-05-31 10:18:13
 * @LastEditors: 吴永生 15770852798@163.com
 * @LastEditTime: 2022-09-01 16:14:10
 * @FilePath: /bkunyun/src/views/Project/ProjectSetting/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { toJS } from "mobx";
import { observer } from "mobx-react-lite";
import _ from "lodash";
import { memo, useCallback, useEffect, useMemo, useState } from "react";
import { Box, OutlinedInput } from "@mui/material";

import Dialog from "@/components/mui/MyDialog";
import useMyRequest from "@/hooks/useMyRequest";
import { useStores } from "@/store";
import { useMessage } from "@/components/MySnackbar";
import MyBorderlessSelect, { IOption } from "@/components/mui/MyBorderlessSelect";
import MyTable from "@/components/mui/MyTable";
import SearchInput from "@/components/BusinessComponents/SearchInput";
import {
	addProjectUser,
	fetchProjectPower,
	fetchProjectUsersList,
} from "@/api/project_api";

interface IProps {
	setAddMemberDialog: (val: boolean) => void;
	addMemberDialog: boolean;
	getTableList: () => void;
}

const AddMember = observer((props: IProps) => {
	const { addMemberDialog, setAddMemberDialog, getTableList } = props;

	const { currentProjectStore } = useStores();

	const [tableData, setTableData] = useState([]);
	const [projectMember, setProjectMember] = useState("");
	const [filterTableData, setFilterTableData] = useState([]);
	const [checkData, setCheckData] = useState<string[]>([]);
	const [selectOptions, setSelectOptions] = useState<IOption[]>([]);
	const Message = useMessage();

	const changePermission = useCallback(
		(val: string, index: number) => {
			const tableDataIndex = tableData[index] as any;
			const newVal = { ...tableDataIndex, projectRole: val };
			const newTableData = _.cloneDeep(tableData);
			newTableData.splice(index, 1, newVal);
			setTableData(newTableData);
		},
		[tableData]
	);

	const columns = useMemo(() => {
		return [
			{ id: "checkbox", width: 50 },
			{ id: "username", label: "项目成员", width: 160 },
			{
				id: "projectRole",
				label: "项目权限",
				width: 160,
				render: (item: string, row: any, index: number) => {
					const defaultValue = selectOptions.filter(
						(every) => every.value === item
					);
					return (
							<MyBorderlessSelect
								value={defaultValue?.length ? defaultValue[0]?.value : "VIEWER"}
								onChange={(val) => changePermission(val, index)}
								options={selectOptions}
								size="small"
							/>
					);
				},
			},
		];
	}, [changePermission, selectOptions]);

	/** 过滤表格数据 */
	useEffect(() => {
		if (!!projectMember) {
			const newVal =
				tableData.filter((item: any) => {
					return item?.username?.includes(projectMember);
				}) || [];
			setFilterTableData(newVal || []);
		} else {
			setFilterTableData(tableData);
		}
	}, [projectMember, tableData]);

	// 获取表格数据接口
	const { run: getProjectUsersList } = useMyRequest(fetchProjectUsersList, {
		onSuccess: (res: any) => {
			setTableData(res?.data);
		},
	});

	// 获取项目权限
	const { run: getProjectPower } = useMyRequest(fetchProjectPower, {
		onSuccess: (res: any) => {
			setSelectOptions(res.data);
		},
	});

	// 添加项目成员
	const { run: saveProjectUser } = useMyRequest(addProjectUser, {
		onSuccess: (res: any) => {
			const { errorCode } = res;
			if (errorCode === 0) {
				Message.success("新增成功！");
				getTableList();
				setAddMemberDialog(false);
			}
		},
	});

	useEffect(() => {
		if (addMemberDialog) {
			getProjectPower();
		}
	}, [addMemberDialog, getProjectPower]);

	/** 获取表格数据 */
	useEffect(() => {
		if (!addMemberDialog) return;
		const projectInfo = toJS(currentProjectStore?.currentProjectInfo);
		getProjectUsersList({ id: projectInfo?.id || "" });
	}, [
		currentProjectStore?.currentProjectInfo,
		addMemberDialog,
		getProjectUsersList,
	]);

	const onClose = (event: any = {}, reason: any = "other") => {
		// 点击弹窗外不关闭弹窗
		if (reason === "backdropClick") {
			return;
		}
		setAddMemberDialog(false);
	};

	const onConfirm = () => {
		const projectInfo = toJS(currentProjectStore?.currentProjectInfo);
		const params = tableData.filter((item: any) => {
			return checkData.includes(item?.username);
		});
		if (params.length) {
			saveProjectUser(projectInfo?.id || "", params);
		} else {
			Message.info("请先选择项目成员！");
		}
	};

	return (
		<>
			<Dialog
				open={addMemberDialog}
				onClose={onClose}
				onConfirm={onConfirm}
				title="添加成员"
			>
				<Box>
					<SearchInput
						onKeyUp={(e: any) => {
							if (e.keyCode === 13) {
								setProjectMember(e.target.value);
							}
						}}
						placeholder="搜索项目成员"
						sx={{ mb: 2 }}
					/>
					<div style={{ overflow: "overlay", maxHeight: 400 }}>
						<MyTable
							noDataText={
								projectMember ? `暂无 "${projectMember}" 搜索结果` : undefined
							}
							tableContainerStyle={{ height: 346 }}
							checkboxData={(val: string[]) => setCheckData(val)}
							param="username"
							disabledParam={"enabled"}
							rowHover={true}
							stickyHeader={true}
							rows={filterTableData}
							rowsPerPage="99"
							headCells={columns}
							footer={false}
							tableStyle={{ minWidth: "auto" }}
							borderBottom="none"
						/>
					</div>
				</Box>
			</Dialog>
		</>
	);
});

export default memo(AddMember);
