import React from 'react'

import { type INotSlot, LxItem } from '../lxItem'

import type { BorderRadiusProps, SpaceProps, ColorProps } from '@lx-react-materiel/shared'
import { commonStyleFn } from '@lx-react-materiel/shared'

import type { ViewProps } from '@tarojs/components'
import { View } from '@tarojs/components'

import type { Required as IRequired } from 'utility-types'

import './index.less'

type IItem = Pick<INotSlot, 'label' | 'value'>

export interface LxItemGroupBasicProps extends BorderRadiusProps, SpaceProps, ColorProps, Pick<ViewProps, 'className' | 'children' | 'style'> {
  items: IItem[]
  options?: Omit<INotSlot, 'label' | 'value'> // 剩余配置
}

/**
 * 这里必备 className 是为了循环得到唯一 key
 */
export type LxItemGroupProps = IRequired<LxItemGroupBasicProps, 'items' | 'className'>

/**
 * 用于展示 label-value 分组数据
 *
 * @param props
 * @constructor
 *
 * @example
 *
 * // 用法1
 *
 * <LxItemGroup
 *   borderRadius={16}
 *   className="order-item-group"
 *   items={[
 *     {
 *       label: '订单编号',
 *       value: '123123'
 *     },
 *     {
 *       label: '创建时间',
 *       value: '2023-05-10 12:52:32'
 *     },
 *     {
 *       label: '支付方式',
 *       value: '微信支付'
 *     }
 *   ]}
 *   marginTop={55}
 * />
 *
 * // 用法2：传入子项 options 配置
 *
 * <LxItemGroup
 *   borderRadius={16}
 *   className="order-item-group"
 *   items={[
 *     {
 *       label: '订单编号',
 *       value: '123123'
 *     },
 *     {
 *       label: '创建时间',
 *       value: '2023-05-10 12:52:32'
 *     },
 *     {
 *       label: '支付方式',
 *       value: '微信支付'
 *     }
 *   ]}
 *   marginTop={55}
 * />
 */
export function LxItemGroup (props: LxItemGroupProps) {
  const {
    className = '',
    items,
    options,
    style = commonStyleFn(props),
    ...groupRest
  } = props

  // 获取子项 lxItem 配置
  const {
    borderRadius = 0,
    background = '#fff',
    leftColor = '#989EA9',
    rightColor = '#141E33',
    ...rest
  } = options ?? {}

  // 单项 LxItem 属性
  const mergeItem = (item: IItem) => ({
    ...item,
    ...rest,
    leftColor,
    rightColor,
    background,
    // group下 Item 不需要有圆角
    borderRadius
  })

  const mergeProps = {
    ...groupRest,
    className: `lx-item__group ${className ?? ''}`,
    style
  }

  return (
    <View { ...mergeProps }>
      {
        items.map((item, index) => <LxItem key={`${className}-item-${index}`} {...mergeItem(item)}></LxItem>)
      }
    </View>
  )
}

export default LxItemGroup
