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, Select, Tabs } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import history, { btnFlagFu2, infoPageBackFu } 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 from '@/components/MyTable'
import { EXbtnFu } from '@/utils/EXBtn'
import {
  D3_APIcreate,
  D3_APIdel,
  D3_APIgetInfo,
  D3_APIrevocation,
  D3_APIsaveApply,
  D3_APIsaveAudit,
  D3_APIsaveCreate,
  D3_APIsaveDraft
} from '@/store/action/D3staff'
import { D3StaffOversiderType, ID3StaffItem, SON_TYPE_NAME } from '../types'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '@/store'
import { OutsiderModal } from '../components/OutsiderModal'
import { D3STAFF_OUTSIDER_TABLE_COLUMNS } from '../constants'
import { D2_APIgetList } from '@/store/action/D2storSet'
import dayjs from 'dayjs'
import { EXPORT_WORD_ENUM } from '@/utils/exportTemplates'
import encodeStr, { decodeStr } from '@/utils/pass'

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

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

  // 滚到顶部
  const sollrDom = useRef<HTMLDivElement>(null)
  // 顶部数据
  const [topInfo, setTopInfo] = useState({} as ID3StaffItem)
  const storeList = useSelector((state: RootState) => state.D2storSet.tableInfo.list)
  const [outsiderVisible, setOutsiderVisible] = useState(false)
  const [oversiderList, setOversiderList] = useState<D3StaffOversiderType[]>([])
  const { list: storageIdArr } = useSelector((state: RootState) => state.D2storSet.tableInfo)
  const pageDisabled = ['3', '4'].includes(key)
  const [checkedOversider, setCheckedOversider] = useState<null | D3StaffOversiderType>(null)
  const [curTab, setCurTab] = useState(SON_TYPE_NAME.OUT)

  const dispatch = useDispatch()

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

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

  // 获取详情
  const getInfoFu = useCallback(
    async (id2?: number) => {
      try {
        const res = await D3_APIgetInfo(id2 || id)
        if (res.code === 0) {
          const { memberIds, sonTypeName } = res.data
          setTopInfo(res.data)
          setCurTab(sonTypeName)
          setOversiderList(JSON.parse(decodeURIComponent(decodeStr(memberIds || ''))) || [])
        }
      } catch (err) {
        console.log(err)
      }
    },
    [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.reason) {
      MessageFu.warning('请输入入库事由')
      return true
    }

    return false
  }, [topInfo])

  const curStore = useMemo(() => {
    return storeList.find(i => i.id === topInfo.storageId)
  }, [storeList, topInfo])

  // 审批的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 D3_APIsaveAudit({
          orderId: topInfo.id,
          rtfOpinion: rtf2,
          status: auditSta === '同意' ? 1 : 2
        })

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

        const obj = {
          ...topInfo,
          rtf: JSON.stringify(rtf1.val || ''),
          memberIds: encodeStr(encodeURIComponent(JSON.stringify(oversiderList))),
          sonTypeName: curTab
        }
        // console.log(123, obj)

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

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

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

      const obj = {
        ...topInfo,
        rtf: JSON.stringify(rtf1.val || '')
      }

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

  // 查看模式点击审批 编辑
  const lookJumpFu = useCallback(
    (val: '审批' | '编辑') => {
      history.push(`/staff_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, [
          curTab === SON_TYPE_NAME.IN
            ? EXPORT_WORD_ENUM.INSIDER_FORM
            : EXPORT_WORD_ENUM.OUTSIDER_FORM
        ])}

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

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

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

  return (
    <div className={styles.D3staff}>
      <div className='pageTitle'>人员出入库-{pageTitTxt}</div>

      <div className='D4main' ref={sollrDom}>
        {['3'].includes(key) ? (
          <X3auditInfo
            dirCode='D4wealth'
            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 className='D4row'>
            <div className='D4rowll'>
              <span>*</span>入库时间：
            </div>
            <div className='D4rowrr'>
              <DatePicker
                showTime
                disabled={pageDisabled}
                defaultValue={dayjs(topInfo.date)}
                style={{ width: '300px' }}
                onChange={e => {
                  setTopInfo({ ...topInfo, date: e.format('YYYY-MM-DD HH:mm:ss') })
                }}
              />
            </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={pageDisabled}
                placeholder='请输入内容'
                maxLength={200}
                showCount
              />
            </div>
          </div>
        </div>

        {/* 库房信息 */}
        <div className='D4googsBox'>
          <div className='D4Tit2'>
            <div className='D4Tit2ll'>库房信息</div>
          </div>
        </div>
        <div className='D4rowAll'>
          <div className='D4row'>
            <div className='D4rowll'>库别名称：</div>
            <div className='D4rowrr'>
              <Select
                disabled={pageDisabled}
                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 => {
                  setTopInfo({ ...topInfo, storageId: e ? e : null })
                }}
              />
            </div>
          </div>
          <div className='D4row'>
            <div className='D4rowll'>库房负责人：</div>
            <div className='D4rowrr'>{curStore?.managerUser || '--'}</div>
          </div>
        </div>

        {/* 人员信息 */}
        <div className='D4googsBox'>
          <div className='D4Tit2'>
            <div className='D4Tit2ll'>人员信息</div>
          </div>

          <Tabs
            type='card'
            activeKey={curTab}
            items={[
              {
                key: SON_TYPE_NAME.OUT,
                label: '外部人员',
                disabled: pageDisabled,
                children: (
                  <>
                    <div className={styles.tabRow}>
                      <Input
                        readOnly={pageDisabled}
                        value={topInfo.authUser}
                        addonBefore='陪同人员'
                        placeholder='请填入姓名，以逗号分隔'
                        style={{ width: 500 }}
                        allowClear
                        onChange={e => setTopInfo({ ...topInfo, authUser: e.target.value })}
                      />

                      {!pageDisabled && (
                        <Button type='primary' onClick={() => setOutsiderVisible(true)}>
                          新增
                        </Button>
                      )}
                    </div>
                    <MyTable
                      readOnly={pageDisabled}
                      rowKey='name'
                      yHeight={200}
                      list={oversiderList}
                      pagination={false}
                      columnsTemp={D3STAFF_OUTSIDER_TABLE_COLUMNS}
                      lastBtn={
                        pageDisabled
                          ? undefined
                          : [
                              {
                                title: '操作',
                                render(item: D3StaffOversiderType, _: any, index: number) {
                                  return (
                                    <>
                                      <Button
                                        size='small'
                                        type='text'
                                        onClick={() => {
                                          setCheckedOversider(item)
                                          setOutsiderVisible(true)
                                        }}
                                      >
                                        编辑
                                      </Button>
                                      <MyPopconfirm
                                        txtK='删除'
                                        onConfirm={() => {
                                          const temp = [...oversiderList]
                                          temp.splice(index, 1)
                                          setOversiderList(temp)
                                        }}
                                      />
                                    </>
                                  )
                                }
                              }
                            ]
                      }
                    />
                  </>
                )
              },
              {
                key: SON_TYPE_NAME.IN,
                label: '内部人员',
                disabled: pageDisabled,
                children: (
                  <>
                    <div className={styles.tabRow}>
                      <Input
                        readOnly={pageDisabled}
                        value={topInfo.authUser}
                        addonBefore='进库人员'
                        placeholder='请填入姓名，以逗号分隔'
                        style={{ width: 500 }}
                        allowClear
                        onChange={e => setTopInfo({ ...topInfo, authUser: e.target.value })}
                      />
                    </div>
                  </>
                )
              }
            ]}
            onChange={e => setCurTab(e as SON_TYPE_NAME)}
          />
        </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('/staff')} />
          </>
        )}
      </div>

      {/* 添加外部人员 */}
      <OutsiderModal
        item={checkedOversider}
        visible={outsiderVisible}
        setVisible={setOutsiderVisible}
        onOk={item => setOversiderList([...oversiderList, item])}
        onCancel={() => {
          setCheckedOversider(null)
        }}
      />
    </div>
  )
}

const MemoC21edit = React.memo(C21edit)

export default MemoC21edit
