import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { useParams } from 'react-router-dom'
import { pageTitTxtObj } from '@/pages/D_storeManage/D4impStor/D4edit'
import X3auditInfo from '@/pages/X_stock/X3auditInfo'
import { Button, DatePicker, Input } from 'antd'
import dayjs from 'dayjs'
import { B3aForm1 } from '@/pages/B_enterTibet/B3_4page/B3edit/data'
import Z3upFiles from '@/components/Z3upFiles'
import ZRichTexts from '@/components/ZRichTexts'
import B3GaddNow from '@/pages/B_enterTibet/B3goodsTable/B3GaddNow'
import MyTable from '@/components/MyTable'
import history, { openGoodsInfoFu } from '@/utils/history'
import MyPopconfirm from '@/components/MyPopconfirm'
import { B3eTableC } from '@/utils/tableData'
import { MessageFu } from '@/utils/message'
import classNames from 'classnames'
import Y1cathet from '@/pages/Y_goodsDetails/Y1cathet'
import B3GaddNew from '@/pages/B_enterTibet/B3goodsTable/B3GaddNew'
import ImageLazy from '@/components/ImageLazy'
import X2lookText from '@/pages/X_stock/X2lookText'
import B3flowTable from '@/pages/B_enterTibet/B3flowTable'

