import React, { useCallback, useEffect, useMemo, useState } from 'react'
import styles from './index.module.scss'
import { Button } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import history, { backPageFu } from '@/utils/history'
import { useParams } from 'react-router-dom'
import { editBtnShowFu, editPageToTopFu, pageSkitFu } from '@/utils/authority'
import { useInfo } from '../InfoContext'
import { MessageFu } from '@/utils/message'
import { fileIdsResFu } from '@/utils'
import { API_objType } from '@/store/action/Dmanage/D1register'
import AuditList from '../AuditList'
import { GoodsType } from '../SonGoodsList/data'
import { Typetable } from '../data'

type Props = {
  path: string
  APIobj: API_objType
  // 是否至少需要添加一条数据，不需要校验的话不传
  checkListTxt?: string
  // 需要校验的字段和提示
  verifyArr?: { key: string; txt: string }[]
  // 其他需要校验的回调函数,返回 flag为true 表示校验不通过，txt为提示语
  verifyBackFu?: (info: Typetable) => { flag: boolean; txt: string; info?: any }
  // 页面特有数据，如 storageId，会合并到提交的 obj 中
  getExtraData?: (info: Typetable, snaps: GoodsType[]) => Record<string, any>
  // 第二个模块
  isTow?: boolean
  // 藏品修改模块
  isEdit?: boolean
}

