/*
 * @Author: 吴永生 15770852798@163.com
 * @Date: 2022-07-11 11:56:58
 * @LastEditors: 吴永生 15770852798@163.com
 * @LastEditTime: 2022-08-02 17:40:14
 * @FilePath: /bkunyun/src/components/CommonComponents/RadioGroupOfButtonStyle/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// 按钮样式的单选组
import classnames from "classnames";
import { useMemo } from "react";
import style from "./index.module.css";

type radioOption = {
	value: string;
	label: string;
};

type IRadioGroupOfButtonStyleProps = {
	radioOptions: Array<radioOption>;
	value: string;
	handleRadio: any;
	RadiosBoxStyle?: object;
	radioStyle?: object;
	radioActiveBgBoxStyle?: object;
};

const RadioGroupOfButtonStyle = (props: IRadioGroupOfButtonStyleProps) => {
	const {
		radioOptions,
		value,
		handleRadio,
		RadiosBoxStyle,
		radioStyle,
		radioActiveBgBoxStyle,
	} = props;

	const radioWidth = useMemo(() => {
		if (radioOptions.length) {
			return Number((100 / radioOptions.length).toFixed(2));
		} else {
			return 100;
		}
	}, [radioOptions]);

	const activeIndex: any = useMemo(() => {
		let res = 0;
		radioOptions.forEach((item, index) => {
			if (item.value === value) {
				res = index;
			}
		});
		return res;
	}, [value, radioOptions]);

	return (
		<div className={style.RadiosBox} style={RadiosBoxStyle}>
			<div className={style.radioActiveBgBox} style={radioActiveBgBoxStyle}>
				<div
					className={style.radioActiveBg}
					style={{
						width: `${radioWidth}%`,
						transform: `translateX(${activeIndex * 100}%)`,
					}}
				></div>
			</div>

			{radioOptions.map((options, index) => {
				return (
					<div
						key={options.value}
						className={style.radioBox}
						onClick={() => handleRadio(options.value)}
					>
						<div
							className={classnames({
								[style.radio]: true,
								[style.radioActive]: value === options.value,
							})}
							style={radioStyle}
						>
							{options.label}
						</div>
						<div
							className={classnames({
								[style.border]: true,
								[style.borderHidden]: !(
									index !== radioOptions.length - 1 &&
									index !== activeIndex &&
									index !== activeIndex - 1
								),
							})}
						></div>
					</div>
				);
			})}
		</div>
	);
};

export default RadioGroupOfButtonStyle;
