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/B3_4page/type'
import {
  E2_APIcreate,
  E2_APIdel,
  E2_APIgetInfo,
  E2_APIrevocation,
  E2_APIsaveApply,
  E2_APIsaveAudit,
  E2_APIsaveCreate,
  E2_APIsaveDraft
} from '@/store/action/E2damaged'
import { pageTitTxtObj } from '@/pages/D_storeManage/D4impStor/D4edit'
import { MessageFu } from '@/utils/message'
import history, { btnFlagFu2, openGoodsInfoFu } from '@/utils/history'
import { C1GoodType } from '@/pages/A3_ledger/C1ledger/type'
import classNames from 'classnames'
import dayjs from 'dayjs'
import { Button, DatePicker, Input, Select } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import B3GaddNow from '@/pages/B_enterTibet/B3goodsTable/B3GaddNow'
import { EXbtnFu } from '@/utils/EXBtn'
import X3auditInfo from '@/pages/X_stock/X3auditInfo'
import { D4goodsTableC, statusObj } from '@/utils/tableData'
import { B3aForm1 } from '@/pages/B_enterTibet/B3_4page/B3edit/data'
import Z3upFiles from '@/components/Z3upFiles'
import ZRichTexts from '@/components/ZRichTexts'
import MyTable from '@/components/MyTable'
import B3flowTable from '@/pages/B_enterTibet/B3flowTable'
import Y1cathet from '@/pages/Y_goodsDetails/Y1cathet'

function E2edit() {
  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 E2_APIcreate()
    if (res.code === 0) {
      setTopInfo(res.data)
    }
  }, [])

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

      // 设置富文本
      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 pageTitTxt = useMemo(() => {
    return Reflect.get(pageTitTxtObj, key)
  }, [key])

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

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

        if (res.code === 0) {
          MessageFu.success('审批成功')
          // 跳详情页
          history.push(`/damaged_edit/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(',')
        }
        // console.log(123, obj)

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

        if (val === '草稿') {
          // 存草稿 当前页保存 不跳转
          const res = await E2_APIsaveDraft(obj)
          if (res.code === 0) {
            MessageFu.success('草稿保存成功')
          }
        } else {
          const res = val === '创建' ? await E2_APIsaveCreate(obj) : await E2_APIsaveApply(obj)
          if (res.code === 0) {
            MessageFu.success(`${val}成功`)
            // 跳到详情页
            history.push(`/damaged_edit/4/${topInfo.id}`)
          }
        }
      }
    },
    [auditSta, 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 tableLastBtn = useMemo(() => {
    return [
      {
        title: '存放位置',
        width: 200,
        render: (item: C1GoodType) => {
          return item.siteStr ? item.siteStr.replaceAll(',', ' / ') : '（空）'
        }
      },
      {
        title: '操作',
        render: (item: C1GoodType) => {
          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: '' })

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

      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(','),
        goods: topInfo.goods.map(v => ({
          goodsId: v.id,
          siteId: v.siteId
        }))
      }

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

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

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

  return (
    <div className={styles.E2edit}>
      <div className='pageTitle'>残损登记-{pageTitTxt}</div>

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

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

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

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

          <div className='E2row'>
            <div className='E2rowll'>相关盘点：</div>
            {/* 待完善 */}
            <div className='E2rowrr'>
              <Select
                disabled={['3', '4'].includes(key)}
                placeholder={['3', '4'].includes(key) ? '（空）' : '请搜索编码'}
                showSearch
                options={[]}
                fieldNames={{ label: 'num', value: 'num' }}
                allowClear={true}
                // value={topInfo.relatedOrderNum || null}
                // onChange={e => setTopInfo({ ...topInfo, relatedOrderNum: e ? e : '' })}
              />
            </div>
          </div>
          <div className='E2row'>
            <div className='E2rowll'>原因事由：</div>
            <div className='E2rowrr'>
              <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='E2row E2row2'>
            <div className='E2rowll'>附件：</div>
            <div className='E2rowrr'>
              <Z3upFiles
                max={10}
                isLook={['3', '4'].includes(key)}
                ref={filesRef}
                fileCheck={false}
                dirCode='E2damaged'
                myUrl='cms/orderPreserveDamaged/upload'
                lookData={topInfo.files || []}
                size={500}
                fromData={{ moduleId: topInfo.id }}
              />
            </div>
          </div>

          <div className='E2row E2rowFull'>
            <div className='E2rowll'>备注：</div>
            <div className='E2rowrr'>
              <ZRichTexts
                check={false}
                dirCode='E2damaged'
                myUrl='cms/orderPreserveDamaged/upload'
                isLook={['3', '4'].includes(key)}
                ref={ZRichTextRef}
                isOne={true}
                upAudioBtnNone={true}
              />
            </div>
          </div>
        </div>

        {/* 藏品清单 */}
        <div className='E2googsBox'>
          <div className='E2Tit2'>
            <div className='E2Tit2ll'>藏品清单</div>
            <div className='E2Tit2rr'>
              {['3', '4'].includes(key) ? null : (
                <Button
                  type='primary'
                  onClick={() =>
                    setNowSta({
                      key: 'E2',
                      id: 'cms/orderPreserveDamaged/goods/getList'
                    })
                  }
                >
                  新增
                </Button>
              )}
            </div>
          </div>

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

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

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

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

      {nowSta.id ? (
        <B3GaddNow
          nowSta={nowSta}
          closeFu={() => setNowSta({ key: '', id: '' })}
          dataResFu={data => setTopInfo({ ...topInfo, goods: data })}
          oldCheckArr={topInfo.goods || []}
          // 待完善
          // canObj={{ storageId: topInfo.storageId }}
        />
      ) : null}
    </div>
  )
}

const MemoE2edit = React.memo(E2edit)

export default MemoE2edit
