import React, { useCallback, useEffect, useRef } from 'react'
import styles from './index.module.scss'
import { Button, DatePicker, Form, FormInstance, Input, InputNumber, Modal, Select } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import {
  dictSelect,
  isNoteSelect,
  levelSelect,
  qualitySelect,
  sizeSelect,
  tornSelect
} from '@/utils/select'
import TextArea from 'antd/es/input/TextArea'
import ZupOne from '@/components/ZupOne'
import Z3upFiles from '@/components/Z3upFiles'
import dayjs from 'dayjs'
import { API_addGoods, API_getFileListByIds, API_getGoodsInfo } from '@/store/action/B1ledger'
import { MessageFu } from '@/utils/message'
import history from '@/utils/history'
import { B2_APIresubmit } from '@/store/action/B2register'
import { B3_APIcreate, B3_APIgetInfo, B3_APIresubmit } from '@/store/action/B3edit'
import { B1listType } from '../B1ledger/data'
import { timeChange } from '@/utils/deriveFu'

type Props = {
  sId: number
  closeFu: () => void
  orderId?: number //外层订单id
  isEdit?: boolean //藏品修改模块
  isEditresubmit?: Boolean //藏品修改模块重新提交
}

function A0addGoods({ sId, closeFu, isEdit, orderId, isEditresubmit }: Props) {
  const oldObjRef = useRef({} as B1listType)

  // 设置表单ref
  const FormBoxRef = useRef<FormInstance>(null)

  // 封面图的ref
  const ZupThumbRef = useRef<any>(null)

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

  const getInfoFu = useCallback(
    async (id: number) => {
      const res = await API_getGoodsInfo(id)

      if (res.code === 0) {
        const info = { ...res.data }

        ;['level', 'torn', 'qualityUnit', 'isNote', 'sizeUnit'].forEach(v => {
          if (!info[v]) info[v] = null
        })

        // 把旧的数据存起来(2个日期得单独处理一下)
        if (isEdit || isEditresubmit)
          oldObjRef.current = {
            ...res.data,
            inHouseTime: timeChange(res.data.inHouseTime),
            registerTime: timeChange(res.data.registerTime),
            file: res.data.file || []
          }

        // 设置封面图
        ZupThumbRef.current?.setFileComFileFu({
          fileName: '',
          filePath: info.thumbPc,
          thumb: info.thumb
        })
        // 设置附件
        filesRef.current?.showList(info.file)
        // inHouseTime registerTime 2个日期需要格式处理一下
        if (info.inHouseTime) info.inHouseTime = dayjs(info.inHouseTime)
        if (info.registerTime) info.registerTime = dayjs(info.registerTime)

        // 从藏品修改的 重新提交进入，应该把需改之后的信息带入表单
        if (isEditresubmit && orderId) {
          const resR = await B3_APIgetInfo(orderId)

          if (resR.code === 0) {
            // 拿到快照新数据
            const goodsArr = resR.data.snaps
            if (goodsArr && goodsArr[0] && goodsArr[0].snap) {
              const objStr = goodsArr[0].snap
              try {
                const obj: any = JSON.parse(objStr)
                ;['level', 'torn', 'qualityUnit', 'isNote', 'sizeUnit'].forEach(v => {
                  if (!obj[v]) obj[v] = null
                })
                // inHouseTime registerTime 2个日期需要格式处理一下
                if (obj.inHouseTime) obj.inHouseTime = dayjs(obj.inHouseTime)
                if (obj.registerTime) obj.registerTime = dayjs(obj.registerTime)

                FormBoxRef.current?.setFieldsValue(obj)

                // 设置封面图
                ZupThumbRef.current?.setFileComFileFu({
                  fileName: '',
                  filePath: obj.thumbPc,
                  thumb: obj.thumb
                })

                if (obj.fileIds) {
                  const fileArr = obj.fileIds.split(',').map((v: any) => Number(v))

                  const resFlie = await API_getFileListByIds(fileArr)

                  if (resFlie.code === 0) {
                    filesRef.current?.showList(resFlie.data || [])
                  }
                }
              } catch (error) {
                MessageFu.warning('JSON数据错误')
              }
            }
          }
        } else FormBoxRef.current?.setFieldsValue(info)
      }
    },
    [isEdit, isEditresubmit, orderId]
  )

  useEffect(() => {
    if (sId > 0) getInfoFu(sId)
  }, [getInfoFu, sId])

  // 没有通过校验
  const onFinishFailed = useCallback(async () => {
    // return MessageFu.warning("有表单不符号规则!");
  }, [])

  // 通过校验点击确定
  const onFinish = useCallback(
    async (values: any) => {
      // 封面图
      const coverUrl1 = ZupThumbRef.current?.fileComFileResFu()

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

      // 2个日期的格式处理
      let inHouseTime = ''
      if (values.inHouseTime) inHouseTime = dayjs(values.inHouseTime).format('YYYY-MM-DD')
      let registerTime = ''
      if (values.registerTime) registerTime = dayjs(values.registerTime).format('YYYY-MM-DD')

      const obj = {
        ...values,
        id: sId > 0 ? sId : null,
        inHouseTime,
        registerTime,
        fileIds,
        thumb: coverUrl1.thumb || '',
        thumbPc: coverUrl1.filePath || ''
      }

      for (const k in obj) {
        if (obj[k] === null || obj[k] === undefined) obj[k] = ''
      }

      // 藏品修改模块，先对比数据有没有改变，把旧数据存起来
      if (isEdit || isEditresubmit) {
        let flag = true

        // fileIds 要特别处理

        const fileOld = (oldObjRef.current.file || []).map((v: any) => v.id).join(',')

        if (fileIds !== fileOld) flag = false

        // console.log(fileNew, fileOld)

        for (const k in obj) {
          if (!['fileIds', 'file'].includes(k)) {
            if (obj[k] && oldObjRef.current[k as 'num'] !== obj[k]) {
              flag = false
            }
          }
        }

        if (flag) return MessageFu.warning('未修改藏品信息')

        obj.oldGoods = JSON.stringify(oldObjRef.current)
      }

      if (isEdit) {
        // 藏品修改模块新增
        const res = await B3_APIcreate(obj)
        if (res.code === 0) {
          MessageFu.success('藏品修改提交成功')
          history.push(`/edit_look/1/${res.data.id}`)
        }
      } else if (sId > 0) {
        // 藏品修改/藏品登记页面点击重新提交
        const res = isEditresubmit
          ? await B3_APIresubmit(orderId!, obj)
          : await B2_APIresubmit(orderId!, obj)
        if (res.code === 0) {
          MessageFu.success('重新提交成功')
          history.push(`/${isEditresubmit ? 'edit' : 'register'}_look/1/${res.data.id}`)
        }
      } else {
        // 藏品登记新增
        const res = await API_addGoods(obj)
        if (res.code === 0) {
          MessageFu.success('登记成功')
          history.push(`/register_look/1/${res.data.id}`)
        }
      }
    },
    [isEdit, isEditresubmit, orderId, sId]
  )

  return (
    <Modal
      wrapClassName={styles.A0addGoods}
      open={true}
      title={isEdit ? '藏品修改' : sId > 0 ? '藏品重新提交' : '藏品登记'}
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className='AGmain'>
        <Form
          scrollToFirstError={true}
          ref={FormBoxRef}
          name='basic'
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete='off'
        >
          <div className='AGbox'>
            <div className='AGrow'>
              <Form.Item
                label='藏品编号'
                name='num'
                getValueFromEvent={e => e.target.value.replace(/\s+/g, '')}
                rules={[{ required: true, message: '请输入藏品编号' }]}
              >
                <Input maxLength={20} showCount placeholder='请输入内容' />
              </Form.Item>
            </div>
            <div className='AGrow'>
              <Form.Item
                label='原编号'
                name='formerNum'
                getValueFromEvent={e => e.target.value.replace(/\s+/g, '')}
              >
                <Input maxLength={20} showCount placeholder='请输入内容' />
              </Form.Item>
            </div>

            <div className='AGrowAll'>
              <Form.Item
                label='藏品标题'
                name='name'
                getValueFromEvent={e => e.target.value.trim()}
                rules={[{ required: true, message: '请输入藏品标题' }]}
              >
                <Input maxLength={50} showCount placeholder='请输入内容' />
              </Form.Item>
            </div>

            <div className='AGrow'>
              <Form.Item label='入馆日期' name='inHouseTime'>
                <DatePicker />
              </Form.Item>
            </div>

            <div className='AGrow'>
              <Form.Item label='登记日期' name='registerTime'>
                <DatePicker />
              </Form.Item>
            </div>

            <div className='AGrow'>
              <Form.Item label='来源类型' name='sourceDictId'>
                <Select allowClear placeholder='请选择' options={dictSelect('藏品来源')} />
              </Form.Item>
            </div>

            <div className='AGrow'>
              <Form.Item label='来源详情' name='sourceInfo'>
                <Input maxLength={20} showCount placeholder='请输入内容' />
              </Form.Item>
            </div>

            <div className='AGrowAll'>
              <Form.Item label='藏品简介' name='intro'>
                <TextArea maxLength={500} showCount placeholder='请输入内容' />
              </Form.Item>
            </div>

            <div className='AGrow'>
              <Form.Item label='年代' name='ageDictId'>
                <Select allowClear placeholder='请选择' options={dictSelect('藏品年代')} />
              </Form.Item>
            </div>
            <div className='AGrow'>
              <Form.Item label='类型' name='typeDictId'>
                <Select allowClear placeholder='请选择' options={dictSelect('藏品类型')} />
              </Form.Item>
            </div>
            <div className='AGrow'>
              <Form.Item label='级别' name='level'>
                <Select allowClear placeholder='请选择' options={levelSelect} />
              </Form.Item>
            </div>
            <div className='AGrow'>
              <Form.Item label='材质' name='textureDictId'>
                <Select allowClear placeholder='请选择' options={dictSelect('藏品材质')} />
              </Form.Item>
            </div>

            <div className='AGrow'>
              <Form.Item label='完残程度' name='torn'>
                <Select allowClear placeholder='请选择' options={tornSelect} />
              </Form.Item>
            </div>

            <div className='AGrow AGrowFen'>
              <Form.Item label='数量' name='pcs'>
                <InputNumber min={1} max={99999} precision={0} placeholder='请输入正整数' />
              </Form.Item>

              <Form.Item name='pcsUnitDictId'>
                <Select allowClear placeholder='请选择单位' options={dictSelect('数量单位')} />
              </Form.Item>
            </div>

            <div className='AGrow AGrowFen'>
              <Form.Item label='重量' name='quality'>
                <InputNumber min={1} max={99999} placeholder='请输入数字' />
              </Form.Item>

              <Form.Item name='qualityUnit'>
                <Select allowClear placeholder='请选择单位' options={qualitySelect} />
              </Form.Item>
            </div>

            <div className='AGrow'>
              <Form.Item label='有无说明牌' name='isNote'>
                <Select allowClear placeholder='请选择' options={isNoteSelect} />
              </Form.Item>
            </div>

            <div className='AGrowAll'>
              <div className='AGsizeBox'>
                <div className='formLeft'>尺寸：</div>
                <div className='formRight'>
                  <Form.Item label='通长' name='sizeL'>
                    <InputNumber min={0} max={99999} placeholder='请输入数字' />
                  </Form.Item>

                  <Form.Item label='通宽' name='sizeW'>
                    <InputNumber min={0} max={99999} placeholder='请输入数字' />
                  </Form.Item>
                  <Form.Item label='通高' name='sizeH'>
                    <InputNumber min={0} max={99999} placeholder='请输入数字' />
                  </Form.Item>

                  <Form.Item name='sizeUnit'>
                    <Select allowClear placeholder='请选择' options={sizeSelect} />
                  </Form.Item>
                </div>
              </div>
            </div>

            <div className='AGrowAll'>
              <Form.Item label='备注' name='remark'>
                <TextArea maxLength={500} showCount placeholder='请输入内容' />
              </Form.Item>
            </div>

            <div className='AGrow'>
              <div className='AGsizeBox'>
                <div className='formLeft'>附件：</div>
                <div className='formRight'>
                  <Z3upFiles
                    size={500}
                    isLook={false}
                    ref={filesRef}
                    fileCheck={false}
                    dirCode='goodsAdd'
                    myUrl='cms/order/register/upload'
                  />
                </div>
              </div>
            </div>

            <div className='AGrow'>
              <div className='AGsizeBox'>
                <div className='formLeft'>封面图：</div>
                <div className='formRight'>
                  <ZupOne
                    ref={ZupThumbRef}
                    isLook={false}
                    fileCheck={false}
                    dirCode='goodsAdd'
                    myUrl='cms/order/register/upload'
                    format={['image/jpeg', 'image/png']}
                    formatTxt='png、jpg和jpeg'
                    checkTxt='请上传封面图!'
                    upTxt='最多1张'
                    myType='thumb'
                    size={5}
                  />
                </div>
              </div>
            </div>
          </div>

          {/* 确定和取消按钮 */}
          <br />
          <Form.Item wrapperCol={{ offset: 11, span: 16 }}>
            <Button type='primary' htmlType='submit'>
              提交
            </Button>
            &emsp;
            <MyPopconfirm txtK='取消' onConfirm={closeFu} />
          </Form.Item>
        </Form>
      </div>
    </Modal>
  )
}

const MemoA0addGoods = React.memo(A0addGoods)

export default MemoA0addGoods
