import {styled} from 'styled-components'
import {ProFormList, ProFormSelect, ProFormText,ProFormGroup,ProFormSegmented} from '@ant-design/pro-components'
import {memo, useState, forwardRef, useMemo} from 'react'
import {LOGIC_TYPE} from "../pages/IndexDefine/constants";

const component = forwardRef(({
  options
},ref) => {
  const [count,setCount]=useState(0);

  const joinLogic=(index)=>{
    const display = ( index !== (count-1) )
    if (display){
      return <ProFormSegmented
        name="condition"
        fieldProps={{style:{marginLeft:"50%"}}}
        initialValue="and"
        valueEnum={{
          and: '并且',
          or: '或者',
        }}
      />
    }
  }

  const fields = useMemo(()=>{
    if (options){
      const fieldsOptions = [];
      const {dimensions,measures} = options;
      dimensions.forEach(({name,bizName})=>{
        fieldsOptions.push({
          label: name,
          value: bizName,
        })
      })
      measures.forEach(({name,bizName})=>{
        fieldsOptions.push({
          label: name,
          value: bizName,
        })
      })
      return fieldsOptions
    }
    return []
  },[options])

  return (
    <Container ref={ref}>
      <CustomFromList
        min={1}
        name="attributes"
        wrapperCol={{span:24}}
        creatorButtonProps={{
          creatorButtonText: '添加条件'
        }}
        onAfterAdd={(e,s,c)=>{setCount(c)}}
        onAfterRemove={(e,c)=>{setCount(c)}}
        itemContainerRender={(doms,{index})=> {
          return <>
            {doms}
            {joinLogic(index)}
          </>
        }}
      >
        <ProFormGroup key="group">
          <ProFormSelect
            width="sm"
            name="fields"
            placeholder="请选择字段"
            options={fields}
          />
          <ProFormSelect
            width="sm"
            name="logic"
            placeholder="请选择逻辑"
            valueEnum={LOGIC_TYPE}
          />
          <ProFormText
            width={250}
            name="value"
            placeholder="请输入值"
          />
        </ProFormGroup>
      </CustomFromList>
    </Container>
  )
})

export const LogicPanel = memo(component)

const CustomFromList=styled(ProFormList)`
  .ant-form-item {
    margin-bottom: 5px;
  }
  .ant-pro-form-list-action{
    margin-block-end: 0;
    line-height: 0;
    height: 29px;
  }
`
const Container = styled.div`
  width: 95%;
  padding-block-end: 1px;
  padding-block-start: 15px;
  padding-inline-end: 20px;
  padding-inline-start: 20px;
  background-color: #f5f5f5;
  min-height: 68px;
`
