import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { useParams } from 'react-router-dom'
import { Button, DatePicker, Input, Modal, Select } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import history, { btnFlagFu2 } from '@/utils/history'
import { MessageFu } from '@/utils/message'
import { statusObj } from '@/utils/tableData'
import X3auditInfo from '@/pages/X_stock/X3auditInfo'
import ZflowTable from '@/components/ZflowTable'
import MyTable, { MyTableMethods } from '@/components/MyTable'
import { EXbtnFu } from '@/utils/EXBtn'
import {
  D7_APIcreate,
  D7_APIdel,
  D7_APIgetInfo,
  D7_APIsaveApply,
  D7_APIsaveAudit,
  D7_APIsaveCreate,
  D7_APIsaveDraft
} from '@/store/action/D7check'
import { ID7CheckItem } from '../types'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '@/store'
import { D2_APIgetList } from '@/store/action/D2storSet'
import { StocktakingModal } from '../components/StocktakingModal'
import { D7CHECK_COLLECTION_COLUMNS } from '../constants'
import dayjs from 'dayjs'
import { areAllCheckersFilled } from '@/utils/objects'
import { C1GoodType } from '@/pages/A3_ledger/C1ledger/type'
import { BatchFillingModal } from '../components/BatchFillingModal'
import { EXPORT_WORD_ENUM } from '@/utils/exportTemplates'

