import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { useParams } from 'react-router-dom'
import { E1_APIgetGoodsList } from '@/store/action/E1accident'
import { FourTableType } from '@/pages/B_enterTibet/B1collect/type'
import {
  E3_APIcreate,
  E3_APIdel,
  E3_APIgetInfo,
  E3_APIrevocation,
  E3_APIsaveApply,
  E3_APIsaveAudit,
  E3_APIsaveCreate,
  E3_APIsaveDraft
} from '@/store/action/E3actuality'
import { API_goodsInfo } from '@/store/action/C1ledger'
import { pageTitTxtObj } from '@/pages/D_storeManage/D4impStor/D4edit'
import dayjs from 'dayjs'
import { MessageFu } from '@/utils/message'
import history, { btnFlagFu2, infoPageBackFu } from '@/utils/history'
import { Button, DatePicker, Input, Select } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import { EXbtnFu } from '@/utils/EXBtn'
import X3auditInfo from '@/pages/X_stock/X3auditInfo'
import { statusObj } from '@/utils/tableData'
import { selectObj } from '@/utils/select'
import TextArea from 'antd/es/input/TextArea'
import Z3upFiles from '@/components/Z3upFiles'
import ZupFileTable from '@/components/ZupFileTable'
import ZflowTable from '@/components/ZflowTable'
import ZRichTexts from '@/components/ZRichTexts'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '@/store'
import { D7_APIList } from '@/store/action/D7check'
import { EXPORT_WORD_ENUM } from '@/utils/exportTemplates'
function E3edit() {
  // 相关盘点单下拉数据
  // 从仓库拿数据
  const dispatch = useDispatch()

  useEffect(() => {
    dispatch(D7_APIList({ pageNum: 1, pageSize: 99999 }))
  }, [dispatch])

  const relatedOrderNumArr = useSelector((state: RootState) => state.D7check.tableInfo.list)

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

  // 事故藏品选择编号类型
  const [goodsArr, setGoodsArr] = useState<{ value: string; label: string; num: string }[]>([])

  const numNameChangeFu = useCallback(async (val: string) => {
    const res = await E1_APIgetGoodsList(val)

    if (res.code === 0) {
      const arr = res.data || []
      setGoodsArr(
        arr.map((v: any) => ({
          num: v.num,
          label: v.name,
          value: v.id + ''
        }))
      )
    }
  }, [])

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

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

  // 创建订单
  const creatFu = useCallback(async () => {
    const res = await E3_APIcreate()
    if (res.code === 0) {
      const obj = res.data

      // 从藏品详情点击按钮进来
      const urlAll = window.location.href
      if (urlAll.includes('?id=')) {
        const urlId = urlAll.split('?id=')[1]
        const res2 = await API_goodsInfo(Number(urlId), 12)
        if (res2.code === 0) {
          obj.numName = res2.data.numName
          numNameChangeFu(res2.data.numName)

          obj.goodsIds = urlId
          setTopInfo(obj)
        }
      } else setTopInfo(obj)
    }
  }, [numNameChangeFu])

  // 获取详情
  const getInfoFu = useCallback(
    async (id2?: number) => {
      const res = await E3_APIgetInfo(id2 || id)
      if (res.code === 0) {
        const data = res.data

        setTopInfo(data)

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

        if (data.numName) numNameChangeFu(data.numName)
      }
    },
    [id, numNameChangeFu]
  )

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

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

  const pageTitTxt = useMemo(() => {
    return Reflect.get(pageTitTxtObj, key)
  }, [key])

  const timeChange = useCallback(
    (e: any) => {
      setTopInfo({ ...topInfo, date: dayjs(e).format('YYYY-MM-DD') })
    },
    [topInfo]
  )

  // 上传附件的ref
  const filesRef = useRef<any>(null)

  // 备注的ref
  const ZRichTextRef = useRef<any>(null)

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

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

  // 字段的校验
  const checkFu = useCallback(() => {
    if (!topInfo.date) {
      MessageFu.warning('请选择登记日期')
      return true
    }

    if (!topInfo.numName || !topInfo.goodsIds) {
      MessageFu.warning('请选择登记藏品')
      return true
    }

    if (!topInfo.reason) {
      MessageFu.warning('请输入现状描述')
      return true
    }

    if (!topInfo.sonUser) {
      MessageFu.warning('请输入经手人')
      return true
    }
  }, [topInfo])

  // 新增的底部按钮点击
  const btnClickFu = useCallback(
    async (val: '草稿' | '创建' | '保存' | '审批') => {
      if (checkFu()) {
        if (sollrDom.current) sollrDom.current.scrollTop = 0
        return
      }

      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 E3_APIsaveAudit({
          orderId: topInfo.id,
          rtfOpinion: rtf2,
          status: auditSta === '同意' ? 1 : 2
        })

        if (res.code === 0) {
          MessageFu.success('审批成功')
          // 跳详情页
          history.push(`/actuality_edit/4/${topInfo.id}`)
        }
      } else {
        // 富文本
        const rtf1 = ZRichTextRef.current?.fatherBtnOkFu() || { flag: true }

        // 上传附件
        const filesRes = filesRef.current.filesIdRes()

        const obj = {
          ...topInfo,
          snaps: [
            {
              goodsId: topInfo.goodsIds,
              id: topInfo.id,
              snap: JSON.stringify({
                reason: topInfo.reason,
                date: topInfo.date,
                sonUser: topInfo.sonUser
              })
            }
          ],
          rtf: JSON.stringify(rtf1.val || ''),
          fileIds: filesRes.join(',')
        }
        // console.log(123, obj)

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

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

  // 查看的按钮创建-提交-撤回
  const lookBtnFu = useCallback(
    async (val: '创建' | '提交' | '撤回') => {
      // 富文本
      const rtf1 = ZRichTextRef.current?.fatherBtnOkFu() || { flag: true }

      // 上传附件
      const filesRes = filesRef.current.filesIdRes()
      const obj = {
        ...topInfo,
        rtf: JSON.stringify(rtf1.val || ''),
        fileIds: filesRes.join(',')
      }

      const res =
        val === '创建'
          ? await E3_APIsaveCreate(obj)
          : val === '提交'
          ? await E3_APIsaveApply(obj)
          : await E3_APIrevocation(id)

      if (res.code === 0) {
        if (sollrDom.current) sollrDom.current.scrollTop = 0
        MessageFu.success(val + '成功')
        getInfoFu()
      }
    },
    [getInfoFu, id, topInfo]
  )

  // 查看模式点击删除
  const delFu = useCallback(async () => {
    const res = await E3_APIdel(id)
    if (res.code === 0) {
      MessageFu.success('删除成功')
      history.push('/actuality')
    }
  }, [id])

  // 查看模式点击审批 编辑
  const lookJumpFu = useCallback(
    (val: '审批' | '编辑') => {
      history.push(`/actuality_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, [EXPORT_WORD_ENUM.COLLECTION_CURRENT_STATUS])}

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

        <Button onClick={() => infoPageBackFu('/actuality')}>返回</Button>
      </>
    )
  }, [delFu, lookBtnFu, lookJumpFu, topInfo])

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

  return (
    <div className={styles.E3edit}>
      <div className='pageTitle'>现状登记-{pageTitTxt}</div>

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

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

        <div className='E3rowAll'>
          <div className='E3row'>
            <div className='E3rowll'>申请类型：</div>
            <div className='E3rowrr'>{topInfo.name}</div>
          </div>

          <div className='E3row'>
            <div className='E3rowll'>
              <span> * </span>登记日期：
            </div>
            <div className='E3rowrr'>
              <DatePicker
                disabled={['3', '4'].includes(key)}
                allowClear={false}
                value={topInfo.date ? dayjs(topInfo.date) : null}
                onChange={timeChange}
              />
            </div>
          </div>

          <div className='E3row E3rowFull2'>
            <div className='E3rowll'>
              <span> * </span>登记藏品：
            </div>
            <div className='E3rowrr'>
              <Select
                disabled={['3', '4'].includes(key)}
                allowClear={false}
                placeholder='请选择编号类型'
                style={{ width: 150 }}
                value={topInfo.numName ? topInfo.numName : null}
                onChange={e => {
                  setTopInfo({ ...topInfo, numName: e, goodsIds: '' })
                  numNameChangeFu(e)
                }}
                options={selectObj['藏品编号类型']}
              />
              <Select
                disabled={['3', '4'].includes(key) || !topInfo.numName}
                placeholder={!topInfo.numName ? '请先选择编号类型' : '请输入藏品编号或藏品名称'}
                showSearch
                filterOption={(input, option) => {
                  const txt = option!.label + option!.num

                  return txt.toLowerCase().includes(input.toLowerCase())
                }}
                options={goodsArr}
                // fieldNames={{ label: 'num', value: 'num' }}
                allowClear={false}
                value={topInfo.goodsIds || null}
                onChange={e => setTopInfo({ ...topInfo, goodsIds: e ? e : '' })}
              />
            </div>
          </div>

          <div className='E3row E3rowFull2'>
            <div className='E3rowll'>
              <span> * </span>现状描述：
            </div>
            <div className='E3rowrr'>
              <TextArea
                value={topInfo.reason}
                onChange={e => setTopInfo({ ...topInfo, reason: e.target.value.trim() })}
                readOnly={['3', '4'].includes(key)}
                placeholder='请输入内容'
                maxLength={500}
                showCount
              />
            </div>
          </div>

          <div className='E3row'>
            <div className='E3rowll'>
              <span> * </span>经手人：
            </div>
            <div className='E3rowrr'>
              <Input
                value={topInfo.sonUser}
                onChange={e => setTopInfo({ ...topInfo, sonUser: e.target.value.trim() })}
                readOnly={['3', '4'].includes(key)}
                placeholder='请输入内容'
                maxLength={30}
                showCount
              />
            </div>
          </div>

          <div className='E3row'>
            <div className='E3rowll'>相关盘点单：</div>
            <div className='E3rowrr'>
              <Select
                disabled={['3', '4'].includes(key)}
                placeholder={['3', '4'].includes(key) ? '空' : '请搜索盘点单编号'}
                showSearch
                filterOption={(input, option) => {
                  const txt = option!.label

                  return txt.toLowerCase().includes(input.toLowerCase())
                }}
                options={relatedOrderNumArr.map(v => ({ value: v.num, label: v.num }))}
                // fieldNames={{ label: 'num', value: 'num' }}
                allowClear={false}
                value={topInfo.relatedOrderNum || null}
                onChange={e => setTopInfo({ ...topInfo, relatedOrderNum: e ? e : '' })}
              />
            </div>
          </div>

          <div className='E3row E3row2'>
            <div className='E3rowll'>附件：</div>
            <div className='E3rowrr'>
              <Z3upFiles
                max={10000}
                isLook={['3', '4'].includes(key)}
                ref={filesRef}
                fileCheck={false}
                dirCode='E3actuality'
                myUrl='cms/orderPreserveCurrent/upload'
                lookData={topInfo.files || []}
                fromData={{ moduleId: topInfo.id }}
              />
            </div>
          </div>

          <div className='E3row E3rowFull'>
            <div className='E3rowll'>备注：</div>
            <div className='E3rowrr'>
              <ZRichTexts
                check={false}
                dirCode='E3actuality'
                myUrl='cms/goodsFile/upload'
                isLook={['3', '4'].includes(key)}
                ref={ZRichTextRef}
                isOne={true}
                upAudioBtnNone={true}
              />
            </div>
          </div>
        </div>

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

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

      {/* 底部按钮 */}
      <div className='E3btn'>
        {['3', '4'].includes(key) &&
        topInfo.audits &&
        topInfo.audits.length &&
        [2, 3, 4].includes(topInfo.status) ? (
          <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('/accident')} />
          </>
        )}
      </div>
    </div>
  )
}

const MemoE3edit = React.memo(E3edit)

export default MemoE3edit
