import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { useParams } from 'react-router-dom'
import {
  C2_APIaduit,
  C2_APIcreate,
  C2_APIgetInfo,
  C2_APIresubmit
} from '@/store/action/C2storageIn'
import { C2lookPageStaObj, locTxtChangeFu, locTxtValueFu } from '../data'
import { B1listType } from '@/pages/B1ledger/data'
import { Button, DatePicker, Input } from 'antd'
import { statusSelect } from '@/utils/select'
import history, { backPageFu, openLink } from '@/utils/history'
import MyPopconfirm from '@/components/MyPopconfirm'
import { MessageFu } from '@/utils/message'
import dayjs from 'dayjs'
import TextArea from 'antd/es/input/TextArea'
import Z3upFiles from '@/components/Z3upFiles'
import MyTable from '@/components/MyTable'
import { auditTableC, goodsSelectTableC } from '@/utils/tableData'
import A0selectGoods from '@/pages/A0selectGoods'
import { API_getGoodsInfo } from '@/store/action/B1ledger'
function C2look() {
  const { key, id } = useParams<any>()
  // key:1-新增 2-重新提交/编辑 3-查看 4-审批

  // 从藏品信息模块进来，带上当前藏品信息
  const isGoodsInfoRu = useCallback(async (id: number) => {
    const res = await API_getGoodsInfo(id)
    if (res.code === 0) {
      setSnaps([res.data])
    }
  }, [])

  useEffect(() => {
    const urlAll = window.location.href
    if (key === '1' && urlAll.includes('?oldId=')) {
      isGoodsInfoRu(Number(urlAll.split('?oldId=')[1]))
    }
  }, [isGoodsInfoRu, key])

  // 顶部数据
  const [info, setInfo] = useState({} as B1listType)

  // 新增的时候进页面创建订单
  const createFu = useCallback(async () => {
    const res = await C2_APIcreate()
    if (res.code === 0) {
      setInfo(res.data)
    }
  }, [])

  // 获取详情
  const getInfoFu = useCallback(async () => {
    const res = await C2_APIgetInfo(id)
    if (res.code === 0) {
      // console.log('获取详情：', res)
      const data = res.data
      setInfo(data)
      // 设置附件(需要异步)

      setTimeout(() => {
        filesRef.current?.showList(data.files || [])
      }, 100)

      // 藏品清单快照信息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') createFu()
    else if (['2', '3', '4'].includes(key)) getInfoFu()
  }, [createFu, getInfoFu, key])

  // 申请状态
  const topStatusRes = useMemo(() => {
    let txt = '创建订单'
    const obj = statusSelect.find(v => v.value === info.status)
    if (obj) txt = obj.label
    return txt
  }, [info.status])

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

  const boxRef = useRef<HTMLDivElement>(null)

  // 上传附件的ref
  const filesRef = useRef<any>(null)

  // 藏品清单 和 快照数据

  const [snaps, setSnaps] = useState<B1listType[]>([])
  const delSnapIdsRef = useRef<number[]>([])

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

  const goodsTableBtn = useMemo(() => {
    return [
      {
        title: '入库位置',
        render: (item: B1listType) => {
          return (
            <>
              {['柜号', '层数', '层格编号'].map((txt, index) => (
                <div key={index} className='C2TableTxt'>
                  <Input
                    readOnly={['3', '4'].includes(key)}
                    placeholder={['3', '4'].includes(key) ? '（空）' : `请输入${txt}`}
                    maxLength={10}
                    value={locTxtValueFu(index, item.siteIn)}
                    showCount
                    onChange={e =>
                      setSnaps(
                        snaps.map(v => ({
                          ...v,
                          siteIn:
                            v.id === item.id
                              ? locTxtChangeFu(index, e.target.value.trim(), item.siteIn)
                              : v.siteIn
                        }))
                      )
                    }
                  />
                </div>
              ))}
            </>
          )
        }
      },
      {
        title: '操作',
        render: (item: B1listType) => {
          return (
            <>
              <Button size='small' type='text' onClick={() => openLink(`/goodsLook/${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))
                  }}
                />
              )}
            </>
          )
        }
      }
    ]
  }, [key, snaps])

  // 点击提交
  const btnOk = useCallback(async () => {
    if (key === '4') {
      // 审批
      if (!auditSta) {
        MessageFu.warning('请选择审批结果')
        boxRef.current?.scrollTo({ top: 0, behavior: 'smooth' })
        return
      }

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

      if (res.code === 0) {
        MessageFu.success('审批成功')
        history.replace(`/storageIn_look/3/${info.id}`)
      }
    } else if (['1', '2'].includes(key)) {
      // 新增和重新提交

      // 处理日期格式
      if (!info.date) {
        MessageFu.warning('请选择入库日期')
        boxRef.current?.scrollTo({ top: 0, behavior: 'smooth' })
        return
      }

      if (!info.num) {
        MessageFu.warning('请输入入库单编号')
        boxRef.current?.scrollTo({ top: 0, behavior: 'smooth' })
        return
      }

      if (snaps.length === 0) return MessageFu.warning('请添加藏品')

      // 附件
      let fileIds = ''
      const fileArr: any[] = filesRef.current?.filesRes()
      if (fileArr && fileArr.length) fileIds = fileArr.map(v => v.id).join(',')

      const snapsRes = snaps.map(v => ({
        goodsId: v.id,
        id: v.id2 ? v.id2 : null,
        orderId: info.id,
        siteIn: v.siteIn,
        snap: JSON.stringify(v)
      }))

      const obj = {
        date: info.date,
        delSnapIds: delSnapIdsRef.current.length ? delSnapIdsRef.current : '',
        fileIds,
        goodIds: snaps.map(v => v.id).join(','),
        id: info.id,
        num: info.num,
        reason: info.reason,
        snaps: snapsRes
      }

      // if (1 + 1 === 2) {
      //   console.log(123, obj)
      //   return
      // }

      const res = await C2_APIresubmit(obj)

      if (res.code === 0) {
        MessageFu.success(key === '1' ? '创建订单成功' : '重新提交成功')
        history.replace(`/storageIn_look/3/${info.id}`)
      }
    }
  }, [auditSta, info, key, rtfOpinion, snaps])

  // 点击新增打开弹窗
  const [addShow, setAddShow] = useState(false)

  return (
    <div className={styles.C2look} ref={boxRef}>
      <div className='pageTitle'>藏品入库 - {Reflect.get(C2lookPageStaObj, key)}</div>

      {info.id ? (
        <>
          <div className='C2lTop'>
            <div className='C2lTopll'>
              <div className='C2lTit'>申请信息</div>
              <div className='C2lTopllBtn'>
                <Button type='dashed'>{topStatusRes}</Button>
              </div>
            </div>
            <div className='C2lToprr'>
              {key !== '3' ? (
                <>
                  <Button type='primary' onClick={btnOk}>
                    提交
                  </Button>
                  &emsp;
                </>
              ) : null}

              {['1', '2'].includes(key) ? (
                <MyPopconfirm txtK='返回' onConfirm={() => backPageFu('/storageIn')} />
              ) : (
                <Button onClick={() => backPageFu('/storageIn')}>返回</Button>
              )}
            </div>
          </div>

          <div className='C2form'>
            {['3', '4'].includes(key) ? (
              <>
                <div className='C2formRow'>
                  <div className='C2formRowll'>订单类型：</div>
                  <div className='C2formRowrr C2formRowrr2'>藏品入库</div>
                </div>

                <div className='C2formRow'>
                  <div className='C2formRowll'>发起人员：</div>
                  <div className='C2formRowrr C2formRowrr2'>
                    {info.creatorName + ' - ' + info.createTime}
                  </div>
                </div>
              </>
            ) : null}

            <div className='C2formRow'>
              <div className='C2formRowll'>
                <span>* </span>入库日期：
              </div>
              <div className='C2formRowrr'>
                <DatePicker
                  disabled={['3', '4'].includes(key)}
                  allowClear={false}
                  value={info.date ? dayjs(info.date) : null}
                  onChange={e => setInfo({ ...info, date: dayjs(e).format('YYYY-MM-DD') })}
                />
              </div>
            </div>

            <div className='C2formRow'>
              <div className='C2formRowll'>
                <span>* </span>入库单编号：
              </div>
              <div className='C2formRowrr'>
                <Input
                  value={info.num}
                  onChange={e => setInfo({ ...info, num: e.target.value.trim() })}
                  readOnly={['3', '4'].includes(key)}
                  placeholder='请输入内容'
                  maxLength={30}
                  showCount
                />
              </div>
            </div>

            <div className='C2formRow C2formRowAll'>
              <div className='C2formRowll'>事由说明：</div>
              <div className='C2formRowrr'>
                <TextArea
                  value={info.reason}
                  onChange={e => setInfo({ ...info, reason: e.target.value })}
                  readOnly={['3', '4'].includes(key)}
                  placeholder={['3', '4'].includes(key) ? '（空）' : '请输入内容'}
                  maxLength={1000}
                  showCount
                />
              </div>
            </div>

            {['3', '4'].includes(key) ? (
              <div style={{ width: '100%', height: '10px' }}></div>
            ) : null}

            <div className='C2formRow C2formRowAll'>
              <div className='C2formRowll'>附件：</div>
              <div className='C2formRowrr'>
                <Z3upFiles
                  size={500}
                  isLook={['3', '4'].includes(key)}
                  ref={filesRef}
                  fileCheck={false}
                  dirCode='storageIn_look'
                  myUrl='cms/orderSite/in/upload'
                />
              </div>
            </div>

            {/* 审批相关 */}
            {key === '4' ? (
              <>
                <div className='C2formRow C2formRowAll'>
                  <div className='C2formRowll'>
                    <span>* </span>审批结果：
                  </div>
                  <div className='C2formRowrr'>
                    {['同意', '不同意'].map(v => (
                      <Button
                        key={v}
                        onClick={() => setAuDitSta(v)}
                        type={auditSta === v ? 'primary' : 'default'}
                      >
                        {v}
                      </Button>
                    ))}
                  </div>
                </div>
                <div className='C2formRow C2formRowAll' style={{ marginBottom: 25 }}>
                  <div className='C2formRowll'>审批意见：</div>
                  <div className='C2formRowrr'>
                    <TextArea
                      value={rtfOpinion}
                      onChange={e => setRtfOpinion(e.target.value)}
                      placeholder='请输入内容'
                      maxLength={200}
                      showCount
                    />
                  </div>
                </div>
              </>
            ) : null}
          </div>

          <div className='C2lTit2'>
            <div className='C2lTit'>藏品清单</div>
            {['1', '2'].includes(key) ? (
              <Button type='primary' onClick={() => setAddShow(true)}>
                新增
              </Button>
            ) : (
              <div></div>
            )}
          </div>

          <MyTable
            list={snaps}
            columnsTemp={goodsSelectTableC}
            lastBtn={goodsTableBtn}
            pagingInfo={false}
          />

          {['3', '4'].includes(key) ? (
            <>
              <div className='C2lTit'>申请流程</div>

              <MyTable
                list={info.audits || []}
                columnsTemp={auditTableC}
                pagingInfo={false}
                widthSet={{ rtfOpinion: 600 }}
              />
            </>
          ) : null}
        </>
      ) : null}

      {/* 打开藏品选择弹窗 */}
      {addShow ? (
        <A0selectGoods
          type='入库'
          closeFu={() => setAddShow(false)}
          oldCheckArr={snaps}
          dataResFu={data => {
            //需要过滤掉已经有id的-不替换数据，没有id的替换数据 因为数据可能已经在另外一个弹窗更新了
            const nowIds = snaps.map(v => v.id)
            let dataRes = data.map((v, i) => {
              if (nowIds.includes(v.id)) return snaps[i]
              else return v
            })

            dataRes.forEach(v => {
              // id2表示的是自己这条数据的id id才是goodsId
              const obj = snapsID2ref.current.find(c => c.goodsId === v.id)

              if (obj) v.id2 = obj.id
            })

            setSnaps(dataRes)
          }}
        />
      ) : null}
    </div>
  )
}

const MemoC2look = React.memo(C2look)

export default MemoC2look
