import React, { useCallback, useEffect, useRef, useState } from 'react'
import styles from './index.module.scss'
import { useParams } from 'react-router-dom'
import { FourTableType } from '@/pages/B_enterTibet/B1collect/type'
import {
  FourAPI_audit,
  FourAPI_del,
  FourAPI_getInfo,
  FourAPI_revocation,
  FourAPI_saveApply
} from '@/store/action/FourAll'
import { pageTitTxtObj } from '@/pages/D_storeManage/D4impStor/D4edit'
import X3auditInfo from '@/pages/X_stock/X3auditInfo'
import { Button } from 'antd'
import { statusObj } from '@/utils/tableData'
import history, { openGoodsInfoFu } from '@/utils/history'
import Y11com from '@/pages/Y_goodsDetails/Y1cathet/Y11com'
import Y33com from '@/pages/Y_goodsDetails/Y1cathet/Y33com'
import { C1GoodType } from '@/pages/A3_ledger/C1ledger/type'
import { API_goodsInfo } from '@/store/action/C1ledger'
import ZupFileTable from '@/components/ZupFileTable'
import ZflowTable from '@/components/ZflowTable'
import MyPopconfirm from '@/components/MyPopconfirm'
import { MessageFu } from '@/utils/message'
import { EXbtnFu } from '@/utils/EXBtn'
import { C22infoBtnFu } from '../../C22goodEdit/data'
function C1look() {
  const { key, id } = useParams<any>()
  // key: 3审批 4查看
  // 滚到顶部
  const sollrDom = useRef<HTMLDivElement>(null)

  // 顶部数据
  const [topInfo, setTopInfo] = useState({} as FourTableType)

  const [info, setInfo] = useState({} as C1GoodType)

  // 获取详情
  const getInfoFu = useCallback(async () => {
    const res = await FourAPI_getInfo('3', id)
    if (res.code === 0) {
      const data = res.data
      setTopInfo(data)
      if (data.goodsIds) {
        const res2 = await API_goodsInfo(data.goodsIds)
        if (res2.code === 0) {
          setInfo(res2.data)
        }
      }
    }
  }, [id])

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

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

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

  // 申请记录
  const [auditsShow, setAuditsShow] = useState(false)

  // 藏品详情的信息
  const [goodType, setGoodType] = useState('藏品信息')

  // 点击编辑
  const editBtnFu = useCallback(() => {
    MessageFu.success('已跳转至编辑页面')
    history.push(`/register?id=${id}`)
  }, [id])

  // 点击提交
  const btnOkFu = useCallback(async () => {
    const res = await FourAPI_saveApply('3', topInfo)
    if (res.code === 0) {
      MessageFu.success('提交成功')
      history.push('/goodEdit')
    }
  }, [topInfo])

  // 点击删除
  const delFu = useCallback(async () => {
    const res = await FourAPI_del('3', id)
    if (res.code === 0) {
      MessageFu.success('删除成功')
      history.push('/goodEdit')
    }
  }, [id])

  // 点击撤回
  const cheHuiFu = useCallback(async () => {
    // 撤回-该状态 刷新当前页
    const res = await FourAPI_revocation('3', id)
    if (res.code === 0) {
      MessageFu.success('撤回成功')
      if (sollrDom.current) sollrDom.current.scrollTop = 0
      getInfoFu()
    }
  }, [getInfoFu, id])

  // 点击审批
  const auditFu = useCallback(async () => {
    // console.log('审批信息富文本', rtf2)
    if (!auditSta) {
      if (sollrDom.current) sollrDom.current.scrollTop = 0
      return MessageFu.warning('请选择审批结果')
    }
    const rtf2 = ZAuditRef.current?.resData()

    const res = await FourAPI_audit('3', {
      orderId: topInfo.id,
      rtfOpinion: rtf2,
      status: auditSta === '同意' ? 1 : 2
    })

    if (res.code === 0) {
      MessageFu.success('提交成功')
      history.push(`/goodEdit`)
    }
  }, [auditSta, topInfo.id])

  return (
    <div className={styles.C1look}>
      <div className='pageTitle'>藏品登记-{Reflect.get(pageTitTxtObj, key)}</div>

      {/* 主体 */}
      <div className='C1lBox' ref={sollrDom}>
        <div className='C1Tit'>
          申请信息
          {key === '1' ? null : (
            <Button type='dashed'>{Reflect.get(statusObj, topInfo.status)}</Button>
          )}
        </div>

        {topInfo.id ? (
          <div className='C1rowAll'>
            <div className='C1row'>
              <div className='C1rowll'>业务单号：</div>
              <div className='C1rowrr'>{topInfo.num}</div>
            </div>

            <div className='C1row'>
              <div className='C1rowll'>业务名称：</div>
              <div className='C1rowrr'>{topInfo.name}</div>
            </div>

            <div className='C1row'>
              <div className='C1rowll'>发起人：</div>
              <div className='C1rowrr'>{topInfo.creatorName + ' - ' + topInfo.createTime}</div>
            </div>

            <div className='C1row'>
              <div className='C1rowll'>发起部门：</div>
              <div className='C1rowrr'>{topInfo.deptName}</div>
            </div>
          </div>
        ) : null}

        <div className='C1main'>
          {['3'].includes(key) ? (
            <X3auditInfo
              titHide={true}
              dirCode='C1register'
              myUrl='cms/goodsFile/upload'
              auditSta={auditSta}
              auditStaFu={val => setAuDitSta(val)}
              ref={ZAuditRef}
            />
          ) : null}
        </div>

        <div className='C1Tit C1Tit2'>
          藏品详情
          <div className='C1TitRR'>
            更多操作请在详情页中进行
            <Button type='primary' onClick={() => openGoodsInfoFu(Number(topInfo.goodsIds))}>
              查看详情
            </Button>
          </div>
          <div className='C1Good'>
            {['藏品信息', '藏品附件'].map(v => (
              <Button
                onClick={() => setGoodType(v)}
                key={v}
                type={v === goodType ? 'primary' : 'default'}
              >
                {v}
              </Button>
            ))}
          </div>
        </div>

        {info.id ? (
          <div className='Y1info'>
            {goodType === '藏品信息' ? <Y11com info={info} /> : null}
            {goodType === '藏品附件' ? <Y33com sId={info.id} /> : null}
          </div>
        ) : null}

        {/* 附件归档 */}
        {topInfo.status === 4 ? (
          <ZupFileTable
            listTemp={topInfo.filing || []}
            dirCode='C1register'
            myUrl='cms/register/upload'
            fromData={{ moduleId: topInfo.id }}
          />
        ) : null}
      </div>

      {/* 底部按钮 */}
      <div className='C1lBtn'>
        {['3', '4'].includes(key) && topInfo.audits && topInfo.audits.length ? (
          <Button type='primary' onClick={() => setAuditsShow(true)}>
            申请记录
          </Button>
        ) : null}

        {/* 能进审批页，点审批按钮的必定有权限 */}
        {key === '3' ? (
          C22infoBtnFu(topInfo)['审批'] ? (
            <Button type='primary' onClick={auditFu}>
              提交
            </Button>
          ) : null
        ) : (
          <>
            {C22infoBtnFu(topInfo)['编辑'] ? (
              <Button type='primary' onClick={editBtnFu}>
                编辑
              </Button>
            ) : null}
            {C22infoBtnFu(topInfo)['提交'] ? (
              <Button type='primary' onClick={btnOkFu}>
                提交
              </Button>
            ) : null}

            {C22infoBtnFu(topInfo)['重新提交'] ? (
              <Button type='primary' onClick={btnOkFu}>
                重新提交
              </Button>
            ) : null}

            {EXbtnFu(topInfo)}

            {C22infoBtnFu(topInfo)['撤回'] ? (
              <MyPopconfirm
                txtK='撤回'
                onConfirm={() => cheHuiFu()}
                Dom={
                  <Button type='primary' danger>
                    撤回
                  </Button>
                }
              />
            ) : null}

            {C22infoBtnFu(topInfo)['删除'] ? (
              <MyPopconfirm
                txtK='删除'
                onConfirm={() => delFu()}
                Dom={
                  <Button type='primary' danger>
                    删除
                  </Button>
                }
              />
            ) : null}
          </>
        )}
      </div>

      {/* 申请流程 */}
      {auditsShow ? (
        <ZflowTable tableArr={topInfo.audits || []} closeFu={() => setAuditsShow(false)} />
      ) : null}
    </div>
  )
}

const MemoC1look = React.memo(C1look)

export default MemoC1look
