/*
 * @Author: 吴永生#A02208 yongsheng.wu@wholion.com
 * @Date: 2022-05-31 10:18:13
 * @LastEditors: 吴永生 15770852798@163.com
 * @LastEditTime: 2022-07-28 18:10:42
 * @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 { IResponse, useHttp } from "@/api/http";
import { useStores } from "@/store";
import { useMessage } from "@/components/MySnackbar";
import MySelect, { IOption } from "@/components/mui/MySelect";
import MyTable from "@/components/mui/MyTable";
import SearchInput from "@/components/BusinessComponents/SearchInput";

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

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

	const http = useHttp();
	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 (
						<MySelect
							input={<OutlinedInput />}
							value={defaultValue?.length ? defaultValue[0]?.value : "VIEWER"}
							onChange={(val) => changePermission(val, index)}
							options={selectOptions}
							size="small"
						/>
					);
				},
			},
		];
	}, [changePermission, selectOptions]);

	useEffect(() => {
		if (addMemberDialog) {
			http.get<IResponse<any>>("/cpp/project/listroles").then((res) => {
				const arr = [];
				const { data } = res;
				for (const key in data) {
					arr.push({
						label: String(data[key]),
						value: key,
					});
				}
				setSelectOptions(arr);
			});
		}
	}, [addMemberDialog, http]);

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

	/** 获取表格数据 */
	useEffect(() => {
		if (!addMemberDialog) return;
		const projectInfo = toJS(currentProjectStore?.currentProjectInfo);
		http
			.get<IResponse<any>>("/cpp/project/listusers", {
				params: { id: projectInfo?.id || "" },
			})
			.then((res) => {
				setTableData(res?.data);
			});
	}, [currentProjectStore?.currentProjectInfo, http, addMemberDialog]);

	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) {
			http
				.put<IResponse<any>>(
					`/cpp/project/updatemember?id=${projectInfo?.id || ""}`,
					params
				)
				.then((res) => {
					const { errorCode } = res;
					if (errorCode === 0) {
						Message.success("新增成功！");
						getTableList();
						setAddMemberDialog(false);
					}
				});
		} else {
			Message.warning("请先选择项目成员！");
		}
	};

	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={{ overflowY: "scroll", maxHeight: 400 }}>
						<MyTable
							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);
