import React, { useCallback, useEffect, useMemo, 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 { C1GoodType } from '@/pages/A3_ledger/C1ledger/type'
import {
  D8_APIcreate,
  D8_APIdel,
  D8_APIgetInfo,
  D8_APIrevocation,
  D8_APIsaveApply,
  D8_APIsaveAudit,
  D8_APIsaveCreate,
  D8_APIsaveDraft
} from '@/store/action/D8cancel'
import { pageTitTxtObj } from '../../D4impStor/D4edit'
import { MessageFu } from '@/utils/message'
import history, { btnFlagFu2, openGoodsInfoFu } from '@/utils/history'
import TextArea from 'antd/es/input/TextArea'
import { Button } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import { EXbtnFu } from '@/utils/EXBtn'
import X3auditInfo from '@/pages/X_stock/X3auditInfo'
import { D8tableCgoods, statusObj } from '@/utils/tableData'
import ZRichTexts from '@/components/ZRichTexts'
import MyTable from '@/components/MyTable'
import ZflowTable from '@/components/ZflowTable'
import ZupFileTable from '@/components/ZupFileTable'
import ZGaddNow from '@/components/ZGaddNow'
import classNames from 'classnames'
import Y1cathet from '@/pages/Y_goodsDetails/Y1cathet'

const tableArrTemp = [
  { name: '注销后去向', key: 'txt1' },
  { name: '注销原因', key: 'txt2' },
  { name: '备注', key: 'txt3' }
]

function D8edit() {
  const { key, id } = useParams<any>()
  // key:1 新增 2编辑 3审批 4查看
  // 滚到顶部
  const sollrDom = useRef<HTMLDivElement>(null)
  // 顶部数据
  const [topInfo, setTopInfo] = useState({} as FourTableType)

  // 藏品清单快照数据
  const [snaps, setSnaps] = useState<C1GoodType[]>([])
  const delSnapIdsRef = useRef<number[]>([])

  const snapsID2ref = useRef<{ goodsId: number; id: number }[]>([])

  // 创建订单
  const creatFu = useCallback(async () => {
    const res = await D8_APIcreate()
    if (res.code === 0) {
      setTopInfo(res.data)
    }
  }, [])

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

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

      // 藏品清单快照信息id对比
      const arrTemp: any = []
      const snapsTemp = data.snaps || []

      snapsTemp.forEach((v: any) => {
        snapsID2ref.current.push({ goodsId: v.goodsId, id: v.id })

        const obj = JSON.parse(v.snap || '{}')
        if (obj.id) obj.id2 = v.id

        arrTemp.push(obj)
      })
      setSnaps(arrTemp)
    }
  }, [id])

  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])

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

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

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

  // 新增的底部按钮点击
  const btnClickFu = useCallback(
    async (val: '草稿' | '创建' | '保存' | '审批') => {
      if (val !== '草稿') {
        if (snaps.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 D8_APIsaveAudit({
          orderId: topInfo.id,
          rtfOpinion: rtf2,
          status: auditSta === '同意' ? 1 : 2
        })

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

        const obj = {
          ...topInfo,
          rtf: JSON.stringify(rtf1.val || ''),
          goodsIds: snaps.map(v => v.id).join(','),
          delSnapIds: delSnapIdsRef.current.length ? delSnapIdsRef.current : '',
          snaps: snaps.map(v => ({
            goodsId: v.id,
            id: v.id2 ? v.id2 : null,
            orderId: topInfo.id,
            snap: JSON.stringify(v)
          }))
        }
        // console.log(123, obj.snaps)

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

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

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

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

  // 表格的输入框改变
  const tableInputChange = useCallback(
    (id: number, val: string, key: 'txt1') => {
      setSnaps(
        snaps.map(v => ({
          ...v,
          [key]: v.id === id ? val : v[key]
        }))
      )
    },
    [snaps]
  )

  const tableLastBtn = useMemo(() => {
    const arr: any = []

    tableArrTemp.forEach(v => {
      arr.push({
        title: v.name,
        width: 150,
        render: (item: C1GoodType) => {
          return (
            <TextArea
              readOnly={['3', '4'].includes(key)}
              placeholder={
                ['3', '4'].includes(key) && !item[v.key as 'txt1']
                  ? '（空）'
                  : '请输入内容，不超过200字'
              }
              maxLength={200}
              value={item[v.key as 'txt1']}
              onChange={e => tableInputChange(item.id, e.target.value, v.key as 'txt1')}
            />
          )
        }
      })
    })

    arr.push({
      title: '操作',
      render: (item: C1GoodType) => {
        return (
          <>
            <Button size='small' type='text' onClick={() => openGoodsInfoFu(item.id)}>
              查看
            </Button>
            {['3', '4'].includes(key) ? null : (
              <MyPopconfirm
                txtK='删除'
                onConfirm={() => {
                  if (item.id2 && !delSnapIdsRef.current.includes(item.id2))
                    delSnapIdsRef.current.push(item.id2)
                  setSnaps(snaps.filter(v => v.id !== item.id))
                }}
              />
            )}
          </>
        )
      }
    })

    return arr
  }, [key, snaps, tableInputChange])

  // 点击添加按钮
  const [nowSta, setNowSta] = useState({ key: '', id: '' })

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

      // 富文本
      const rtf1 = ZRichTextRef.current?.fatherBtnOkFu() || { flag: true }

      const obj = {
        ...topInfo,
        rtf: JSON.stringify(rtf1.val || ''),
        goodsIds: snaps.map(v => v.id).join(','),
        delSnapIds: delSnapIdsRef.current.length ? delSnapIdsRef.current : '',
        snaps: snaps.map(v => ({
          goodsId: v.id,
          id: v.id2 ? v.id2 : null,
          orderId: topInfo.id,
          snap: JSON.stringify(v)
        }))
      }

      // console.log(123, obj.snaps)

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

      const res =
        val === '创建'
          ? await D8_APIsaveCreate(obj)
          : val === '提交'
          ? await D8_APIsaveApply(obj)
          : await D8_APIrevocation(id)

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

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

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

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

  return (
    <div className={styles.D8edit}>
      <div className='pageTitle'>藏品注销-{pageTitTxt}</div>

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

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

        <div className='D8rowAll'>
          {topInfo.id ? (
            <>
              <div className='D8row'>
                <div className='D8rowll'>业务单号：</div>
                <div className='D8rowrr'>{topInfo.num}</div>
              </div>

              <div className='D8row'>
                <div className='D8rowll'>业务名称：</div>
                <div className='D8rowrr'>{topInfo.name}</div>
              </div>

              <div className='D8row'>
                <div className='D8rowll'>发起人：</div>
                <div className='D8rowrr'>
                  {topInfo.creatorName} - {topInfo.createTime}
                </div>
              </div>

              <div className='D8row'>
                <div className='D8rowll'>发起部门：</div>
                <div className='D8rowrr'>{topInfo.deptName}</div>
              </div>
            </>
          ) : null}

          <div className='D8row D8rowFull'>
            <div className='D8rowll'>备注：</div>
            <div className='D8rowrr'>
              <ZRichTexts
                check={false}
                dirCode='D8cancel'
                myUrl='cms/goodsFile/upload'
                isLook={['3', '4'].includes(key)}
                ref={ZRichTextRef}
                isOne={true}
                upAudioBtnNone={true}
              />
            </div>
          </div>
        </div>

        {/* 藏品清单 */}
        <div className='D8googsBox'>
          <div className='D8Tit2'>
            <div className='D8Tit2ll'>藏品清单</div>
            <div className='D8Tit2rr'>
              {['3', '4'].includes(key) ? null : (
                <Button
                  type='primary'
                  onClick={() =>
                    setNowSta({
                      key: 'D8',
                      id: 'cms/orderLogout/goods/getList'
                    })
                  }
                >
                  添加
                </Button>
              )}
            </div>
          </div>

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

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

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

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

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

      {nowSta.id ? (
        <ZGaddNow
          nowSta={nowSta}
          closeFu={() => setNowSta({ key: '', id: '' })}
          dataResFu={data => {
            const dataTemp = [...data]
            dataTemp.forEach(v => {
              // id2表示的是自己这条数据的id id才是goodsId
              const obj = snapsID2ref.current.find(c => c.goodsId === v.id)

              if (obj) v.id2 = obj.id
            })
            setSnaps(dataTemp)
          }}
          oldCheckArr={snaps}
        />
      ) : null}
    </div>
  )
}

const MemoD8edit = React.memo(D8edit)

export default MemoD8edit
