import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import style from './index.module.scss'
import { useParams } from 'react-router-dom'
import X3auditInfo from '@/pages/X_stock/X3auditInfo'
import { Button, Input, Radio, Select } from 'antd'
import { statusObj } from '@/utils/tableData'
import MyTable, { MyTableMethods } from '@/components/MyTable'
import { F1_SON_TYPE_NAME_OPTS, F1_SON_TYPE_OPTS } from '../constants'
import ZGaddNow from '@/components/ZGaddNow'
import MyPopconfirm from '@/components/MyPopconfirm'
import history, { btnFlagFu2, infoPageBackFu, openGoodsInfoFu } from '@/utils/history'
import {
  F1_APIcreate,
  F1_APIdel,
  F1_APIgetInfo,
  F1_APIrevocation,
  F1_APIsaveApply,
  F1_APIsaveAudit,
  F1_APIsaveCreate,
  F1_APIsaveDraft
} from '@/store/action/F1exhibition'
import { MessageFu } from '@/utils/message'
import { EXbtnFu } from '@/utils/EXBtn'
import { F1_SON_TYPE_ENUM, F1_SON_TYPE_NAME_ENUM, F1exhibitionItemType } from '../types'
import ZflowTable from '@/components/ZflowTable'
import { pageTitTxtObj } from '@/pages/D_storeManage/D4impStor/D4edit'
import { C1GoodType } from '@/pages/A3_ledger/C1ledger/type'
import { areAllCheckersFilled } from '@/utils/objects'
import dayjs, { Dayjs } from 'dayjs'
import { EXPORT_WORD_ENUM } from '@/utils/exportTemplates'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '@/store'
import { D6_APIgetList } from '@/store/action/D6putsStor'
import { D4_APIgetList } from '@/store/action/D4impStor'

