import React, { useCallback, useEffect, useMemo, useState } from 'react'
import {observer} from 'mobx-react';
import Icon from '../../components/icons'
import Select from '../../components/Select'
import InputBox from '../../components/InputBox'
import NumberInput from '../../components/NumberInput'
import DatePicker from '../../components/DatePicker'
import DateRangePicker from '../../components/DateRangePicker'
import Modal from '../../components/Modal';
import Button from '../../components/Button';
import Spinner from '../../components/Spinner';
import CardToggler from './CardToggler'

interface OptionsType {
  label: string
  value: string
}

enum typeEnum {
  STRING = 'string',
  NUMBER = 'number',
  SELECT = 'select',
  DATE = 'date',
}

enum cardTypeEnum {
  PUBLIC = 'C',
  private = 'P'
}

const defaultTypeOprMap: any = {
  [typeEnum.STRING]: 'begin with',
  [typeEnum.NUMBER]: '=',
  [typeEnum.SELECT]: 'in',
  [typeEnum.DATE]: '=',
}
const typeOprMap: any = {
  [typeEnum.STRING]: [
    {label: '开头是', value: 'begin with'},
    {label: '开头不是', value: 'not begin with'},
    {label: '结尾是', value: 'end with'},
    {label: '结尾不是', value: 'not end with'},
    {label: '模糊匹配', value: 'like'},
    {label: '等于', value: '='},
    {label: '不等于', value: '<>'},
    {label: '为空', value: 'is null'},
    {label: '不为空', value: 'is not null'},
  ],
  [typeEnum.NUMBER]: [
    {label: '等于', value: '='},
    {label: '不等于', value: '<>'},
    {label: '大于', value: '>'},
    {label: '小于', value: '<'},
    {label: '大于等于', value: '>='},
    {label: '小于等于', value: '<='},
    {label: '介于', value: 'between'},
    {label: '为空', value: 'is null'},
    {label: '不为空', value: 'is not null'},
  ],
  [typeEnum.SELECT]: [
    {label: '包含', value: 'in'},
    {label: '不包含', value: 'not in'},
    {label: '为空', value: 'is null'},
    {label: '不为空', value: 'is not null'},
  ],
  [typeEnum.DATE]: [
    {label: '等于', value: '='},
    {label: '大于', value: '>'},
    {label: '小于', value: '<'},
    {label: '大于等于', value: '>='},
    {label: '小于等于', value: '<='},
    {label: '介于', value: 'between'},
    {label: '为空', value: 'is null'},
    {label: '不为空', value: 'is not null'},
  ]
}

const rendererTypeMap: any = {
  'input-text': typeEnum.STRING,
  'textarea': typeEnum.STRING,
  'input-number': typeEnum.NUMBER,
  'select': typeEnum.SELECT,
  'input-tag': typeEnum.SELECT,
  'input-date-range': typeEnum.DATE,
  'input-date': typeEnum.DATE,
}



