import React, { useState } from 'react';
import { View, Image } from '@tarojs/components';
import classNames from 'classnames';

const fullStarIcon = 'https://wanmi-b2b-x-site.oss-cn-shanghai.aliyuncs.com/pandora-ui/assets/components/images/star-rate/icon-star.png';
const emptyStarIcon = 'https://wanmi-b2b-x-site.oss-cn-shanghai.aliyuncs.com/pandora-ui/assets/components/images/star-rate/icon-empty-star.png';
const halfStarIcon = 'https://wanmi-b2b-x-site.oss-cn-shanghai.aliyuncs.com/pandora-ui/assets/components/images/star-rate/icon-half-star.png';

interface IStarProps {
  /** 当前评分 */
  rating?: number;
  /** 是否可编辑 */
  disabled?: boolean;
  /** 总分 */
  maxStars?: number;
  /** 是否展示半星 */
  halfStarEnabled?: boolean;
  /** 尺寸 */
  size?: 'large' | 'small';
  /** 评分变更回调 */
  onNumChange?: (num: number) => void;
}

/**
 * 评分组件
 */
const StartRate: React.FC<IStarProps> = ({
  rating = 0,
  maxStars = 5,
  disabled = false,
  halfStarEnabled = false,
  size = 'large',
  onNumChange = (_num: number) => {},
}) => {
  const [num, setNum] = useState<number>(rating);
  const imgStyle = classNames(size === 'small' ? 'img-small' : 'img');
  const clickAreaStyle = classNames(
    'click-area',
    size === 'small' && 'click-area-small',
  );

  const renderStart = () => {
    let idx = 0;
    const starButtons: JSX.Element[] = [];
    while (idx < maxStars) {
      const src = renderStarButton(idx);
      const key = idx;
      const star = (
        <View
          key={idx}
          className={clickAreaStyle}
          onClick={() => {
            if (!(disabled || halfStarEnabled)) {
              const newNum = key + 1;
              setNum(newNum);
              !!onNumChange && onNumChange(newNum);
            }
          }}>
          <Image src={src} className={imgStyle} />
        </View>
      );
      starButtons.push(star);
      idx += 1;
    }
    return starButtons;
  };

  const renderStarButton = (idx: number) => {
    // 不含半星
    if (!halfStarEnabled) {
      return num > idx ? fullStarIcon : emptyStarIcon;
    }
    if (num - idx === 0.5) {
      return halfStarIcon;
    } else if (num - idx > 1) {
      return fullStarIcon;
    }
    return emptyStarIcon;
  };

  return <View className='wm-star-box'>{renderStart()}</View>;
};

export default StartRate;
