/*
 * @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, useState } from "react";
import { Box } 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/MyTableNew";
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 = [
		{ id: "username", label: "项目成员", width: 200 },
		{
			id: "projectRole",
			label: "项目权限",
			width: 100,
		},
	];

	const randerRole = (item: any, index: number) => {
		const defaultValue = selectOptions.filter(
			(every) => every.value === item.projectRole
		);
		return (
			<MyBorderlessSelect
				value={defaultValue?.length ? defaultValue[0]?.value : "VIEWER"}
				onChange={(val) => changePermission(val, index)}
				options={selectOptions}
				size="small"
				sx={{ position: "relative", left: "-13px" }}
			/>
		);
	};

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

	// 获取表格数据接口
	const { run: getProjectUsersList, loading } = 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) {
			setProjectMember("");
			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={{ height: "320px" }}>
						<MyTable
							noDataText={
								projectMember ? `暂无 "${projectMember}" 搜索结果` : undefined
							}
							tableKey="username"
							hasCheckbox={true}
							selectItems={checkData}
							setSelectItems={setCheckData}
							fixedHead={true}
							rows={filterTableData.map((item: any, idnex) => ({
								...item,
								projectRole: randerRole(item, idnex),
							}))}
							headCells={columns}
							loading={loading}
						/>
					</div>
				</Box>
			</Dialog>
		</>
	);
});

export default memo(AddMember);
