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 X3auditInfo from '@/pages/X_stock/X3auditInfo'
import { Button, DatePicker, Input } from 'antd'
import dayjs from 'dayjs'
import { B3aForm1 } from '@/pages/B_enterTibet/B3_4page/B3edit/data'
import Z3upFiles from '@/components/Z3upFiles'
import ZRichTexts from '@/components/ZRichTexts'
import B3GaddNow from '@/pages/B_enterTibet/B3goodsTable/B3GaddNow'
import MyTable from '@/components/MyTable'
import history, { btnFlagFu2, openGoodsInfoFu, textFu } from '@/utils/history'
import MyPopconfirm from '@/components/MyPopconfirm'
import { B3eTableC, statusObj } from '@/utils/tableData'
import { MessageFu } from '@/utils/message'
import classNames from 'classnames'
import Y1cathet from '@/pages/Y_goodsDetails/Y1cathet'
import B3GaddNew from '@/pages/B_enterTibet/B3goodsTable/B3GaddNew'
import ImageLazy from '@/components/ImageLazy'
import X2lookText from '@/pages/X_stock/X2lookText'
import B3flowTable from '@/pages/B_enterTibet/B3flowTable'
import { FourTableType } from '@/pages/B_enterTibet/B3_4page/type'
import {
  C6_APIcreate,
  C6_APIdel,
  C6_APIgetInfo,
  C6_APIrevocation,
  C6_APIsaveApply,
  C6_APIsaveAudit,
  C6_APIsaveCreate,
  C6_APIsaveDraft
} from '@/store/action/C6edit'
import { EXbtnFu } from '@/utils/EXBtn'
import {
  ArrKeyType,
  Y11infoArr1,
  Y11infoArr2,
  Y11infoArr3,
  Y11infoArr4,
  Y11infoArr5
} from '@/pages/Y_goodsDetails/Y1cathet/data'
import { baseURL } from '@/utils/http'
import { GoodFileType } from '@/pages/B_enterTibet/B3goodsTable/B3GaddNew/type'

export type OldNewType = {
  name: string
  qian: string | GoodFileType[]
  hou: string | GoodFileType[]
}

const oldNewTxtArr: ArrKeyType = [
  ...Y11infoArr1,
  ...Y11infoArr2,
  ...Y11infoArr3,
  ...Y11infoArr4,
  ...Y11infoArr5,
  {
    name: '封面图',
    key: 'thumb',
    backFu: info => {
      return { thumb: info.thumb, thumbPc: info.thumbPc }
    }
  }
]