function C6add() {
  const { key, id } = useParams<any>()

  // 滚到顶部
  const sollrDom = useRef<HTMLDivElement>(null)

  useEffect(() => {
    console.log('key:', key)

    if (sollrDom.current) sollrDom.current.scrollTop = 0
  }, [key])

  // 上传附件的ref
  const filesRef = useRef<any>(null)
  // const filesRes = filesRef.current.filesIdRes();

  // 富文本的ref
  const ZRichTextRef = useRef<any>(null)

  // 审批意见的ref
  const ZAuditRef = useRef<any>(null)

  // 设置富文本
  //  ZRichTextRef.current?.ritxtShowFu(JSON.parse(data.rtf))

  const timeChange = useCallback((e: any) => {
    console.log(123, e)
  }, [])

  // 新增的底部按钮点击
  const btnClickFu = useCallback((val: number) => {
    const rtf1 = ZRichTextRef.current?.fatherBtnOkFu() || { flag: true }
    console.log('申请信息富文本', JSON.stringify(rtf1.val || ''))

    const rtf2 = ZAuditRef.current?.resData()
    console.log('审批信息富文本', rtf2)

    // if (1 + 1 === 2) return

    if (val === 2) {
      // 存草稿 当前页保存 不跳转
      MessageFu.success('草稿保存成功')
    } else {
      // 跳到详情页
      history.push(`/edit_add/4/999`)
    }
  }, [])

  // 打开侧边栏
  const [cathet, setCathet] = useState(0)

  // 点击删除
  const delTableFu = useCallback(async (id: number) => {}, [])

  const startBtn = useMemo(() => {
    return [
      {
        title: '藏品编号',
        render: (item: any) => {
          return (
            <span
              onClick={() => setCathet(item.id)}
              className={classNames('D1GtNum', item.id === cathet ? 'D1GtNumAc' : '')}
            >
              {item.num}
            </span>
          )
        }
      }
    ]
  }, [cathet])

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: any) => {
          return (
            <>
              <Button size='small' type='text' onClick={() => openGoodsInfoFu(item.id)}>
                查看
              </Button>
              {['3', '4'].includes(key) ? null : (
                <MyPopconfirm txtK='删除' onConfirm={() => delTableFu(item.id)} />
              )}
            </>
          )
        }
      }
    ]
  }, [delTableFu, key])

  // 审批的sta
  const [auditSta, setAuDitSta] = useState('')

  // 点击所选藏品 / 继续编辑
  const [nowSta, setNowSta] = useState({ key: '', id: '', type: '' })

  // 查看模式下的按钮 待完善
  const lookBtn = useMemo(() => {
    return (
      <>
        <Button type='primary'>创建</Button>
        <Button type='primary'>提交</Button>
        <MyPopconfirm
          txtK='撤回'
          onConfirm={() => {}}
          Dom={
            <Button type='primary' danger>
              撤回
            </Button>
          }
        />

        <Button type='primary'>审批</Button>
        <Button type='primary'>编辑</Button>
        <Button type='primary'>重新提交</Button>
        <Button type='primary'>导出</Button>
        <MyPopconfirm
          txtK='删除'
          onConfirm={() => {}}
          Dom={
            <Button type='primary' danger>
              删除
            </Button>
          }
        />
        <Button onClick={() => history.push('/edit')}>返回</Button>
      </>
    )
  }, [])

  // 模拟 所选藏品 表格数据
  const [listTemp, setListTemp] = useState<any[]>([{ id: 99, thumb: '', num: '一段编号_可点击' }])

  // 编辑明细 表格
  const tableLastBtn2 = useMemo(() => {
    return [
      {
        title: '编辑项',
        render: (item: any) =>
          ['封面图', '附件信息', '简介'].includes(item.name) ? (
            <span className='C6tab2Tit'>{item.name}</span>
          ) : (
            item.name
          )
      },
      {
        title: '编辑前',
        render: (item: any) => {
          if (item.name === '封面图')
            return (
              <div className='tableImgAuto'>
                <ImageLazy
                  width={60}
                  height={60}
                  srcBig={item.qian}
                  src={item.qian}
                  offline={true}
                />
              </div>
            )
          else if (item.name === '附件信息')
            return item.qian.map((v: any, i: number) => (
              <a key={v.name} href={v.src} download target='_blank' rel='noreferrer'>
                {v.name}
                {i < item.qian.length - 1 ? '，' : ''}
              </a>
            ))
          else if (item.name === '简介')
            return (
              <Button size='small' type='text' onClick={() => setLook('xxx')}>
                查看
              </Button>
            )
          else return item.qian || '（空）'
        }
      },
      {
        title: '编辑后',
        render: (item: any) => {
          if (item.name === '封面图')
            return (
              <div className='tableImgAuto'>
                <ImageLazy width={60} height={60} srcBig={item.hou} src={item.hou} offline={true} />
              </div>
            )
          else if (item.name === '附件信息')
            return item.hou.map((v: any, i: number) => (
              <a key={v.name} href={v.src} download target='_blank' rel='noreferrer'>
                {v.name}
                {i < item.hou.length - 1 ? '，' : ''}
              </a>
            ))
          else if (item.name === '简介')
            return (
              <Button size='small' type='text' onClick={() => setLook('xxx')}>
                查看
              </Button>
            )
          else return item.hou || '（空）'
        }
      }
    ]
  }, [])

  //查看富文本信息
  const [look, setLook] = useState('')

  return (
    <div className={styles.C6add}>
      <div className='pageTitle'>藏品编辑-{Reflect.get(pageTitTxtObj, key)}</div>

      <div className='C6main' ref={sollrDom}>
        {['3'].includes(key) ? (
          <X3auditInfo
            dirCode='待完善'
            myUrl='待完善'
            auditSta={auditSta}
            auditStaFu={val => setAuDitSta(val)}
            ref={ZAuditRef}
          />
        ) : null}

        {/* 表单字段、附件等 */}
        <div className='C6Tit'>
          {/* 待完善 */}
          申请信息
          <Button type='dashed'>草稿</Button>
        </div>
        <div className='C6rowAll'>
          <div className='C6row'>
            <div className='C6rowll'>
              <span> * </span>申请名称：
            </div>
            <div className='C6rowrr'>
              <Input
                readOnly={['3', '4'].includes(key)}
                placeholder='请输入内容'
                maxLength={30}
                showCount
              />
            </div>
          </div>

          <div className='C6row'>
            <div className='C6rowll'>
              <span> * </span>业务日期：
            </div>
            <div className='C6rowrr'>
              <DatePicker
                disabled={['3', '4'].includes(key)}
                allowClear={false}
                value={dayjs()}
                onChange={timeChange}
              />
            </div>
          </div>

          {B3aForm1.map(v => (
            <div className='C6row' key={v.name}>
              <div className='C6rowll'>{v.name}：</div>
              <div className='C6rowrr'>
                这是一段文本
                {['3', '4'].includes(key) && v.name === '发起人'
                  ? ' - 查看和审批后面显示创建时间'
                  : ''}
              </div>
            </div>
          ))}

          <div className='C6row C6row2'>
            <div className='C6rowll'>附件：</div>
            <div className='C6rowrr'>
              <Z3upFiles
                max={10}
                isLook={['3', '4'].includes(key)}
                ref={filesRef}
                fileCheck={false}
                dirCode={'xxxxxxx'}
                myUrl='xxxxxxxxxxxx'
                lookData={[]}
                size={500}
              />
            </div>
          </div>

          <div className='C6row'>
            <div className='C6rowll'>原因事由：</div>
            <div className='C6rowrr'>
              <Input
                readOnly={['3', '4'].includes(key)}
                placeholder='请输入内容'
                maxLength={30}
                showCount
              />
            </div>
          </div>

          <div className='C6row C6rowFull'>
            <div className='C6rowll'>备注：</div>
            <div className='C6rowrr'>
              <ZRichTexts
                check={false}
                dirCode={'xxxxxxxx'}
                isLook={['3', '4'].includes(key)}
                ref={ZRichTextRef}
                myUrl='xxxxxxxxxx'
                isOne={true}
                upAudioBtnNone={true}
              />
            </div>
          </div>
        </div>

        {/* 所选藏品 */}
        <div className='C6googsBox'>
          <div className='C6Tit2'>
            <div className='C6Tit2ll'>所选藏品</div>
            <div className='C6Tit2rr'>
              {['3', '4'].includes(key) ? null : (
                <>
                  <Button type='primary' onClick={() => setNowSta({ key: '7', id, type: 'now' })}>
                    选择藏品
                  </Button>
                  <Button
                    disabled={listTemp.length === 0}
                    type='primary'
                    onClick={() => setNowSta({ key: '7', id, type: 'new' })}
                  >
                    继续编辑
                  </Button>
                </>
              )}
            </div>
          </div>

          {/* 表格 */}
          <MyTable
            list={listTemp}
            columnsTemp={B3eTableC}
            startBtn={startBtn}
            lastBtn={tableLastBtn}
            pagingInfo={false}
          />
        </div>

        {/* 编辑明细 */}
        <div className='C6googsBox'>
          <div className='C6Tit'>编辑明细</div>

          {/* 表格 */}
          <MyTable
            list={[
              { id: 1, name: '名称', qian: '11', hou: '22' },
              {
                id: 2,
                name: '封面图',
                qian: 'https://houseoss.4dkankan.com/project/DEMO/staticResource/touxiang.jpg',
                hou: 'https://houseoss.4dkankan.com/project/DEMO/staticResource/touxiang.jpg'
              },
              {
                id: 3,
                name: '附件信息',
                qian: [
                  {
                    name: '666.jpg',
                    src: 'https://houseoss.4dkankan.com/project/DEMO/staticResource/touxiang.jpg'
                  }
                ],
                hou: [
                  {
                    name: '666.jpg',
                    src: 'https://houseoss.4dkankan.com/project/DEMO/staticResource/touxiang.jpg'
                  },
                  {
                    name: '777.mp4',
                    src: 'https://houseoss.4dkankan.com/project/DEMO/staticResource/loop.mp4'
                  }
                ]
              },
              { id: 4, name: '简介', qian: '11', hou: '22' }
            ]}
            columnsTemp={[]}
            lastBtn={tableLastBtn2}
            pagingInfo={false}
          />
        </div>

        {/* 申请流程 */}
        {['3', '4'].includes(key) ? (
          <B3flowTable
            tableArr={
              [
                //  待完善
              ]
            }
          />
        ) : null}
      </div>

      {/* 底部按钮 */}
      <div className='C6btn'>
        {key === '4' ? (
          lookBtn
        ) : (
          <>
            <Button type='primary' onClick={() => btnClickFu(1)}>
              {key === '1' ? '创建' : '保存'}
            </Button>

            {key === '1' ? (
              <Button type='primary' onClick={() => btnClickFu(2)}>
                存草稿
              </Button>
            ) : null}

            <MyPopconfirm txtK='取消' onConfirm={() => history.push('/edit')} />
          </>
        )}
      </div>

      {/* 打开侧边栏 */}
      <Y1cathet sId={cathet} closeFu={() => setCathet(0)} />

      {/* 所选藏品弹窗 / 继续编辑 */}

      {nowSta.id ? (
        nowSta.type === 'now' ? (
          <B3GaddNow
            isOne={true}
            nowSta={nowSta}
            closeFu={() => setNowSta({ key: '', id: '', type: '' })}
            dataResFu={data => {
              setListTemp([{ id: 99, thumb: '', num: '一段编号_可点击' }])
              setTimeout(() => {
                setNowSta({ key: '7', id: '77', type: 'new' })
              }, 20)
            }}
            // 待完善
            oldCheckArr={[]}
          />
        ) : (
          <B3GaddNew
            nowSta={nowSta}
            closeFu={() => setNowSta({ key: '', id: '', type: '' })}
            isEdit={true}
            succFu={obj => {}}
          />
        )
      ) : null}

      {/* 查看富文本 */}
      {look ? <X2lookText closeFu={() => setLook('')} text='待完善' /> : null}
    </div>
  )
}

const MemoC6add = React.memo(C6add)

export default MemoC6add
