import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { pageTitTxtObj } from '@/pages/D_storeManage/D4impStor/D4edit'
import { useParams } from 'react-router-dom'
import { Button, DatePicker, Input, Select } from 'antd'
import { statusObj } from '@/utils/tableData'
import { FourTableType } from '@/pages/B_enterTibet/B1collect/type'
import dayjs from 'dayjs'
import { selectObj } from '@/utils/select'
import Z3upFiles from '@/components/Z3upFiles'
import ZRichTexts from '@/components/ZRichTexts'
import MyPopconfirm from '@/components/MyPopconfirm'
import history, { btnFlagFu2 } from '@/utils/history'
import { MessageFu } from '@/utils/message'
import X3auditInfo from '@/pages/X_stock/X3auditInfo'
import {
  E1_APIcreate,
  E1_APIdel,
  E1_APIgetGoodsList,
  E1_APIgetInfo,
  E1_APIrevocation,
  E1_APIsaveApply,
  E1_APIsaveAudit,
  E1_APIsaveCreate,
  E1_APIsaveDraft
} from '@/store/action/E1accident'
import { EXbtnFu } from '@/utils/EXBtn'
import ZflowTable from '@/components/ZflowTable'
import ZupFileTable from '@/components/ZupFileTable'
function E1edit() {
  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 E1_APIcreate()
    if (res.code === 0) {
      setTopInfo(res.data)
    }
  }, [])

  // 获取详情
  const getInfoFu = useCallback(async () => {
    const res = await E1_APIgetInfo(id)
    if (res.code === 0) {
      const data = res.data

      setTopInfo(data)

      // 设置富文本
      ZRichTextRefQian.current?.ritxtShowFu(JSON.parse(data.authInfoRtf || '{}'))
      ZRichTextRefHou.current?.ritxtShowFu(JSON.parse(data.authResultRtf || '{}'))
      ZRichTextRefYuan.current?.ritxtShowFu(JSON.parse(data.reason || '{}'))
      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)
  // const filesRes = filesRef.current.filesIdRes();

  // 事故前的ref
  const ZRichTextRefQian = useRef<any>(null)

  // 事故后的ref
  const ZRichTextRefHou = useRef<any>(null)

  // 事故原因及经过
  const ZRichTextRefYuan = 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.sonTypeName) {
      MessageFu.warning('请输入事故责任')
      return true
    }
    if (!topInfo.numName || !topInfo.goodsIds) {
      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 E1_APIsaveAudit({
          orderId: topInfo.id,
          rtfOpinion: rtf2,
          status: auditSta === '同意' ? 1 : 2
        })

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

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

        const obj = {
          ...topInfo,
          authInfoRtf: JSON.stringify(rtfQian.val || ''),
          authResultRtf: JSON.stringify(rtfHou.val || ''),
          reason: JSON.stringify(rtfYuan.val || ''),
          rtf: JSON.stringify(rtf1.val || ''),
          fileIds: filesRes.join(',')
        }
        // console.log(123, obj)

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

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

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

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

      const res =
        val === '创建'
          ? await E1_APIsaveCreate(obj)
          : val === '提交'
          ? await E1_APIsaveApply(obj)
          : await E1_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 E1_APIdel(id)
    if (res.code === 0) {
      MessageFu.success('删除成功')
      history.push('/accident')
    }
  }, [id])

  // 查看模式点击审批 编辑
  const lookJumpFu = useCallback(
    (val: '审批' | '编辑') => {
      history.push(`/accident_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('/accident')}>返回</Button>
      </>
    )
  }, [delFu, lookBtnFu, lookJumpFu, topInfo])

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

  return (
    <div className={styles.E1edit}>
      <div className='pageTitle'>事故登记-{pageTitTxt}</div>

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

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

        <div className='E1rowAll'>
          <div className='E1row'>
            <div className='E1rowll'>申请类型：</div>
            <div className='E1rowrr'>{topInfo.name}</div>
          </div>

          <div className='E1row'>
            <div className='E1rowll'>
              <span> * </span>事故时间：
            </div>
            <div className='E1rowrr'>
              <DatePicker
                disabled={['3', '4'].includes(key)}
                allowClear={false}
                value={topInfo.date ? dayjs(topInfo.date) : null}
                onChange={timeChange}
              />
            </div>
          </div>

          <div className='E1row'>
            <div className='E1rowll'>
              <span> * </span>事故责任：
            </div>
            <div className='E1rowrr'>
              <Input
                value={topInfo.sonTypeName}
                onChange={e => setTopInfo({ ...topInfo, sonTypeName: e.target.value.trim() })}
                readOnly={['3', '4'].includes(key)}
                placeholder='请输入内容'
                maxLength={30}
                showCount
              />
            </div>
          </div>

          <div className='E1row'>
            <div className='E1rowll'>
              <span> * </span>事故藏品：
            </div>
            <div className='E1rowrr'>
              <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='E1row E1rowFull'>
            <div className='E1rowll'>
              事故前&emsp;
              <br />
              藏品状态：
            </div>
            <div className='E1rowrr'>
              <ZRichTexts
                check={false}
                dirCode='E1accident'
                myUrl='cms/goodsFile/upload'
                isLook={['3', '4'].includes(key)}
                ref={ZRichTextRefQian}
                isOne={true}
                upAudioBtnNone={true}
              />
            </div>
          </div>

          <div className='E1row E1rowFull'>
            <div className='E1rowll'>
              事故后&emsp;
              <br />
              藏品现状：
            </div>
            <div className='E1rowrr'>
              <ZRichTexts
                check={false}
                dirCode='E1accident'
                myUrl='cms/goodsFile/upload'
                isLook={['3', '4'].includes(key)}
                ref={ZRichTextRefHou}
                isOne={true}
                upAudioBtnNone={true}
              />
            </div>
          </div>

          <div className='E1row E1rowFull'>
            <div className='E1rowll'>
              事故原因&emsp;
              <br />
              及经过：
            </div>
            <div className='E1rowrr'>
              <ZRichTexts
                check={false}
                dirCode='E1accident'
                myUrl='cms/goodsFile/upload'
                isLook={['3', '4'].includes(key)}
                ref={ZRichTextRefYuan}
                isOne={true}
                upAudioBtnNone={true}
              />
            </div>
          </div>

          <div className='E1row E1row2'>
            <div className='E1rowll'>附件：</div>
            <div className='E1rowrr'>
              <Z3upFiles
                max={10}
                isLook={['3', '4'].includes(key)}
                ref={filesRef}
                fileCheck={false}
                dirCode='E1accident'
                myUrl='cms/orderPreserveAccident/upload'
                lookData={topInfo.files || []}
                size={500}
                fromData={{ moduleId: topInfo.id }}
              />
            </div>
          </div>

          <div className='E1row'>
            <div className='E1rowll'>鉴定人：</div>
            <div className='E1rowrr'>
              <Input
                value={topInfo.authUser}
                onChange={e => setTopInfo({ ...topInfo, authUser: e.target.value.trim() })}
                readOnly={['3', '4'].includes(key)}
                placeholder='请输入内容'
                maxLength={30}
                showCount
              />
            </div>
          </div>

          <div className='E1row E1rowFull'>
            <div className='E1rowll'>备注：</div>
            <div className='E1rowrr'>
              <ZRichTexts
                check={false}
                dirCode='E1accident'
                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='E1accident'
            myUrl='cms/orderPreserveAccident/upload'
            fromData={{ moduleId: topInfo.id }}
          />
        ) : null}
      </div>

      {/* 底部按钮 */}
      <div className='E1btn'>
        {['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('/accident')} />
          </>
        )}
      </div>
    </div>
  )
}

const MemoE1edit = React.memo(E1edit)

export default MemoE1edit