function EditBtn({
  path,
  APIobj,
  checkListTxt = '',
  verifyArr = [{ key: 'num', txt: '请输入申请编号' }],
  verifyBackFu,
  getExtraData,
  isTow,
  isEdit
}: Props) {
  const { info, info2, snaps, setTimeKeyFu, auditInfo, editObj } = useInfo()

  const [btnCan, setBtnCan] = useState({ status: 0, creatorId: 0 })

  useEffect(() => {
    setBtnCan({ status: info.status, creatorId: info.creatorId })
  }, [info.status, info.creatorId])

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

  const isLook = useMemo(() => {
    return ['3', '4'].includes(key)
  }, [key])

  const [btnPowArr, setBtnPowArr] = useState<string[]>([])

  useEffect(() => {
    if (btnCan.creatorId) {
      const arr = editBtnShowFu(btnCan.status, btnCan.creatorId)
      setBtnPowArr(arr)
    }
  }, [btnCan])

  //   藏品数量不能为空判断 、藏品登记号为空 和重复的判断
  const numFlag = (data: GoodsType[]) => {
    const numSet = new Set<string>()

    for (const item of data) {
      // 检查是否为空
      if (!item.num || item.num.trim() === '') {
        return `${item.name} - 藏品登记号不能为空`
      }

      if (!item.pcs || !item.pcsUnitDictId) {
        return `${item.name} - 藏品数量不能为空`
      }

      // 检查是否重复
      if (numSet.has(item.num)) {
        const duplicateNames = data.filter(d => d.num === item.num).map(d => d.name)
        return `${duplicateNames.join(' / ')} - 藏品登记号重复`
      }

      numSet.add(item.num)
    }

    return null
  }

  // 点击按钮触发事件
  const sonClick = useCallback(
    async (val: string, flag?: string) => {
      // console.log('点击按钮', val, flag)
      // 新增、编辑、审批、查看互相跳转
      if (flag) pageSkitFu(path, val, info.id, flag)
      else {
        const goodIdArr: number[] = []
        const collectIdArr: number[] = []
        const snapsArr: any[] = []

        snaps.forEach((v, i) => {
          // 从征集中选的藏品--并且没有在点编辑（点提交）存到藏品数据库。这时候就属于征集id
          const flag = v.pageType === 'clue' && !v.clueId

          if (flag) collectIdArr.push(v.id)
          else goodIdArr.push(v.id)

          let snapSon: any = {
            ...v,
            id: v.isNew || flag ? null : v.id
          }
          // console.log('----------', snapSon)

          // 只有一个藏品的第二个模块
          if (isTow && i === 0) {
            const info2Res: any = info2

            snapSon = {
              id: snapSon.id,
              idTemp: snapSon.idTemp,
              name: snapSon.name,
              num: snapSon.num,
              thumbPc: snapSon.thumbPc,
              ...info2Res
            }
            if (info.files2 && info.files2.length) {
              snapSon.fileIds2 = info.files2.map(v => v.id).join(',')
            }
          }

          // 藏品修改模块----------
          if (isEdit && i === 0) {
            snapSon = editObj
          }

          // console.log('xxxxxxxx', snapSon)

          snapsArr.push({
            goodId: v.isNew || flag ? null : v.id,
            orderId: info.id,
            snap: JSON.stringify(snapSon)
          })
        })

        // 没有选择关联藏品的时候，只存下面的字段
        if (snaps.length === 0) {
          let snapSon: any = {}
          snapSon = {
            ...info2
          }
          if (info.files2 && info.files2.length) {
            snapSon.fileIds2 = info.files2.map(v => v.id).join(',')
          }

          snapsArr.push({
            orderId: info.id,
            snap: JSON.stringify(snapSon)
          })
        }

        let obj = {
          ...info,
          fileIds: fileIdsResFu(info.files),
          goodIds: goodIdArr.join(','),
          collectIds: collectIdArr.join(','),
          snaps: snapsArr
        }

        if (getExtraData) {
          const extra = getExtraData(info, snaps)
          if (extra) {
            const { snaps, ...rest } = extra
            obj = { ...obj, ...rest } as typeof obj
            if (snaps) obj = { ...obj, snaps: snaps } as typeof obj
          }
        }

        // if (1 + 1 === 2) {
        //   // console.log('--------', obj)

        //   console.log('xxxxxxxxx', JSON.parse(obj.snaps[0].snap))
        //   return
        // }

        // 草稿、发起、审批、撤回、删除

        if (val === '草稿') {
          const res = await APIobj['草稿'](obj)
          if (res.code === 0) {
            pageSkitFu(path, '4', info.id, '详情', '保存草稿成功')
          }
        } else if (val === '撤回') {
          const res = await APIobj['撤回'](obj.id)
          if (res.code === 0) {
            MessageFu.success('撤回成功')
            // 重新调用获取详情接口-当前页刷新状态
            setTimeKeyFu()
          }
        } else if (val === '删除') {
          const res = await APIobj['删除'](obj.id)
          if (res.code === 0) {
            MessageFu.success('删除成功')
            // 回到列表页面
            history.replace(path)
          }
        } else if (val === '发起') {
          let txt = ''
          if (isLook) txt = '，已为您跳转到编辑页面'

          // 校验字段
          let verifyFlag = false
          verifyArr.forEach(cc => {
            if (!info[cc.key as 'num']) {
              verifyFlag = true
              if (isLook) history.replace(`${path}_edit/2/${info.id}`)
              MessageFu.warning(cc.txt + txt)
              return
            }
          })

          if (verifyFlag) return

          // 是否至少需要添加一条数据
          if (checkListTxt) {
            if (snaps.length === 0) {
              if (isLook) history.replace(`${path}_edit/2/${info.id}`)

              MessageFu.warning(checkListTxt + txt)
              return
            } else if (['/register', '/enterGuan'].includes(path)) {
              // 藏品登记/藏品入馆，需要校验 藏品登记号 为空 或者 重复

              // console.log('-----', snaps, obj)
              const flag = numFlag(snaps)

              if (flag) {
                MessageFu.warning(flag + txt)
                if (isLook) history.replace(`${path}_edit/2/${info.id}`)
                return
              }
            }
          }

          // 其他自己制定的校验函数
          if (verifyBackFu) {
            const flagObj = verifyBackFu(info2)
            if (flagObj.flag) {
              if (isLook) history.replace(`${path}_edit/2/${info.id}`)
              MessageFu.warning(flagObj.txt + txt)
              return
            }
            // // 如果需要传递数据
            // if (flagObj.info) {
            //   // 自己把数据加到obj里面 给后端
            // }
          }

          // console.log('xxxxxx', obj)
          // return

          const res = await APIobj['发起'](obj)
          if (res.code === 0) {
            if (['1', '2'].includes(key)) {
              pageSkitFu(path, '4', info.id, '详情', '提交成功')
            } else {
              MessageFu.success('发起成功')
              // 重新调用获取详情接口-当前页刷新状态
              setTimeKeyFu()
            }
          }
        } else if (val === '重新发起') {
          const res = await APIobj['重新发起'](obj.id)
          if (res.code === 0) {
            MessageFu.success('重新发起成功')
            // 重新调用获取详情接口-当前页刷新状态
            setTimeKeyFu()
          }
        } else if (val === '审批') {
          if (!auditInfo.status) {
            editPageToTopFu()
            return MessageFu.warning('请选择审批结果')
          } else {
            const auditObj = {
              ...auditInfo,
              orderId: info.id
            }
            const res = await APIobj['审批'](auditObj)
            if (res.code === 0) {
              pageSkitFu(path, '4', info.id, '详情', '审批成功')
            }
          }
        }
      }
    },
    [
      APIobj,
      auditInfo,
      checkListTxt,
      editObj,
      getExtraData,
      info,
      info2,
      isEdit,
      isLook,
      isTow,
      key,
      path,
      setTimeKeyFu,
      snaps,
      verifyArr,
      verifyBackFu
    ]
  )

  // 申请记录的显示
  const [auditListShow, setAuditListShow] = useState(false)

  return (
    <div className={styles.EditBtn}>
      <div>
        {['1', '2'].includes(key) ? (
          <>
            <Button type='primary' onClick={() => sonClick('草稿')}>
              存草稿
            </Button>
            <Button type='primary' onClick={() => sonClick('发起')}>
              提交
            </Button>
            <MyPopconfirm txtK='取消' onConfirm={() => backPageFu(path)} />
          </>
        ) : key === '3' ? (
          <Button type='primary' onClick={() => sonClick('审批')}>
            审批
          </Button>
        ) : key === '4' ? (
          <>
            {btnPowArr.includes('重新发起') ? (
              <Button type='primary' onClick={() => sonClick('重新发起')}>
                重新发起
              </Button>
            ) : null}
            {btnPowArr.includes('撤回') ? (
              <MyPopconfirm
                txtK='撤回'
                onConfirm={() => sonClick('撤回')}
                Dom={<Button danger>撤回</Button>}
              />
            ) : null}
            {btnPowArr.includes('编辑') ? (
              <Button type='primary' onClick={() => sonClick('2', '编辑')}>
                编辑
              </Button>
            ) : null}
            {btnPowArr.includes('发起') ? (
              <Button type='primary' onClick={() => sonClick('发起')}>
                发起
              </Button>
            ) : null}
            {btnPowArr.includes('删除') ? (
              <MyPopconfirm
                txtK='删除2'
                onConfirm={() => sonClick('删除')}
                Dom={<Button danger>删除</Button>}
              />
            ) : null}
          </>
        ) : null}

        {isLook ? <Button onClick={() => backPageFu(path)}>返回</Button> : null}
      </div>

      <div>
        {isLook && info.audits && info.audits.length ? (
          <Button onClick={() => setAuditListShow(true)}>申请记录</Button>
        ) : null}
      </div>

      {auditListShow ? (
        <AuditList list={info.audits} closeFu={() => setAuditListShow(false)} />
      ) : null}
    </div>
  )
}

const MemoEditBtn = React.memo(EditBtn)

export default MemoEditBtn
