import {TableDropdown} from '@ant-design/pro-components';
import {Tag} from "antd";

/** 构造表头 */
export const columnsFactory = ({
  dataSource=[],
  onEdit,
  onEditRow,
  onDetail,
  onDelete,
  onCopy,
  ref
})=> {
  const colRender = dataSource.map(item=>{
    if (item.dataIndex==='status'){
      return {
        ...item,
        render: (text) => {
          const color = !text||text===0 ?"error":"success";
          const msg = !text||text===0 ?"失效":"有效";
          return <Tag color={color} key={text}>
            {msg}
          </Tag>
        }
      }
    }
    return item
  })

  const option = {
    title: '操作',
    valueType: 'option',
    key: 'option',
    render: (text, record, _, action) => {
      let creator = []
      // 打开编辑弹窗
      onEdit && creator.push(<a key="editable" onClick={()=>onEdit(record)}>编辑</a>);
      // 编辑当前行
      onEditRow && creator.push(<a key="editable" onClick={()=>action?.startEditable?.(record.id)}>编辑</a>);
      // 打开当前行明细
      onDetail && creator.push(<a target="_blank" rel="noopener noreferrer" key="view" onClick={()=>onDetail(record)}>查看</a>);
      // 下拉菜单中的选项
      if (onDelete || onCopy) {
        let menus = []
        onDelete && menus.push({key: 'delete', name: '删除'});
        onCopy && menus.push({key: 'copy', name: '复制'});
        creator.push(
          <TableDropdown
            key="actionGroup"
            onSelect={(event) => {
              event==='delete' && onDelete(record,()=>action?.reload())
              event==='copy' && onCopy(record,()=>action?.reload())
            }}
            menus={menus}
          />
        )
      }
      return ref ? <span ref={ref}>{creator}</span> : creator
    },
  }

  return [...colRender,option]
}

/** 获取下拉菜单 */
export const optionFactory=(values)=>(
  values.map(item=>({
    label:item.name||item.displayName,
    value:item.id,
  }))
)

