import {forwardRef, memo, useMemo, useState} from 'react';
import {styled} from 'styled-components'
import {Button, Col, Row} from 'antd'

/**
 *
 * @type {React.NamedExoticComponent<{readonly options?: *, readonly title?: *, readonly onSelect?: *}>}
 */

const component = forwardRef(({
  mode="radio",
  type,
  title,
  options,
  link,
  defaultCheck,
  onClick,
  onSelect,
  onChange
},ref) => {
  const isArray = Object.prototype.toString.call(options) === '[object Array]';
  const [checked, setChecked] = useState(defaultCheck);
  const isValueArray = Object.prototype.toString.call(checked) === '[object Array]';
  // 按钮类型判断
  const buttonType = (value)=>{
    let status = false
    if (mode==="radio"){
      status = checked===value
    }
    if (mode==="checkBox"){
      status = (isValueArray?checked:[]).includes(value)
    }
    return status?"primary":"default"
  }

  // 点击事件处理
  const onCellClick = (value,item) => {
    if (mode==="radio"){
      setChecked(value)
      onSelect(value,item)
    }
    if (mode==="checkBox"){
      let newChecked = []
      let newMap = []
      const init = isValueArray?checked:[]
      const exist = init.includes(value)
      if (exist){
        newChecked = init.filter(item=>item!==value)
        newMap = options.filter(obj1 => newChecked.some(obj2 => obj1.value === obj2));
      }else {
        newChecked = init.concat(value)
        newMap = options.filter(obj1 => newChecked.some(obj2 => obj1.value === obj2));
      }
      setChecked(newChecked)
      onChange(newChecked,newMap)
    }
  }

  const memoOption = useMemo(()=>[
    options?.map(item => (
      <CustomButton
        key={item?.value}
        type={buttonType(item?.value)}
        onClick={() => onCellClick(item?.value,item)}
      >
        {item?.label}
      </CustomButton>
    ))
  ],[options,checked])
  return (
    <Container ref={ref}>
      <Row>
        {title && <Col span={2} style={{textAlign:"right"}}><Span>{title}:</Span></Col>}
        <Col span={22}>
          {
            isArray? memoOption :<CustomButton type={type?type:"link"} children={<Span>{link}</Span>} onClick={onClick}/>
          }
        </Col>
      </Row>


    </Container>
  )
})
export const RadioCheckButton = memo(component);

const Container = styled.div`
  line-height: 40px
`;

const Span = styled.span`
  font-size: ${p => p.theme.fontSizeLG + 'px'};
  font-weight: bold;
`;

const CustomButton = styled(Button)`
  margin-left: 15px;
`;