const FilterTabItem = (props: any) => {
  let {
    classnames: cx,
    translate: __,
    filter,
    filterContent,

    curCardId,
    advancedFilter,
    setAdvancedFilter,

    resolveVariable,
  } = props


  const filterMap = useMemo(() => {
    let obj: any = {};
    filter.forEach((v: any)=>{
      obj[v.name] = v;
    })
    return obj
  }, [filter])

  function rendererTypeTransform(type: string){
    let _type = rendererTypeMap[type] || typeEnum.STRING;
    let opr = defaultTypeOprMap[_type]

    return {
      type: _type,
      opr
    }
  }
  function handleReplaceCardContent(content: any[][]){
    let _advancedFilter = advancedFilter.map((v: any)=>{
      if(v.CARD_ID === curCardId){
        return {
          ...v,
          CARD_CONTENT: content
        }
      }
      return v;
    })

    setAdvancedFilter(_advancedFilter)
  }

  // ❤
  function editDataKey(groupIndex: number, itemIndex: number, val: OptionsType){

    let content = filterContent.map((v: any, i: number)=>{
      if(i === groupIndex){
        return v.map((vv: any, ii: number)=>{
          let key = val.value;
          let curItem = filterMap[key];
          let {type: _type, opr} = rendererTypeTransform(curItem.type)

          if(ii === itemIndex){
            return {
              key,
              type: _type,
              typeValue: opr,
              value: []
            }
          }

          return vv;
        })
      }

      return v;
    })

    handleReplaceCardContent(content)

  }
  // ❤
  function editDataOpr(groupIndex: number, itemIndex: number, val: OptionsType){

    let content = filterContent.map((v: any, i: number)=>{
      if(i === groupIndex){
        return v.map((vv: any, ii: number)=>{
          let typeValue = val.value;

          if(ii === itemIndex){
            return {
              ...vv,
              typeValue,
              value: []
            }
          }

          return vv;
        })
      }

      return v;
    })

    handleReplaceCardContent(content)

  }
  // ❤
  function editDataVal(groupIndex: number, itemIndex: number, val: Array<string | number>){

    let content = filterContent.map((v: any, i: number)=>{
      if(i === groupIndex){
        return v.map((vv: any, ii: number)=>{

          if(ii === itemIndex){
            return {
              ...vv,
              value: val
            }
          }

          return vv;
        })
      }

      return v;
    })

    handleReplaceCardContent(content)
    
  }

  // ❤
  function addGroup(){

    let curFilter = filter?.[0] || {}
    let { name, type } = curFilter;
    let {type: _type, opr} = rendererTypeTransform(type)

    let content = filterContent.concat([[{
      key: name,
      type: _type,
      typeValue: opr,
      value: []
    }]])

    handleReplaceCardContent(content)
  }

  // ❤
  function addItem(groupIndex: number, availableFilter: any){

    let curFilter = availableFilter?.[0] || {}
    let { name, type } = curFilter;
    let {type: _type, opr} = rendererTypeTransform(type)

    let content = filterContent.map((v: any, i: number)=>{
      if(i === groupIndex){
        return v.concat([{
          key: name,
          type: _type,
          typeValue: opr,
          value: []
        }])
      }
      return v;
    })

    handleReplaceCardContent(content)
  }

  // ❤
  function delItem(groupIndex: number, itemIndex: number){

    let content = filterContent.reduce((mo: any[], v: any[], i: number) => {

      if(i === groupIndex){
        let group = v.slice();
        group.splice(itemIndex, 1)

        if(group.length){
          mo.push(group)
        }

      }else{
        mo.push(v)
      }
      return mo
    }, [])

    handleReplaceCardContent(content)
  }

  function renderDate(itemData: any, groupIndex: number, itemIndex: number, fieldInfo: any){
    let { typeValue, value } = itemData;
    if(typeValue === 'is null' || typeValue === 'is not null'){
      return null
    }
    let [val1='', val2=''] = value;
    if(typeValue === 'between'){
      return (
        <DateRangePicker
        value={[val1, val2]}
        placeholder={'Date.placeholder'}
        format={'YYYY-MM-DD'}
        dateFormat={'YYYY-MM-DD'}
        inputFormat={'YYYY-MM-DD'}
        popOverContainer={document.body}
        onChange={(val)=>{
          val = val? val.split(','): [];
          editDataVal(groupIndex, itemIndex, val)
        }}
        />
      )
    }
    return (
      <DatePicker
      value={val1}
      placeholder={'Date.placeholder'}
      format={'YYYY-MM-DD'}
      dateFormat={'YYYY-MM-DD'}
      inputFormat={'YYYY-MM-DD'}
      clearable={true}
      popOverContainer={document.body}
      onChange={(val) =>{
        if(val !== 'Invalid date'){// TODO. else 没处理
          val = val? [val]: []
          editDataVal(groupIndex, itemIndex, val)
        }
      }}
      />
    )
  }

  function renderSelect(itemData: any, groupIndex: number, itemIndex: number, fieldInfo: any){
    const options = resolveVariable(fieldInfo.source);

    let { typeValue, value } = itemData;
    if(typeValue === 'is null' || typeValue === 'is not null'){
      return null
    }
    return (
      <Select 
      value={value}
      options={options}
      clearable={false}
      multiple={true}
      searchable={true}
      popOverContainer={document.body}
      onChange={(value: OptionsType[]) => {
        let keys = value.map((v: any)=> v.value)
        editDataVal(groupIndex, itemIndex, keys)
      }}
      />
    )
  }

  function renderString(itemData: any, groupIndex: number, itemIndex: number, fieldInfo: any){
    let { typeValue, value } = itemData;
    if(typeValue === 'is null' || typeValue === 'is not null'){
      return null
    }

    let [ val1='' ] = value
    return (
      <InputBox
      value={val1}
      placeholder={'请输入'}
      disabled={false}
      readOnly={false}
      onChange={(val: string)=>{
        if(typeof val === 'string'){
          editDataVal(groupIndex, itemIndex, val? [val]: [])
        }
      }}
      />
    )

  }

  function renderNumber(itemData: any, groupIndex: number, itemIndex: number, fieldInfo: any){
    let { typeValue, value } = itemData;
    if(typeValue === 'is null' || typeValue === 'is not null'){
      return null
    }
    let [val1=undefined, val2=undefined] = value;
    if(typeValue === 'between'){
      return (
        <div className={cx('FilterCards-group-item-value-between')}>
          <NumberInput 
          value={val1} 
          onChange={(val: number)=>{
            let _val = val === 0 || val? [val, val2]: ['', val2]
            editDataVal(groupIndex, itemIndex, _val)
          }}/>
          <span>~</span>
          <NumberInput 
          value={val2} 
          onChange={(val: number)=>{
            let _val = val === 0 || val? [val1, val]: [val1, '']
            editDataVal(groupIndex, itemIndex, _val)
          }}/>
        </div>
      )
    }
    return (
      <NumberInput 
      value={val1} 
      onChange={(val: number)=>{
        let _val = val === 0 || val? [val]: []
        editDataVal(groupIndex, itemIndex, _val)
      }}/>
          
    )
  }

  function renderGroupItem(availableFilter: any[], itemData: any, groupIndex: number, itemIndex: number){
    let { key, type, typeValue, value } = itemData;

    let fieldOptions = [filterMap[key]].concat(availableFilter).map(v=>{
      return {
        label: v.label, value: v.name
      }
    })

    let fieldInfo = filter.filter((v: any) => v.name === key)[0] || {};

    return (
      <div className={cx('FilterCards-group-item')} key={itemIndex}>
          
        {/* 删除图标 */}
        <span role="presentation" className="icon-content" onClick={() => delItem(groupIndex, itemIndex)}>
          <Icon icon='sub' />
        </span>

        {/* 且 */}
        <span className={cx("FilterCards-group-item-and")}>{itemIndex? '且': null}</span>

        {/* 选择字段 */}
        <div className={cx('FilterCards-group-item-field')}>
          <Select 
            value={key}
            options={fieldOptions}
            clearable={false}
            searchable={true}
            multiple={false}
            popOverContainer={document.body}
            onChange={(val: OptionsType) => {
              editDataKey(groupIndex, itemIndex, val)
            }}
          />
        </div>

        {/* 选择操作符 */}
        <div className={cx('FilterCards-group-item-opr')}>
          <Select 
            value={typeValue}
            options={typeOprMap[type]}
            clearable={false}
            popOverContainer={document.body}
            onChange={(val: OptionsType) => {
              editDataOpr(groupIndex, itemIndex, val)
            }}
          />
        </div>

        {/* 选择值 */}
        <div className={cx('FilterCards-group-item-value')}>
          {
            type === typeEnum.DATE? renderDate(itemData, groupIndex, itemIndex, fieldInfo): null
          }
          {
            type === typeEnum.NUMBER? renderNumber(itemData, groupIndex, itemIndex, fieldInfo): null
          }
          {
            type === typeEnum.SELECT? renderSelect(itemData, groupIndex, itemIndex, fieldInfo): null
          }
          {
            type === typeEnum.STRING? renderString(itemData, groupIndex, itemIndex, fieldInfo): null
          }
        </div>


      </div>
    )
  }

  function renderGroup(groupData: any[], groupIndex: number){
    let usedFilterKeys = groupData.map(v=> v.key);
    let availableFilter = filter.filter((v: any) => !~usedFilterKeys.indexOf(v.name))
    return (
      <div className={cx('FilterCards-group')} key={groupIndex}>
        { groupIndex? <div className={cx("Group-split-line")}><span className={cx('Group-split-text')}>或</span></div>: null}

        {
          groupData.map((item: any, itemIndex: number)=> renderGroupItem(availableFilter, item, groupIndex, itemIndex))
        }
        
        {
          filter.length > groupData.length?(
            <div className={cx('FilterCards-group-item-add')} onClick={() => addItem(groupIndex, availableFilter)}>
              <span><Icon icon='add' /></span>添加条件
            </div>
          ): null
        }
        
      </div>
    )
  }
  function renderGroups(){
    return filterContent.map((groupData: any, i: number) => renderGroup(groupData, i))
  }

  function empty(){
    return (
      <div className={cx('FilterCards-editor-empty')}>
        暂无筛选条件，你可以通过
        <span className={cx('FilterCards-editor-empty-add')} onClick={addGroup}>添加条件组</span>
        来增加条件
      </div>
    )
  }
  return (
    <div className={cx(`FilterCards-editor`)}>
      <div className={cx(`FilterCards-editor-title`)}>筛选条件</div>
      <div className={cx('FilterCards-group-wrapper')}>
        { filterContent.length? renderGroups(): empty() }
      </div>

      <div className={cx('FilterCards-editor-group-add')} onClick={addGroup}>
        <Icon icon='add' />
        添加条件组
      </div>
    </div>
  )
}

