import React, { useCallback, useState } from 'react';
import Sortable from 'sortablejs';
import cloneDeep from 'lodash/cloneDeep';
import {observer} from 'mobx-react';
import {RendererProps} from '../../factory';
import Modal from '../../components/Modal';
import Button from '../../components/Button';
import Spinner from '../../components/Spinner';
import TooltipWrapper from '../../components/TooltipWrapper';
import type {TooltipObject} from '../../components/TooltipWrapper';
import {noop, autobind} from '../../utils/helper';
import {Icon} from '../../components/icons';

export interface CardTogglerProps extends RendererProps {
  
  /**
   * 按钮提示文字，hover focus 时显示
   */
  tooltip?: string | TooltipObject;

  /**
   * 点击内容是否关闭
   */
  closeOnClick?: boolean;

  /**
   *  CardToggler的CSS类名
   */
  className?: string;

  /**
   * 是否显示遮罩层
   */
  overlay?: boolean;

  modalContainer?: () => HTMLElement;
}

export interface CardTogglerState {
  loading: boolean;
  isOpened: boolean;
}

const CardToggler = (props: any) => {
  const {
    placement='top',
    tooltipTrigger=['hover'],
    classPrefix: ns,
    translate: __,
    classnames: cx,
    advancedFilterOriginal,

  } = props;

  const [loading, setLoading] = useState(false)
  const [toggable, setToggable] = useState(false)
  const [advancedFilterTemp, setAdvancedFilterTemp] = useState<any[]>([])

  function open() {

    setAdvancedFilterTemp(advancedFilterOriginal.slice())

    setToggable(true)
  }

  function close() {
    setToggable(false)
  }


  function handleHide(index: number){
    let _advancedFilterTemp = advancedFilterTemp.map((v: any, i: number)=>{
      if(index === i){
        return {
          ...v,
          CARD_DISPLAY: v.CARD_DISPLAY === 'Y'? 'N': 'Y',
        }
      }
      return v;
    })

    setAdvancedFilterTemp(_advancedFilterTemp)
  }
  function handleDel(index: number){
    let _advancedFilterTemp = advancedFilterTemp.slice();

    _advancedFilterTemp.splice(index, 1)

    setAdvancedFilterTemp(_advancedFilterTemp)
  }

  function handleDefault(index: number){

    let _advancedFilterTemp = advancedFilterTemp.map((v: any, i: number)=>{
      return {
        ...v,
        CARD_DEFAULT: index === i? 'Y': 'N',
        CARD_DISPLAY: index === i? 'Y': v.CARD_DISPLAY,
      }
    })

    setAdvancedFilterTemp(_advancedFilterTemp)
  }

  function handleInput(index: number, val: string){
    let _advancedFilterTemp = advancedFilterTemp.map((v: any, i: number)=>{
      if(index === i){
        return {
          ...v,
          CARD_NAME: val
        }
      }
      return v;
    })

    setAdvancedFilterTemp(_advancedFilterTemp)
  }

  async function onConfirm() {
    if(loading)return void 0;
    let {
      env,
      adFilter,

      advancedFilter,
      curCardId,
      curAdFilterId,

      setCurCardId,
      setCurAdFilterId,
      setAdvancedFilter,
      setAdvancedFilterOriginal,
      
      adFilterRequest,

    } = props
    let _advancedFilterTemp = advancedFilterTemp.slice()
    setLoading(true)
    let json = await adFilterRequest(adFilter?.saveAllApi, {
      FILTER_LIST: _advancedFilterTemp.map((v: any)=>{
        return {
          ...v,
          CARD_CONTENT: JSON.stringify(v.CARD_CONTENT)
        }
      })
    })
    setLoading(false)

    if(json.ok){
      let filterOriginal = _advancedFilterTemp.slice()
      let advancedFilterMap: any = {};
      
      // 之前未保存的
      let unSaveLlist = advancedFilter.filter((v: any)=> {
        advancedFilterMap[v.CARD_ID] = v;
        return !v.isSave;
      })
      // 显示的卡片
      let _advancedFilter = filterOriginal.filter((v: any)=> v.CARD_DISPLAY === 'Y').map((v: any)=>{
        if(v.CARD_ID in advancedFilterMap){
          return {
            ...v,
            CARD_CONTENT: advancedFilterMap[v.CARD_ID]['CARD_CONTENT'],
            isSave: true
          }
        }
        return {
          ...v,
          isSave: true
        }
      }).concat(unSaveLlist)

      if(!_advancedFilter.length){
       
        let CARD_ID = "高级筛选1";
        _advancedFilter = [{
          CARD_ID,
          CARD_NAME: CARD_ID,
          CARD_CONTENT: "",
          CARD_DEFAULT: "N",
          CARD_DISPLAY: "Y",
          CARD_TYPE: "P",
          isSave: false,
        }] as any
      }

      setAdvancedFilter(_advancedFilter)

      // 设置curCardId
      let curCard = _advancedFilter.filter((v: any)=> v.CARD_ID === curCardId)[0]
      if( !curCard ){
        setCurCardId(_advancedFilter[0]['CARD_ID'])
      }

      // 设置 curAdFilterId
      let curFilter = filterOriginal.filter((v: any)=> v.CARD_ID === curAdFilterId)[0]
      if( !curFilter ){
        let filterId = filterOriginal.filter((v: any)=> v.CARD_DEFAULT === 'Y')?.[0]?.CARD_ID || null
        setCurAdFilterId(filterId)
      }

      // 设置 advancedFilterOriginal
      setAdvancedFilterOriginal(filterOriginal)

      close();
    }
  }


  const renderModal = useCallback(() => {
    return (
      <Modal
        closeOnEsc
        onHide={close}
        show={toggable}
        contentClassName={cx('CardToggler-modal')}
        container={document.body}
        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={close}
          >
            <Icon icon="close" className="icon" />
          </a>
        </header>

        <div className={cx('CardToggler-modal-content')}>
          <table className={cx('CardToggler-modal-content-table')}>
            <thead>
              <tr>
                <th>筛选名称</th>
                <th>类型</th>
                <th>显示</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              {
                advancedFilterTemp.map((v: any, i: number)=>{
                  let { CARD_NAME, CARD_TYPE, CARD_DISPLAY, CARD_DEFAULT } = v;

                  return (
                    <tr key={i}>
                      <td>
                        {
                          CARD_TYPE === 'P'? (
                            <input className={cx("filter-input")} value={CARD_NAME} onChange={(e) => handleInput(i, e.target.value)} placeholder="请输入" />
                          ): CARD_NAME
                        }
                      </td>
                      <td>{CARD_TYPE === 'P'? '私有': CARD_TYPE === 'C'? '公共': ''}</td>
                      <td>{CARD_DISPLAY === 'Y'? '是': CARD_DISPLAY === 'N'? '否': ''}</td>
                      {
                        CARD_DEFAULT === 'Y'? (
                          <td><span className={cx('Default-show')}>已默认</span></td>
                        ): (
                          <td>
                            <span onClick={() => handleHide(i)}>{CARD_DISPLAY === 'Y'?'隐藏': '取消隐藏'}</span>｜
                            <span onClick={() => handleDefault(i)}>默认</span>
                            {CARD_TYPE === 'P'? <>｜<span onClick={() => handleDel(i)}>删除</span></>:null}
                          </td>
                        )
                      }
                    </tr>
                  )
                })
              }
            </tbody>
          </table>
        </div>

        <footer className={cx('CardToggler-modal-footer')}>
          <div>
            <Button className="mr-4" onClick={close}>
              {__('cancel')}
            </Button>
            {
              loading? <Spinner show={true}/> :(
                <Button level="primary" onClick={onConfirm}>
                  {__('confirm')}
                </Button>
              )
            }
          </div>
        </footer>
      </Modal>
    )
  }, [toggable, advancedFilterTemp, loading])

  const button = <div onClick={open} className={cx('FilterCards-header--listIcon')}><Icon icon='list' /></div>
  return (
    <>
    <TooltipWrapper
      placement={placement}
      tooltip={'管理卡片'}
      trigger={tooltipTrigger}
    >
      {button}
    </TooltipWrapper>

    {renderModal()}
    </>
  );
}

export default CardToggler
