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 { Button, DatePicker } from 'antd'
import { MessageFu } from '@/utils/message'
import MyTable from '@/components/MyTable'
import { B1TableC2, statusObj } from '@/utils/tableData'
import MyPopconfirm from '@/components/MyPopconfirm'
import ZflowTable from '../../../../components/ZflowTable'
import history, { btnFlagFu2 } from '@/utils/history'
import {
  B1_APIcreate,
  B1_APIdel,
  B1_APIgetInfo,
  B1_APIrevocation,
  B1_APIsaveApply,
  B1_APIsaveAudit,
  B1_APIsaveCreate,
  B1_APIsaveDraft
} from '@/store/action/B1collect'
import dayjs from 'dayjs'
import { EXbtnFu } from '@/utils/EXBtn'
import X3auditInfo from '@/pages/X_stock/X3auditInfo'
import B1MoAdd from './B1MoAdd'
import { B1Xtype } from '../data'
import ZupFileTable from '@/components/ZupFileTable'
import { FourTableType } from '../type'

function B1edit() {
  const { key, id } = useParams<any>()
  // key:1 新增 2编辑 3审批 4查看

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

  // -------新增藏品-------------
  const [openId, setOpenId] = useState(0)

  const [clueArr, setClueArr] = useState<B1Xtype[]>([])

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '附件数量',
        render: (item: any) => (item.fileIds ? item.fileIds.split(',').length : 0)
      },
      {
        title: '操作',
        render: (item: any) => {
          return (
            <>
              <Button size='small' type='text' onClick={() => setOpenId(item.id)}>
                {['3', '4'].includes(key) ? '查看' : '编辑'}
              </Button>
              {['3', '4'].includes(key) ? null : (
                <MyPopconfirm
                  txtK='删除'
                  onConfirm={() => setClueArr(clueArr.filter(v => v.id !== item.id))}
                />
              )}
            </>
          )
        }
      }
    ]
  }, [clueArr, key])
  // -------新增藏品-------------

  // 顶部数据
  const [topInfo, setTopInfo] = useState({} as FourTableType)
  // 创建订单
  const creatFu = useCallback(async () => {
    const res = await B1_APIcreate()
    if (res.code === 0) {
      setTopInfo(res.data)
    }
  }, [])

  // 获取详情
  const getInfoFu = useCallback(async () => {
    const res = await B1_APIgetInfo(id)
    if (res.code === 0) {
      setTopInfo(res.data)
      setClueArr(res.data.collects || [])
    }
  }, [id])

  useEffect(() => {
    if (key === '1') creatFu()
    else getInfoFu()

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

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

  const timeChange = useCallback(
    (e: any) => {
      setTopInfo({ ...topInfo, date: dayjs(e).format('YYYY-MM-DD') })
    },
    [topInfo]
  )
  // 审批的sta
  const [auditSta, setAuDitSta] = useState('')

  // 新增的底部按钮点击
  const btnClickFu = useCallback(
    async (val: '草稿' | '创建' | '保存' | '审批') => {
      if (val !== '草稿') {
        if (clueArr.length === 0) return MessageFu.warning('请添加藏品')
      }

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

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

        if (res.code === 0) {
          MessageFu.success('审批成功')
          // 跳详情页
          history.push(`/collect_edit/4/${topInfo.id}`)
        }
      } else {
        const obj = {
          ...topInfo,
          collectIds: clueArr.map(v => v.id).join(',')
        }
        // console.log(123, obj)

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

        if (val === '草稿') {
          // 存草稿 当前页保存 不跳转
          const res = await B1_APIsaveDraft(obj)
          if (res.code === 0) {
            MessageFu.success('草稿保存成功')
          }
        } else {
          const res = val === '创建' ? await B1_APIsaveCreate(obj) : await B1_APIsaveApply(obj)
          if (res.code === 0) {
            MessageFu.success(`${val}成功`)
            // 跳到详情页
            history.push(`/collect_edit/4/${topInfo.id}`)
          }
        }
      }
    },
    [auditSta, clueArr, topInfo]
  )

  // 查看的按钮创建-提交-撤回
  const lookBtnFu = useCallback(
    async (val: '创建' | '提交' | '撤回') => {
      if (val !== '撤回') {
        if (clueArr.length === 0) return MessageFu.warning('请添加藏品')
      }

      const obj = {
        ...topInfo,
        collectIds: clueArr.map(v => v.id).join(',')
      }

      const res =
        val === '创建'
          ? await B1_APIsaveCreate(obj)
          : val === '提交'
          ? await B1_APIsaveApply(obj)
          : await B1_APIrevocation(id)

      if (res.code === 0) {
        if (sollrDom.current) sollrDom.current.scrollTop = 0
        MessageFu.success(val + '成功')
        getInfoFu()
      }
    },
    [clueArr, getInfoFu, id, topInfo]
  )
  // 查看模式点击删除
  const delFu = useCallback(async () => {
    const res = await B1_APIdel(id)
    if (res.code === 0) {
      MessageFu.success('删除成功')
      history.push('/collect')
    }
  }, [id])

  // 查看模式点击审批 编辑
  const lookJumpFu = useCallback(
    (val: '审批' | '编辑') => {
      history.push(`/collect_edit/${val === '审批' ? 3 : 2}/${id}`)
      MessageFu.success(`已跳转至${val}页面`)
    },
    [id]
  )

  // 查看模式下的按钮
  const lookBtn = useMemo(() => {
    return (
      <>
        {btnFlagFu2(topInfo)['创建'] ? (
          <Button type='primary' onClick={() => lookBtnFu('创建')}>
            创建
          </Button>
        ) : null}
        {btnFlagFu2(topInfo)['提交'] ? (
          <Button type='primary' onClick={() => lookBtnFu('提交')}>
            提交
          </Button>
        ) : null}

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

        {btnFlagFu2(topInfo)['审批'] ? (
          <Button type='primary' onClick={() => lookJumpFu('审批')}>
            审批
          </Button>
        ) : null}
        {btnFlagFu2(topInfo)['编辑'] ? (
          <Button type='primary' onClick={() => lookJumpFu('编辑')}>
            编辑
          </Button>
        ) : null}

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

        {EXbtnFu(topInfo)}

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

        <Button onClick={() => history.push('/collect')}>返回</Button>
      </>
    )
  }, [delFu, lookBtnFu, lookJumpFu, topInfo])

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

  return (
    <div className={styles.B1edit}>
      <div className='pageTitle'>藏品征集-{Reflect.get(pageTitTxtObj, key)}</div>

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

        {/* 表单字段、附件等 */}
        <div className='B1Tit'>
          申请信息
          {key === '1' ? null : (
            <Button type='dashed'>{Reflect.get(statusObj, topInfo.status)}</Button>
          )}
        </div>

        <div className='B1rowAll'>
          <div className='B1row'>
            <div className='B1rowll'>业务单号：</div>
            <div className='B1rowrr'>{topInfo.num}</div>
          </div>

          <div className='B1row'>
            <div className='B1rowll'>业务名称：</div>
            <div className='B1rowrr'>{topInfo.name}</div>
          </div>

          <div className='B1row'>
            <div className='B1rowll'>发起人：</div>
            <div className='B1rowrr'>
              {topInfo.creatorName}
              {['3', '4'].includes(key) ? ' - ' + topInfo.createTime || '' : ''}
            </div>
          </div>

          <div className='B1row'>
            <div className='B1rowll'>发起部门：</div>
            <div className='B1rowrr'>{topInfo.deptName}</div>
          </div>

          <div className='B1row'>
            <div className='B1rowll'>
              <span> * </span>征集日期：
            </div>
            <div className='B1rowrr'>
              <DatePicker
                disabled={['3', '4'].includes(key)}
                allowClear={false}
                value={dayjs(topInfo.date)}
                onChange={timeChange}
              />
            </div>
          </div>
        </div>

        {/* 藏品清单 */}
        <div className='B1goodsBox'>
          <div className='B1Tit2'>
            <div className='B1Tit2ll'>藏品清单</div>
            <div className='B1Tit2rr'>
              {['3', '4'].includes(key) ? null : (
                <>
                  <Button type='primary' onClick={() => MessageFu.warning('待完善')}>
                    批量导入
                  </Button>
                  <Button type='primary' onClick={() => setOpenId(-1)}>
                    新增
                  </Button>
                </>
              )}
            </div>
          </div>

          {/* 表格 */}
          <MyTable
            list={clueArr}
            columnsTemp={B1TableC2}
            lastBtn={tableLastBtn}
            pagingInfo={false}
          />
        </div>

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

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

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

        {key === '4' ? (
          lookBtn
        ) : (
          <>
            {key === '3' ? (
              <Button type='primary' onClick={() => btnClickFu('审批')}>
                审批
              </Button>
            ) : (
              <Button type='primary' onClick={() => btnClickFu(key === '1' ? '创建' : '保存')}>
                {key === '1' ? '创建' : '保存'}
              </Button>
            )}

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

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

      {/* 新增弹窗 */}
      {openId ? (
        <B1MoAdd
          look={['3', '4'].includes(key)}
          sId={openId}
          closeFu={() => setOpenId(0)}
          succFu={(obj, txt) => {
            if (txt === '新增') setClueArr([obj, ...clueArr])
            else {
              const index = clueArr.findIndex(v => v.id === obj.id)
              const newArr = [...clueArr]
              newArr[index] = obj
              setClueArr(newArr)
            }
          }}
        />
      ) : null}
    </div>
  )
}

const MemoB1edit = React.memo(B1edit)

export default MemoB1edit