export const AdvancedFilter = (props: any) => {
  let {
    classnames: cx,
    translate: __,
    filter,
    adFilter,
    env,

    resolveVariable,

    adFilterToggable,

    advancedFilter, 
    advancedFilterOriginal,

    curCardId,
    curAdFilterId,
    curAdvancedFilterCard, 

    setCurCardId,
    setCurAdFilterId,
    setAdvancedFilter,
    setAdvancedFilterOriginal,

    adFilterRequest,
  } = props




  let { addApi, editApi, saveAllApi } = adFilter || {};
  

  const [cardAddLoading, setCardAddLoading] = useState(false)
  const [cardSaveAsLoading, setCardSaveAsLoading] = useState(false)
  const [toggleSaveAs, setToggleSaveAs] = useState(false)
  const [viewName, setViewName] = useState('')

  let filterKeys = useMemo(() => {
    return filter.map((v: any)=> v.name)
  }, [filter])

  // 这里将filter里面没有的字段剔除
  let filterContent = (curAdvancedFilterCard.CARD_CONTENT || []).reduce((mo: any[], group: any) => {
    let groupArr = group.filter((item: any) => ~filterKeys.indexOf(item.key))
    if(groupArr.length){
      mo.push(groupArr)
    }
    return mo
  }, [])


  // ❤
  function add(){
    let _advancedFilter = advancedFilter.slice()

    var id = `高级筛选`
    var arrNum: number[] = [];

    _advancedFilter.map((v: any)=>{
        if(/^高级筛选\d+$/.test(v.CARD_NAME)){
            arrNum.push(+v.CARD_NAME.slice(4))
        }
    })

    var num = 1;
    if(arrNum.length){
        num = Math.max.apply(null, arrNum)+1
    }

    id += num,

    _advancedFilter.push({
      CARD_NAME: id,
      CARD_ID: id,
      CARD_CONTENT: [],
      CARD_DEFAULT: "N",
      CARD_DISPLAY: "Y",
      CARD_TYPE: "P",
      isSave: false,
    })
    setAdvancedFilter(_advancedFilter)
    setCurCardId(id)
  }

  // ❤
  async function save(): Promise<any>{
    if(cardAddLoading)return void 0;
    setCardAddLoading(true)
    let { CARD_CONTENT, CARD_NAME } = curAdvancedFilterCard;
    let json = null;

    if(curAdvancedFilterCard.isSave){
      // 编辑
      editApi = editApi.replace(/\:id/, curCardId)
      json = await adFilterRequest(editApi, {
        CARD_CONTENT: JSON.stringify(CARD_CONTENT)
      })

      if(json.ok) {
        env.notify('success', '保存成功');

        let _advancedFilterOriginal = advancedFilterOriginal.slice()

        _advancedFilterOriginal = _advancedFilterOriginal.map((v: any) =>{
          if(v.CARD_ID === curCardId){
            return {
              ...v,
              CARD_CONTENT: CARD_CONTENT
            }
          }
          return v;
        })

        setAdvancedFilterOriginal(_advancedFilterOriginal)
      }

    }else{
      // 新增
      json = await adFilterRequest(addApi, {
        CARD_NAME,
        CARD_CONTENT: JSON.stringify(CARD_CONTENT)
      })

      if(json.ok) {
        env.notify('success', '保存成功');

        let CARD_ID = json?.data?.CARD_ID || ''

        let _advancedFilter = advancedFilter.slice();
        let _advancedFilterOriginal = advancedFilterOriginal.slice()

        let cardInfo: any = null

        _advancedFilter = _advancedFilter.map((v: any)=>{
          if(v.CARD_ID === curCardId){
            cardInfo = {
              ...v,
              CARD_ID,
              isSave: true
            }
            return cardInfo
          }
          return v;
        })

        cardInfo = {...cardInfo}
        Reflect.deleteProperty(cardInfo, 'isSave')
        _advancedFilterOriginal.push(cardInfo)

        if(curCardId === curAdFilterId){
          setCurAdFilterId(CARD_ID)
        }

        setAdvancedFilter(_advancedFilter)
        setAdvancedFilterOriginal(_advancedFilterOriginal)
        setCurCardId(CARD_ID)
      }
    }

    
    setCardAddLoading(false)
  }

  // ❤
  async function saveAs(): Promise<any>{
    if(cardSaveAsLoading)return void 0;
    setCardSaveAsLoading(true)
    if(!viewName)return env.notify('error', '请输入卡片名称')

    let { CARD_CONTENT } = curAdvancedFilterCard;

    let json = await adFilterRequest(addApi, {
      CARD_NAME: viewName,
      CARD_CONTENT: JSON.stringify(CARD_CONTENT)
    })
    setCardSaveAsLoading(false)
    

    if(json.ok){
      env.notify('success', '保存成功');

      let CARD_ID = json?.data?.CARD_ID || ''

      let _advancedFilter = advancedFilter.slice();
      let _advancedFilterOriginal = advancedFilterOriginal.slice()
      let newAdvancedFilter = {
        ...curAdvancedFilterCard,
        CARD_NAME: viewName,
        CARD_ID,
        CARD_TYPE: 'P',
        CARD_DESC: '',
        CARD_DEFAULT: 'N',
        CARD_DISPLAY: 'Y',
      }
      _advancedFilter.push({
        ...newAdvancedFilter,
        isSave: true,
      })

      _advancedFilterOriginal.push(newAdvancedFilter)

      setAdvancedFilter(_advancedFilter)
      setAdvancedFilterOriginal(_advancedFilterOriginal)
      setCurCardId(CARD_ID)
      closeSaveAs()
    }

   
  }

  // ❤
  function restore(){
    let curOrgCard = advancedFilterOriginal.filter((card: any) => card.CARD_ID === curCardId)?.[0] || {};
    let _advancedFilter = advancedFilter.map((card: any) => {
      if(card.CARD_ID === curCardId){
        return {
          ...curOrgCard,
          isSave: true,
        }
      }
      return card
    })
    setAdvancedFilter(_advancedFilter)
  }

  function closeSaveAs() {
    setToggleSaveAs(false)
  }

  return (
    <>
    <div className={cx(`FilterCards`, {
      'FilterCards-show': adFilterToggable
    })}>
      <div className={cx('FilterCards-header')}>
        <div className={cx('FilterCards-header-left')}>
          <div className={cx('FilterCards-header--tabs')}>
            {
              advancedFilter.map((v: any)=>{
                return (
                  <span key={v.CARD_ID} className={
                    cx('FilterCards-header--tab', {
                      'is-active': v.CARD_ID === curCardId
                    })
                  }
                  onClick={() => {
                    setCurCardId(v.CARD_ID)
                  }}
                  >{v.CARD_NAME}</span>
                )
              })
            }
            
          </div>
        </div>
        <div className={cx('FilterCards-header-right')}>
          <div className={cx('FilterCards-header--plusIcon')} onClick={add}><Icon icon='add' /></div>
          <div className={cx('FilterCards-header--tools')}>
            {curAdvancedFilterCard.CARD_TYPE === cardTypeEnum.private? <span onClick={save}>保存</span>: null}
            <span onClick={() => setToggleSaveAs(true)}>另存为</span>
            {curAdvancedFilterCard.isSave?<span onClick={restore}>还原</span>: null}
          </div>

          <CardToggler {...props}/>
        </div>
      </div>

      <FilterTabItem {...props} filterContent={filterContent}/>

    </div>


    <Modal
      closeOnEsc
      onHide={closeSaveAs}
      show={toggleSaveAs}
      contentClassName={cx('CardToggler-modal')}
      overlay={true}
    >
      <header className={cx('CardToggler-modal-header')}>
        <span className={cx('CardToggler-modal-title')}>另存为卡片</span>
        <a
          data-tooltip={__('Dialog.close')}
          data-position="left"
          className={cx('Modal-close')}
          onClick={closeSaveAs}
        >
          <Icon icon="close" className="icon" />
        </a>
      </header>

      <div className={cx('CardToggler-modal-content', 'CardToggler-saveAs')}>
        <div className={cx('CardToggler-saveAs-label')}>卡片名称<span>*</span></div>
        <InputBox
        value={viewName}
        placeholder={'请输入'}
        disabled={false}
        readOnly={false}
        onChange={(val: string)=>{
          if(typeof val === 'string'){
            setViewName(val || '')
          }
        }}
        />
      </div>

      <footer className={cx('CardToggler-modal-footer')}>
        <div>
          <Button className="mr-4" onClick={closeSaveAs}>
            {__('cancel')}
          </Button>
          {
            cardAddLoading?
            <Spinner show={cardAddLoading}/>:
            <Button level="primary" onClick={saveAs}>
              {__('confirm')}
            </Button>
          }
        </div>
      </footer>
    </Modal>
    </>
  )
}