export const pageTitTxtObj = {
  1: '新增',
  2: '编辑',
  3: '审批',
  4: '查看'
}

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

  // 滚到顶部
  const sollrDom = useRef<HTMLDivElement>(null)
  // 顶部数据
  const [topInfo, setTopInfo] = useState({} as ID7CheckItem)
  const { list: storageIdArr } = useSelector((state: RootState) => state.D2storSet.tableInfo)
  const [stocktakingVisible, setStocktakingVisible] = useState(false)
  const [batchFillingVisible, setBatchFillingVisible] = useState(false)
  const [collectionList, setCollectionList] = useState<C1GoodType[]>([])
  const tableRef = useRef<MyTableMethods | null>(null)
  const delSnapIdsRef = useRef<number[]>([])
  // 变更分库缩写 清空 藏品清单
  const [isModalOpen, setIsModalOpen] = useState(0)

  const dispatch = useDispatch()

  useEffect(() => {
    dispatch(D2_APIgetList({ pageNum: 1, pageSize: 99999 }))
  }, [dispatch])

  // 创建订单
  const creatFu = useCallback(async () => {
    const res = await D7_APIcreate()
    if (res.code === 0) {
      setTopInfo({
        ...res.data,
        date: dayjs().format('YYYY-MM-DD')
      })
    }
  }, [])

  // 获取详情
  const getInfoFu = useCallback(
    async (iid = id) => {
      const res = await D7_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
          if (cusForm) tableRef.current?.form.setFieldsValue(cusForm)

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

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

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

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

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

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

  const checkDataFu = useCallback(() => {
    if (!topInfo.date) {
      MessageFu.warning('请选择盘点日期')
      return true
    }
    if (!topInfo.num) {
      MessageFu.warning('请填写盘点单编号')
      return true
    }
    if (!topInfo.storageId) {
      MessageFu.warning('请选择分库')
      return true
    }
    if (!topInfo.reason) {
      MessageFu.warning('请填写盘点事由')
      return true
    }
    if (!collectionList.length) {
      MessageFu.warning('请添加盘点范围')
      return true
    }

    const tableInputVals = tableRef.current?.form.getFieldsValue()
    if (!areAllCheckersFilled('checker', tableInputVals)) {
      MessageFu.warning(`请填写盘点人`)
      return true
    }

    return false
  }, [topInfo, collectionList])

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

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

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

        const obj = {
          ...topInfo,
          goodsIds: collectionList.map(v => v.id).join(','),
          delSnapIds: delSnapIdsRef.current.length ? delSnapIdsRef.current : '',
          snaps: collectionList.map(i => ({
            goodsId: i.id,
            id: i.id2 ? i.id2 : null,
            orderId: topInfo.id,
            statusCheck: tableValues[`${i.id}-statusCheck`],
            snap: JSON.stringify({
              ...i,
              cusForm: tableValues
            })
          })),
          rtf: JSON.stringify(rtf1.val || '')
        }
        // console.log(123, obj)

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

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

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

      const obj = {
        ...topInfo,
        goodsIds: collectionList.map(v => v.id).join(','),
        delSnapIds: delSnapIdsRef.current.length ? delSnapIdsRef.current : '',
        snaps: collectionList.map(i => ({
          goodsId: i.id,
          id: i.id2 ? i.id2 : null,
          orderId: topInfo.id,
          statusCheck: tableValues[`${i.id}-statusCheck`],
          snap: JSON.stringify({
            ...i,
            cusForm: tableValues
          })
        })),
        rtf: JSON.stringify(rtf1.val || '')
      }

      const res = val === '创建' ? await D7_APIsaveCreate(obj) : await D7_APIsaveApply(obj)

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

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

  // 查看模式点击审批 编辑
  const lookJumpFu = useCallback(
    (val: '审批' | '编辑') => {
      history.push(`/check_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)['审批'] ? (
          <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.COLLECTION_INVENTORY])}

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

        <Button onClick={() => history.push('/check')}>返回</Button>
      </>
    )
  }, [delFu, lookBtnFu, lookJumpFu, topInfo])

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

  const handleStocktakingOk = (list: any[]) => {
    delSnapIdsRef.current.push(...collectionList.map(i => i.id2))
    setCollectionList(list)
  }

  const handleBatchFillingOk = (form: any) => {
    const temp: Record<string, string> = {}
    collectionList.forEach(item => {
      temp[`${item.id}-checker`] = form.checker
      temp[`${item.id}-remark`] = form.remark
    })
    tableRef.current?.form.setFieldsValue(temp)
  }

  return (
    <div className={styles.D3staff}>
      <div className='pageTitle'>藏品盘点-{pageTitTxt}</div>

      <div className='D4main' ref={sollrDom}>
        {['3'].includes(key) ? (
          <X3auditInfo
            dirCode='D7check'
            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'>
              <span>*</span>盘点日期：
            </div>
            <div className='D4rowrr'>
              {topInfo.id && (
                <DatePicker
                  defaultValue={dayjs(topInfo.date)}
                  style={{ width: '300px' }}
                  onChange={e => {
                    setTopInfo({ ...topInfo, date: e.format('YYYY-MM-DD') })
                  }}
                />
              )}
            </div>
          </div>

          <div className='D4row'>
            <div className='D4rowll'>
              <span>*</span>盘点单编号：
            </div>
            <div className='D4rowrr'>
              <Input
                value={topInfo.num}
                onChange={e => setTopInfo({ ...topInfo, num: e.target.value })}
                readOnly={['3', '4'].includes(key)}
                placeholder='请输入内容'
                maxLength={30}
                showCount
              />
            </div>
          </div>

          <div className='D4row'>
            <div className='D4rowll'>
              <span>*</span>分库缩写：
            </div>
            <div className='D4rowrr'>
              <Select
                disabled={['3', '4'].includes(key)}
                placeholder='请搜索选择'
                showSearch
                filterOption={(input, option) => {
                  const txt = option!.label

                  return txt.toLowerCase().includes(input.toLowerCase())
                }}
                options={storageIdArr.map(v => ({ label: v.num + ' - ' + v.name, value: v.id }))}
                // fieldNames={{ label: 'num', value: 'num' }}
                allowClear={false}
                value={topInfo.storageId || null}
                onChange={e => {
                  if (topInfo.storageId && topInfo.storageId !== e && collectionList.length) {
                    setIsModalOpen(e)
                  } else setTopInfo({ ...topInfo, storageId: e ? e : null })
                }}
              />
            </div>
          </div>

          <div className='D4row'>
            <div className='D4rowll'>
              <span>*</span>盘点事由：
            </div>
            <div className='D4rowrr'>
              <Input
                value={topInfo.reason}
                onChange={e => setTopInfo({ ...topInfo, reason: e.target.value })}
                readOnly={['3', '4'].includes(key)}
                placeholder='请输入内容'
                maxLength={200}
                showCount
              />
            </div>
          </div>
        </div>

        {/* 盘点范围 */}
        <div className='D4googsBox'>
          <div className='D4Tit2'>
            <div className='D4Tit2ll'>盘点范围</div>
            {!['3', '4'].includes(key) && (
              <div>
                <Button
                  type='primary'
                  disabled={!collectionList.length}
                  style={{ marginRight: 15 }}
                  onClick={() => setBatchFillingVisible(true)}
                >
                  批量填写
                </Button>
                <Button
                  disabled={!topInfo.storageId}
                  type='primary'
                  onClick={() => setStocktakingVisible(true)}
                >
                  设置盘点范围
                </Button>
              </div>
            )}
          </div>

          <MyTable
            ref={tableRef}
            readOnly={['3', '4'].includes(key)}
            widthSet={{ statusCheck: 200, remark: 200 }}
            yHeight={350}
            list={collectionList}
            columnsTemp={D7CHECK_COLLECTION_COLUMNS}
            lastBtn={
              ['3', '4'].includes(key)
                ? undefined
                : [
                    {
                      title: '操作',
                      render(item: C1GoodType, _: any, idx: number) {
                        return (
                          <MyPopconfirm
                            txtK='删除'
                            onConfirm={() => {
                              if (item.id2 && !delSnapIdsRef.current.includes(item.id2))
                                delSnapIdsRef.current.push(item.id2)
                              const temp = [...collectionList]
                              temp.splice(idx, 1)
                              setCollectionList(temp)
                            }}
                          />
                        )
                      }
                    }
                  ]
            }
          />
        </div>

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

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

      {/* 分库缩写改变的时候校验一下 */}
      <Modal
        wrapClassName={styles.D6editMo}
        title='变更分库后，将清空当前的藏品清单'
        open={!!isModalOpen}
        footer={[]}
      >
        <div className='D6editMoBtn'>
          <Button
            type='primary'
            onClick={() => {
              setTopInfo({ ...topInfo, storageId: isModalOpen })

              collectionList.forEach(v => {
                if (!delSnapIdsRef.current.includes(v.id)) delSnapIdsRef.current.push(v.id)
              })
              setCollectionList([])
              setIsModalOpen(0)
            }}
          >
            继续
          </Button>
          &emsp;
          <Button onClick={() => setIsModalOpen(0)}>取消</Button>
        </div>
      </Modal>

      <BatchFillingModal
        visible={batchFillingVisible}
        setVisible={setBatchFillingVisible}
        onOk={handleBatchFillingOk}
      />

      <StocktakingModal
        storageId={topInfo.storageId}
        visible={stocktakingVisible}
        setVisible={setStocktakingVisible}
        onOk={handleStocktakingOk}
      />
    </div>
  )
}

const MemoD7edit = React.memo(D7edit)

export default MemoD7edit