function F1edit() {
  const dispatch = useDispatch()
  const putsStor = useSelector((state: RootState) => state.D6putsStor.tableInfo)
  const impStor = useSelector((state: RootState) => state.D4impStor.tableInfo)
  const { key, id } = useParams<any>()
  // 滚到顶部
  const sollrDom = useRef<HTMLDivElement>(null)
  // 审批的sta
  const [auditSta, setAuDitSta] = useState('')
  // 审批意见的ref
  const ZAuditRef = useRef<any>(null)
  // 顶部数据
  const [topInfo, setTopInfo] = useState({} as F1exhibitionItemType)
  // 点击新增
  const [nowSta, setNowSta] = useState({ key: '', id: '' })
  // 申请记录
  const [auditsShow, setAuditsShow] = useState(false)
  // 藏品清单快照数据
  const [snaps, setSnaps] = useState<C1GoodType[]>([])
  const delSnapIdsRef = useRef<number[]>([])
  const label1 = useMemo(
    () => (topInfo.sonType === F1_SON_TYPE_ENUM.IN ? '借展部门' : '借展单位'),
    [topInfo]
  )
  const goodColumns = useMemo(() => {
    const temp = [
      ['txt', '编号类型', 'numName'],
      ['txt', '藏品编号', 'num'],
      ['txt', '藏品名称', 'name'],
      ['ping', '数量', 'pcs', 'pcsUnit'],
      ['datePicker', '借出日期 *', 'lendDate'],
      [
        'input',
        '出借经手人（甲方）',
        'lenderA',
        {
          maxLength: 20,
          placeholder: '请填写内容，不超过20字'
        }
      ],
      [
        'input',
        '出借经手人（乙方）',
        'lenderb',
        {
          maxLength: 20,
          placeholder: '请填写内容，不超过20字'
        }
      ],
      ['datePicker', '预计归还日期', 'expectedReturnDate'],
      [
        'datePicker',
        '归还日期',
        'returnDate',
        {
          disabledDate: (current?: Dayjs) => current && current > dayjs().endOf('day')
        }
      ],
      [
        'input',
        '归还经手人（甲方）',
        'handlerA',
        {
          maxLength: 20,
          placeholder: '请填写内容，不超过20字'
        }
      ],
      [
        'input',
        '归还经手人（乙方）',
        'handlerB',
        {
          maxLength: 20,
          placeholder: '请填写内容，不超过20字'
        }
      ],
      [
        'input',
        '记录人',
        'recorder',
        {
          maxLength: 20,
          placeholder: '请填写内容，不超过20字'
        }
      ],
      [
        'input',
        '备注',
        'remark',
        {
          maxLength: 20,
          placeholder: '请填写内容，不超过20字'
        }
      ]
    ]

    if (topInfo.sonType === F1_SON_TYPE_ENUM.IN) {
      temp.splice(-1, 0, [
        'input',
        '放置位置',
        'address',
        {
          maxLength: 20,
          placeholder: '请填写内容，不超过20字'
        }
      ])
    }

    return temp
  }, [topInfo.sonType])

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

  const pageDisabled = ['3', '4'].includes(key)
  const tableRef = useRef<MyTableMethods | null>(null)

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

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: any) => (
          <>
            <Button
              size='small'
              type='text'
              onClick={() => openGoodsInfoFu(item.id, 15, '', topInfo.id)}
            >
              查看
            </Button>
            {pageDisabled ? null : (
              <MyPopconfirm
                txtK='删除'
                onConfirm={() => setSnaps(snaps.filter(v => v.id !== item.id))}
              />
            )}
          </>
        )
      }
    ]
  }, [pageDisabled, snaps, topInfo.id])

  // 获取详情
  const getInfoFu = useCallback(
    async (iid = id) => {
      const res = await F1_APIgetInfo(iid)
      if (res.code === 0) {
        const data = res.data
        setTopInfo(data)
        // 藏品清单快照信息id对比
        const arrTemp: any = []
        const snapsTemp = data.snaps || []

        snapsTemp.forEach((v: any) => {
          const { cusForm, ...obj } = JSON.parse(v.snap || '{}')
          if (obj.id) obj.id2 = v.id
          const temp: any = {
            ...cusForm
          }
          if (cusForm) {
            if (cusForm[`${v.goodsId}-lendDate`]) {
              temp[`${v.goodsId}-lendDate`] = dayjs(cusForm[`${v.goodsId}-lendDate`])
            }
            if (cusForm[`${v.goodsId}-expectedReturnDate`]) {
              temp[`${v.goodsId}-expectedReturnDate`] = dayjs(
                cusForm[`${v.goodsId}-expectedReturnDate`]
              )
            }
            if (cusForm[`${v.goodsId}-returnDate`]) {
              temp[`${v.goodsId}-returnDate`] = dayjs(cusForm[`${v.goodsId}-returnDate`])
            }
            tableRef.current?.form.setFieldsValue(temp)
          }

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

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

  // 查看模式点击审批 编辑
  const lookJumpFu = useCallback(
    (val: '审批' | '编辑') => {
      history.push(`/exhibition_edit/${val === '审批' ? 3 : 2}/${id}`)
      MessageFu.success(`已跳转至${val}页面`)
    },
    [id]
  )

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

      const tableValues = tableRef.current?.form.getFieldsValue()
      const obj = {
        ...topInfo,
        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,
            cusForm: tableValues
          }),
          returnDate: tableValues[`${v.id}-returnDate`]
            ? tableValues[`${v.id}-returnDate`].format('YYYY-MM-DD')
            : undefined
        }))
      }

      const res =
        val === '创建'
          ? await F1_APIsaveCreate(obj)
          : val === '提交'
          ? await F1_APIsaveApply(obj)
          : await F1_APIrevocation(id)

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

  // 查看模式下的按钮
  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.REGISTER_LEDGER])}

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

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

  const checkDataFu = useCallback(() => {
    if (!topInfo.typeName) {
      MessageFu.warning('展览名称不能为空')
      return true
    }
    if (!topInfo.sonUnit) {
      MessageFu.warning(label1 + '不能为空')
      return true
    }

    const tableInputVals = tableRef.current?.form.getFieldsValue()
    if (!areAllCheckersFilled('lendDate', tableInputVals)) {
      MessageFu.warning(`请选择借出日期`)
      return true
    }

    return false
  }, [topInfo.sonUnit, topInfo.typeName, label1])

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

      if (val !== '草稿') {
        if (!snaps.length) {
          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 F1_APIsaveAudit({
          orderId: topInfo.id,
          rtfOpinion: rtf2,
          status: auditSta === '同意' ? 1 : 2
        })

        if (res.code === 0) {
          MessageFu.success('审批成功')
          // 跳详情页
          history.push(`/exhibition_edit/4/${topInfo.id}`)
        }
      } else {
        const tableValues = tableRef.current?.form.getFieldsValue()
        const obj = {
          ...topInfo,
          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,
            returnDate: tableValues[`${v.id}-returnDate`]
              ? tableValues[`${v.id}-returnDate`].format('YYYY-MM-DD')
              : undefined,
            snap: JSON.stringify({
              ...v,
              cusForm: tableValues
            })
          }))
        }
        // console.log(123, obj)

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

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

  // 创建订单
  const creatFu = useCallback(async () => {
    const res = await F1_APIcreate()
    if (res.code === 0) {
      setTopInfo({
        ...res.data,
        sonType: F1_SON_TYPE_ENUM.IN,
        sonTypeName: F1_SON_TYPE_NAME_ENUM.TEMP
      })
    }
  }, [])

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

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

  useEffect(() => {
    dispatch(
      D6_APIgetList({
        pageNum: 1,
        pageSize: 999
      })
    )
    dispatch(
      D4_APIgetList({
        pageNum: 1,
        pageSize: 999
      })
    )
  }, [dispatch])

  return (
    <div className={style.F1edit}>
      <div className='pageTitle'>借展管理-{pageTitTxt}</div>

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

        {/* 表单字段、附件等 */}
        <div className='D4Tit'>
          申请信息
          {key === '1' ? null : (
            <Button type='dashed'>{Reflect.get(statusObj, topInfo.status)}</Button>
          )}
        </div>
        <div className='D4rowAll'>
          <div className='D4row'>
            <div className='D4rowll'>业务单号：</div>
            <div className='D4rowrr'>{topInfo.num}</div>
          </div>
          <div className='D4row'>
            <div className='D4rowll'>业务名称：</div>
            <div className='D4rowrr'>{topInfo.name}</div>
          </div>
          <div className='D4row'>
            <div className='D4rowll'>发起人：</div>
            <div className='D4rowrr'>
              {topInfo.creatorName || ''} - {topInfo.createTime || ''}
            </div>
          </div>
          <div className='D4row'>
            <div className='D4rowll'>发起部门：</div>
            <div className='D4rowrr'>{topInfo.deptName}</div>
          </div>
        </div>

        <div className='D4Tit'>展览信息</div>
        <div className='D4rowAll'>
          <div className='D4row'>
            <div className='D4rowll'>
              <span> * </span>展览名称：
            </div>
            <div className='D4rowrr'>
              <Input
                value={topInfo.typeName}
                onChange={e => setTopInfo({ ...topInfo, typeName: e.target.value.trim() })}
                readOnly={pageDisabled}
                placeholder='请输入内容'
                maxLength={30}
                showCount
              />
            </div>
          </div>
          <div className='D4row'>
            <div className='D4rowll'>
              <span> * </span>借展类型：
            </div>
            <div className='D4rowrr'>
              <Radio.Group
                value={topInfo.sonType}
                disabled={pageDisabled}
                onChange={e => setTopInfo({ ...topInfo, sonType: e.target.value })}
              >
                {F1_SON_TYPE_OPTS.map(i => (
                  <Radio key={i.value} value={i.value}>
                    {i.label}
                  </Radio>
                ))}
              </Radio.Group>
            </div>
          </div>
          <div className='D4row'>
            <div className='D4rowll'>
              <span> * </span>展览类型：
            </div>
            <div className='D4rowrr'>
              <Select
                disabled={pageDisabled}
                value={topInfo.sonTypeName}
                options={F1_SON_TYPE_NAME_OPTS}
                onChange={e => setTopInfo({ ...topInfo, sonTypeName: e })}
              />
            </div>
          </div>
          <div className='D4row'>
            <div className='D4rowll'>提用审批单号：</div>
            <div className='D4rowrr'>
              <Select
                allowClear
                showSearch
                options={putsStor.list}
                fieldNames={{
                  label: 'num',
                  value: 'num'
                }}
                placeholder='请输入内容'
                value={topInfo.sonNum ? topInfo.sonNum : undefined}
                onChange={e => setTopInfo({ ...topInfo, sonNum: e })}
              />
            </div>
          </div>
          <div className='D4row'>
            <div className='D4rowll'>
              <span> * </span>
              {label1}：
            </div>
            <div className='D4rowrr'>
              <Input
                value={topInfo.sonUnit}
                onChange={e => setTopInfo({ ...topInfo, sonUnit: e.target.value.trim() })}
                readOnly={pageDisabled}
                placeholder='请输入内容'
                maxLength={30}
                showCount
              />
            </div>
          </div>
          <div className='D4row'>
            <div className='D4rowll'>提退凭证号：</div>
            <div className='D4rowrr'>
              <Select
                allowClear
                showSearch
                options={[...impStor.list, ...putsStor.list]}
                fieldNames={{
                  label: 'num',
                  value: 'num'
                }}
                placeholder='请输入内容'
                value={topInfo.sonNum2 ? topInfo.sonNum2 : undefined}
                onChange={e => setTopInfo({ ...topInfo, sonNum2: e })}
              />
            </div>
          </div>
        </div>

        <div className='D4googsBox'>
          <div className='D4Tit2'>
            <div className='D4Tit2ll'>参展藏品</div>
            <div className='D4Tit2rr'>
              {pageDisabled ? null : (
                <>
                  <Button
                    type='primary'
                    onClick={() => {
                      setNowSta({ key: '5', id: 'cms/orderExhibition/goods/getList' })
                    }}
                  >
                    新增
                  </Button>
                </>
              )}
            </div>
          </div>

          {/* 表格 */}
          <MyTable
            ref={tableRef}
            list={snaps}
            columnsTemp={goodColumns}
            pagingInfo={false}
            lastBtn={tableLastBtn}
            readOnly={pageDisabled}
          />
        </div>
      </div>

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

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

      {/* 新增弹窗 */}
      {nowSta.id ? (
        <ZGaddNow
          menuId={15}
          orderId={topInfo.id}
          nowSta={nowSta}
          searchFilterKey={['statusStorage']}
          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 MemoF1edit = React.memo(F1edit)

export default MemoF1edit
