import React, { useCallback, useEffect, useMemo, useState } from 'react'
import styles from './index.module.scss'
import { Button, Switch } from 'antd'
import { useDispatch, useSelector } from 'react-redux'
import {
  A0_APIdel,
  A0_APIgetList,
  A0_APIgetTinfo,
  A0_APIswitch
} from '@/store/action/A0home'
import { RootState } from '@/store'
import MyTable from '@/components/MyTable'
import { A0listType, A0Ttype } from './data'
import { MessageFu } from '@/utils/message'
import A0Tedit from './A0Tedit'
import dayjs from 'dayjs'
import MyPopconfirm from '@/components/MyPopconfirm'
import { A0tableC } from '@/utils/tableData'
import A0imgAdd from './A0imgAdd'
function A0home() {
  const dispatch = useDispatch()

  const getTinfoFu = useCallback(async () => {
    dispatch(A0_APIgetTinfo())
  }, [dispatch])

  useEffect(() => {
    getTinfoFu()
  }, [getTinfoFu])

  const { Tinfo, imgList } = useSelector((state: RootState) => state.A0home)

  // 开启和关闭
  const switchChange = useCallback(
    async (id: number, val: boolean) => {
      const res = await A0_APIswitch(id, val ? 1 : 0)
      if (res.code === 0) {
        MessageFu.success(`${val ? '开启' : '关闭'}成功`)
        getTinfoFu()
      }
    },
    [getTinfoFu]
  )

  // 通知管理-点击编辑

  const [editTinfo, setEditTinfo] = useState({} as A0Ttype)

  const tableLastBtn1 = useMemo(() => {
    return [
      {
        title: '生效期',
        render: (item: A0Ttype) =>
          item.deadline === 1
            ? '长期'
            : dayjs(item.dateStart).format('YYYY-MM-DD') +
              ' 至 ' +
              dayjs(item.dateEnd).format('YYYY-MM-DD')
      },
      {
        title: '正文',
        width: 800,
        render: (item: A0Ttype) => {
          let txt = '（空）'
          const valArr = JSON.parse(item.rtf || '{txtArr:[]}')
          if (valArr.txtArr.length) {
            const val = valArr.txtArr[0]
            if (val.tableTxt)
              txt =
                val.tableTxt.length >= 100 ? (
                  <span style={{ cursor: 'pointer' }} title={val.tableTxt}>
                    {val.tableTxt.substring(0, 100) + '...'}
                  </span>
                ) : (
                  val.tableTxt
                )
          }
          return txt
        }
      },
      {
        title: '操作',
        render: (item: A0Ttype) => (
          <>
            <Button size='small' type='text' onClick={() => setEditTinfo(item)}>
              编辑
            </Button>
          </>
        )
      }
    ]
  }, [])

  // ------------------------BANNER管理-----------------------------
  const getImgListFu = useCallback(async () => {
    dispatch(A0_APIgetList())
  }, [dispatch])

  useEffect(() => {
    getImgListFu()
  }, [getImgListFu])

  // 点击删除
  const delTableFu = useCallback(
    async (id: number) => {
      const res = await A0_APIdel(id)
      if (res.code === 0) {
        MessageFu.success('删除成功!')
        getImgListFu()
      }
    },
    [getImgListFu]
  )

  // 新增和编辑
  const [imgInfo, setImgInfo] = useState({} as A0listType)

  const tableLastBtn2 = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: A0listType) => (
          <>
            <Button size='small' type='text' onClick={() => setImgInfo(item)}>
              编辑
            </Button>
            <MyPopconfirm txtK='删除' onConfirm={() => delTableFu(item.id)} />
          </>
        )
      }
    ]
  }, [delTableFu])

  return (
    <div className={styles.A0home}>
      <div className='pageTitle'>首页管理</div>

      <div className='A0Tit'>
        <div>通知管理</div>
        <div>
          <Switch
            checked={Tinfo.display === 1}
            onChange={e => switchChange(Tinfo.id, e)}
            checkedChildren='开启'
            unCheckedChildren='关闭'
            defaultChecked
          />
        </div>
      </div>

      <MyTable
        list={Tinfo.id ? [Tinfo] : []}
        pagingInfo={false}
        columnsTemp={[['txt', '标题', 'name']]}
        lastBtn={tableLastBtn1}
      />
      <br />
      <br />
      <div className='A0Tit'>
        <div>BANNER管理</div>
        <div>
          <Button type='primary' onClick={() => setImgInfo({ id: -1 } as A0listType)}>
            新增
          </Button>
        </div>
      </div>

      <MyTable
        classKey='A0imgTable'
        yHeight={522}
        list={imgList}
        pagingInfo={false}
        columnsTemp={A0tableC}
        lastBtn={tableLastBtn2}
      />

      {editTinfo.id ? (
        <A0Tedit
          closeFu={() => setEditTinfo({} as A0Ttype)}
          succFu={getTinfoFu}
          info={editTinfo}
        />
      ) : null}

      {imgInfo.id ? (
        <A0imgAdd
          closeFu={() => setImgInfo({} as A0listType)}
          succFu={getImgListFu}
          info={imgInfo}
        />
      ) : null}
    </div>
  )
}

const MemoA0home = React.memo(A0home)

export default MemoA0home