interface AdComponentIsType{
  filter: any[]
  onSelectFieldValue: (v: any) => any;
  onSelectFieldKey: (v:any) => any;
  resolveVariable: (v:any) => any;
  dynamicFieldKey: any
  dynamicFieldValue: any
  classnames: any
}

// 动态组件
export const AdComponentIs = (props: AdComponentIsType) => {
  let { filter, dynamicFieldKey, dynamicFieldValue, onSelectFieldValue, onSelectFieldKey,
    classnames: cx, resolveVariable } = props;
  
  useEffect(() => {
    if(filter.length){
      onSelectFieldKey(filter[0]['name'])
    }
  }, [])

  const filterTypeMap = useMemo(()=>{
    let obj: any = {}
    filter.forEach((v: any)=>{
      obj[v.name] = v
    })
    return obj
  }, [filter])

  const keyOptions = useMemo(()=>{
    return filter.map(v=>{
      return {
        label: v.label, value: v.name
      }
    })
  }, [filter])

  const renderKey = useCallback(() => {
    return (
      <Select 
        value={dynamicFieldKey}
        options={keyOptions}
        clearable={false}
        multiple={false}
        searchable={true}
        placeholder={'更多字段'}
        onChange={(value: OptionsType) => {
          onSelectFieldKey(value.value)
          onSelectFieldValue(null)
        }}
      />
    )
  }, [dynamicFieldKey])

  const renderValue = useCallback(() => {
    let type = rendererTypeMap[filterTypeMap[dynamicFieldKey]?.type] || typeEnum.STRING
    let valueDom = null
    switch(type){
      case typeEnum.STRING:
        valueDom = (
          <InputBox
          value={dynamicFieldValue}
          placeholder={'请输入'}
          disabled={false}
          readOnly={false}
          onChange={(val: string)=>{
            if(typeof val === 'string'){
              onSelectFieldValue(val)
            }
          }}
          />
        )
        break;
      case typeEnum.NUMBER:
          valueDom = (
            <NumberInput 
            value={dynamicFieldValue} 
            onChange={(val: number)=>{
              onSelectFieldValue(val === 0 || val? val: '')
            }}/>
          )
        break;
      case typeEnum.DATE:
        valueDom = (
          <DateRangePicker
          value={dynamicFieldValue}
          placeholder={'Date.placeholder'}
          format={'YYYY-MM-DD'}
          dateFormat={'YYYY-MM-DD'}
          inputFormat={'YYYY-MM-DD'}
          onChange={(val)=>{
            onSelectFieldValue(val)
          }}
          />
        )
        break;
      case typeEnum.SELECT:
        dynamicFieldKey
        const options = resolveVariable(filterTypeMap[dynamicFieldKey].source);
        valueDom = (
          <Select 
          value={dynamicFieldValue?dynamicFieldValue.split(','):[]}
          options={options}
          clearable={false}
          multiple={true}
          searchable={true}
          onChange={(value: OptionsType[]) => {
            let keys = value.map((v: any)=> v.value).join(',')
            onSelectFieldValue(keys)
          }}
          />
        )
        break;
    }

    return valueDom
  }, [dynamicFieldKey, dynamicFieldValue])

  if(!filter.length) return null
  return (
    <div className={cx('Dynamic-component')}>
      {renderKey()}
      {renderValue()}
    </div>
  )
}

interface AdFilterSearchGroupBoxType{
  classnames: any
  toggable: boolean
  showToggable: boolean// 是否显示高级筛选展开收缩按钮 默认开启
  showResetBtn: boolean// 是否显示重置按钮 默认显示
  onSearch: ()=>any;
  onReset: ()=>any;
  onToggable: ()=>any;
}

// 高级筛选查询按钮组
export const AdFilterSearchGroupBox = (props: AdFilterSearchGroupBoxType) => {
  let {
    classnames: cx,
    toggable,
    showToggable=true,
    showResetBtn=true,
    onSearch,
    onReset,
    onToggable,
  } = props;

  return (
    <div className={cx('Crud-header-control-btn')}>
      <span onClick={onSearch} className={cx('Crud-header-control-btn-search', 'Button--primary')}>
        <Icon icon='search'/>查询
      </span>
      {
        showResetBtn? (
          <span  onClick={onReset}>
            <Icon icon='reset'/>
          </span>
        ): null
      }
      {
        showToggable? (
          <span onClick={onToggable}>
            {toggable? <Icon icon='arrow-db-top'/>: <Icon icon='arrow-db-down'/>}
          </span>
        ): null
      }
    </div>
  )
}