function C6add() {
  // 新旧附件信息对比
  const [oldNewArr, setOldNewArr] = useState<OldNewType[]>([])

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

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

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

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

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

      try {
        if (obj.goods && obj.goods.length && obj.goods[0].tempGoodsJson)
          obj.tempGoodsJson = JSON.parse(obj.goods[0].tempGoodsJson)

        if (obj.snap) setOldNewArr(JSON.parse(obj.snap))
      } catch (error) {
        console.log('error:', error)
      }

      setTopInfo(obj)

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

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

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

  // 上传附件的ref
  const filesRef = useRef<any>(null)
  // const filesRes = filesRef.current.filesIdRes();

  // 富文本的ref
  const ZRichTextRef = useRef<any>(null)

  // 审批意见的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 (!topInfo.name) return MessageFu.warning('申请名称不能为空')

      // 藏品编辑校验
      if (val !== '草稿') {
        if (!topInfo.goods || (topInfo.goods && topInfo.goods.length === 0))
          return MessageFu.warning('请选择藏品')

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

        if (res.code === 0) {
          MessageFu.success('审批成功')
          // 跳详情页
          history.push(`/edit_add/4/${topInfo.id}`)
        }
      } else {
        const rtf1 = ZRichTextRef.current?.fatherBtnOkFu() || { flag: true }
        // console.log('申请信息富文本', JSON.stringify(rtf1.val || ''))

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

        const obj = {
          ...topInfo,
          fileIds: filesRes.join(','),
          rtf: JSON.stringify(rtf1.val || ''),
          goodsIds: topInfo.goods.map(v => v.id).join(','),
          snap: JSON.stringify(oldNewArr),
          tempGoodsJson: topInfo.tempGoodsJson
        }
        // console.log(123, obj)

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

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

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

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

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: FourTableType) => {
          return (
            <>
              <Button size='small' type='text' onClick={() => openGoodsInfoFu(item.id)}>
                查看
              </Button>
              {['3', '4'].includes(key) ? null : (
                <MyPopconfirm
                  txtK='删除'
                  onConfirm={() =>
                    setTopInfo({
                      ...topInfo,
                      goods: topInfo.goods.filter(v => v.id !== item.id)
                    })
                  }
                />
              )}
            </>
          )
        }
      }
    ]
  }, [key, topInfo])

  // 点击所选藏品 / 继续编辑
  const [nowSta, setNowSta] = useState({ key: '', id: '', type: '' })

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

      // 上传附件
      const filesRes = filesRef.current.filesIdRes()
      const obj = {
        ...topInfo,
        fileIds: filesRes.join(','),
        rtf: JSON.stringify(rtf1.val || ''),
        goodsIds: topInfo.goods.map(v => v.id).join(','),
        snap: JSON.stringify(oldNewArr),
        tempGoodsJson: topInfo.tempGoodsJson
      }

      const res =
        val === '创建'
          ? await C6_APIsaveCreate(obj)
          : val === '提交'
          ? await C6_APIsaveApply(obj)
          : await C6_APIrevocation(id)

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

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

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

  // 编辑明细 表格

  const tableLastBtn2Fu = useCallback((item: OldNewType, key: 'qian' | 'hou') => {
    if (item.name === '备注') {
      if (textFu(item[key] as string)) {
        return (
          <Button size='small' type='text' onClick={() => setLook(textFu(item[key] as string))}>
            查看
          </Button>
        )
      } else return '-'
    } else if (item.name === '附件信息') {
      let arr = item[key] as GoodFileType[]

      return arr.length
        ? arr.map((v: any, i: number) => (
            <a key={v.id} href={baseURL + v.filePath} download target='_blank' rel='noreferrer'>
              {v.fileName}
              {i < arr!.length - 1 ? '，' : ''}
            </a>
          ))
        : '-'
    } else if (item.name === '封面图') {
      const info: any = item[key]

      return (
        <div className='tableImgAuto'>
          <ImageLazy
            width={60}
            height={60}
            srcBig={info.thumbPc || info.filePath}
            src={info.thumb}
          />
        </div>
      )
    } else return item[key] || '（空）'
  }, [])

  const tableLastBtn2 = useMemo(() => {
    return [
      {
        title: '编辑项',
        render: (item: OldNewType) =>
          ['封面图', '附件信息', '备注'].includes(item.name) ? (
            <span className='C6tab2Tit'>{item.name}</span>
          ) : (
            item.name
          )
      },
      {
        title: '编辑前',
        render: (item: OldNewType) => tableLastBtn2Fu(item, 'qian')
      },
      {
        title: '编辑后',
        render: (item: OldNewType) => tableLastBtn2Fu(item, 'hou')
      }
    ]
  }, [tableLastBtn2Fu])

  //查看富文本信息
  const [look, setLook] = useState('')

  return (
    <div className={styles.C6add}>
      <div className='pageTitle'>藏品编辑-{Reflect.get(pageTitTxtObj, key)}</div>

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

        {/* 表单字段、附件等 */}
        <div className='C6Tit'>
          申请信息
          {key === '1' ? null : (
            <Button type='dashed'>{Reflect.get(statusObj, topInfo.status)}</Button>
          )}
        </div>
        <div className='C6rowAll'>
          <div className='C6row'>
            <div className='C6rowll'>
              <span> * </span>申请名称：
            </div>
            <div className='C6rowrr'>
              <Input
                value={topInfo.name}
                onChange={e => setTopInfo({ ...topInfo, name: e.target.value.trim() })}
                readOnly={['3', '4'].includes(key)}
                placeholder='请输入内容'
                maxLength={30}
                showCount
              />
            </div>
          </div>

          <div className='C6row'>
            <div className='C6rowll'>
              <span> * </span>业务日期：
            </div>
            <div className='C6rowrr'>
              <DatePicker
                disabled={['3', '4'].includes(key)}
                allowClear={false}
                value={dayjs(topInfo.date)}
                onChange={timeChange}
              />
            </div>
          </div>

          {B3aForm1.map(v => (
            <div className='C6row' key={v.name}>
              <div className='C6rowll'>{v.name}：</div>
              <div className='C6rowrr'>
                {topInfo[v.key as 'name']}
                {['3', '4'].includes(key) && v.name === '发起人'
                  ? ' - ' + topInfo.createTime || ''
                  : ''}
              </div>
            </div>
          ))}

          <div className='C6row C6row2'>
            <div className='C6rowll'>附件：</div>
            <div className='C6rowrr'>
              <Z3upFiles
                max={10}
                isLook={['3', '4'].includes(key)}
                ref={filesRef}
                fileCheck={false}
                dirCode='C6edit'
                myUrl='cms/orderEdit/upload'
                lookData={topInfo.files || []}
                size={500}
              />
            </div>
          </div>

          <div className='C6row'>
            <div className='C6rowll'>原因事由：</div>
            <div className='C6rowrr'>
              <Input
                value={topInfo.reason}
                onChange={e => setTopInfo({ ...topInfo, reason: e.target.value })}
                readOnly={['3', '4'].includes(key)}
                placeholder='请输入内容'
                maxLength={30}
                showCount
              />
            </div>
          </div>

          <div className='C6row C6rowFull'>
            <div className='C6rowll'>备注：</div>
            <div className='C6rowrr'>
              <ZRichTexts
                check={false}
                dirCode='C6edit'
                myUrl='cms/orderEdit/upload'
                isLook={['3', '4'].includes(key)}
                ref={ZRichTextRef}
                isOne={true}
                upAudioBtnNone={true}
              />
            </div>
          </div>
        </div>

        {/* 所选藏品 */}
        <div className='C6googsBox'>
          <div className='C6Tit2'>
            <div className='C6Tit2ll'>所选藏品</div>
            <div className='C6Tit2rr'>
              {['3', '4'].includes(key) ? null : (
                <>
                  <Button
                    type='primary'
                    onClick={() =>
                      setNowSta({ key: '7', id: 'cms/orderEdit/goods/getList', type: 'now' })
                    }
                  >
                    选择藏品
                  </Button>
                  <Button
                    disabled={!(topInfo.goods && topInfo.goods.length)}
                    type='primary'
                    onClick={() =>
                      setNowSta({ key: '7', id: topInfo.goods[0].id + '', type: 'new' })
                    }
                  >
                    继续编辑
                  </Button>
                </>
              )}
            </div>
          </div>

          {/* 表格 */}
          <MyTable
            list={topInfo.goods || []}
            columnsTemp={B3eTableC}
            startBtn={startBtn}
            lastBtn={tableLastBtn}
            pagingInfo={false}
          />
        </div>

        {/* 编辑明细 */}
        <div className='C6googsBox'>
          <div className='C6Tit'>编辑明细</div>

          {/* 表格 */}
          <MyTable
            rowKey='name'
            list={oldNewArr}
            columnsTemp={[]}
            lastBtn={tableLastBtn2}
            pagingInfo={false}
          />
        </div>

        {/* 申请流程 */}
        {['3', '4'].includes(key) ? <B3flowTable tableArr={topInfo.audits || []} /> : null}
      </div>

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

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

      {/* 所选藏品弹窗 / 继续编辑 */}
      {nowSta.id ? (
        nowSta.type === 'now' ? (
          <B3GaddNow
            isOne={true}
            nowSta={nowSta}
            closeFu={() => setNowSta({ key: '', id: '', type: '' })}
            dataResFu={data => {
              setTopInfo({ ...topInfo, goods: data })
              setTimeout(() => {
                setNowSta({ key: '7', id: data[0].id + '', type: 'new' })
              }, 20)

              // 编辑明细清空
              if (topInfo.goods && topInfo.goods[0] && data[0].id !== topInfo.goods[0].id) {
                setOldNewArr([])
              }
            }}
            oldCheckArr={topInfo.goods || []}
          />
        ) : (
          <B3GaddNew
            nowSta={nowSta}
            closeFu={() => setNowSta({ key: '', id: '', type: '' })}
            isEdit={true}
            succFu={(newObj, _, fileNewTemp, fileOldTemp) => {
              const arrRes: OldNewType[] = []

              oldNewTxtArr.forEach(v => {
                const oldInfo = topInfo.goods[0]
                let oldTxt = oldInfo[v.key]
                let newTxt = newObj[v.key] as string

                if ((oldTxt || newTxt) && oldTxt !== newTxt && v.name !== '制档日期') {
                  if (v.backFu && v.name !== '备注') oldTxt = v.backFu(oldInfo)
                  if (v.backFu && v.name !== '备注') newTxt = v.backFu(newObj)

                  arrRes.push({
                    name: v.name,
                    qian: oldTxt,
                    hou: newTxt
                  })
                }
              })

              // 附件信息的对比

              const fileOld = fileOldTemp || []
              const fileNew = fileNewTemp || []

              const fileOldIds = fileOld.map(v => v.id).join('')

              const fileNewIds = fileNew.map(v => v.id).join('')

              if (fileOldIds !== fileNewIds) {
                arrRes.push({
                  name: '附件信息',
                  qian: fileOld.map(
                    v =>
                      ({
                        id: v.id,
                        fileName: v.fileName,
                        filePath: v.filePath
                      } as GoodFileType)
                  ),
                  hou: fileNew.map(
                    v =>
                      ({
                        id: v.id,
                        fileName: v.fileName,
                        filePath: v.filePath
                      } as GoodFileType)
                  )
                })
              }

              setTopInfo({ ...topInfo, tempGoodsJson: newObj })

              setOldNewArr(arrRes)
            }}
          />
        )
      ) : null}

      {/* 查看富文本 */}
      {look ? <X2lookText closeFu={() => setLook('')} text={look} /> : null}
    </div>
  )
}

const MemoC6add = React.memo(C6add)

export default MemoC6add
