import React, { useCallback, useEffect, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, Cascader, Form, FormInstance, Input, InputNumber, Modal } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import TextArea from 'antd/es/input/TextArea'
import Z3upFiles from '@/components/Z3upFiles'
import { B1X_APIgetInfo, B1X_APIsave } from '@/store/action/B1collect'
import { MessageFu } from '@/utils/message'
import { cascaderObjFu } from '@/utils/history'
import ZupTypes from '@/components/ZupTypes'
import { B1Xtype } from '../../data'
import { cascaderChArr } from '@/pages/C_goodsManage/C1register/AddGoods'

type Props = {
  sId: number
  closeFu: () => void
  succFu: (val: B1Xtype, txt: '新增' | '编辑') => void
  look?: boolean
}

function B1MoAdd({ sId, closeFu, succFu, look = false }: Props) {
  const [file, setFile] = useState([])

  const getInfoFu = useCallback(async (id: number) => {
    const res = await B1X_APIgetInfo(id)
    if (res.code === 0) {
      const obj: any = { ...res.data }
      cascaderChArr.forEach(v => {
        if (obj[v]) obj[v] = obj[v].split(',')
      })
      FormBoxRef.current?.setFieldsValue({
        ...obj
      })

      // 设置附件
      setFile(obj.file || [])

      // 设置图片
      imgRef.current?.setFileComFileFu({
        type: 'img',
        fileList: obj.img || []
      })
    }
  }, [])

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

  // 设置表单初始数据（区分编辑和新增）
  const FormBoxRef = useRef<FormInstance>(null)

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

  // 通过校验点击确定
  const onFinish = useCallback(
    async (values: any) => {
      // 上传附件
      const filesRes = filesRef.current.filesIdRes()

      // 上传图片
      const { sonFileIds, coverUrl, coverPcUrl } = imgRef.current?.fileComFileResFu()

      const obj = {
        ...values,
        fileIds: filesRes.join(','),
        id: sId > 0 ? sId : null,
        imgIds: sonFileIds.join(','),
        thumb: coverUrl,
        thumbPc: coverPcUrl
      }

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

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

      // 级联的数据转换成字符串
      cascaderChArr.forEach(v => {
        if (values[v]) obj[v] = values[v].join(',')
      })

      const res = await B1X_APIsave(obj)

      if (res.code === 0) {
        MessageFu.success(sId > 0 ? '编辑成功' : '新增成功')
        succFu(res.data, sId > 0 ? '编辑' : '新增')
        closeFu()
      }
    },
    [closeFu, sId, succFu]
  )

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

  // 上传图片的ref
  const imgRef = useRef<any>(null)

  return (
    <Modal
      wrapClassName={styles.B1MoAdd}
      destroyOnClose
      open={true}
      title={look ? '查看' : sId > 0 ? '编辑' : '新增'}
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className='B1Mmain'>
        <Form
          scrollToFirstError={true}
          ref={FormBoxRef}
          name='basic'
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete='off'
        >
          <div className='B1MformBox'>
            <Form.Item label='名称' name='name' rules={[{ required: true, message: '请输入名称' }]}>
              <Input readOnly={look} maxLength={30} showCount placeholder='请输入内容' />
            </Form.Item>

            <Form.Item label='初定年代' name='dictAgeFirst'>
              <Cascader
                disabled={look}
                options={cascaderObjFu()['年代']}
                placeholder={look ? '（空）' : '请选择'}
                fieldNames={{ label: 'name', value: 'id', children: 'children' }}
              />
            </Form.Item>

            <Form.Item label='年代' name='dictAge'>
              <Cascader
                disabled={look}
                options={cascaderObjFu()['年代']}
                placeholder={look ? '（空）' : '请选择'}
                fieldNames={{ label: 'name', value: 'id', children: 'children' }}
              />
            </Form.Item>

            <Form.Item label='品种' name='dictType'>
              <Cascader
                disabled={look}
                options={cascaderObjFu()['文物类别']}
                placeholder={look ? '（空）' : '请选择'}
                fieldNames={{ label: 'name', value: 'id', children: 'children' }}
              />
            </Form.Item>

            <div className='formRow formRow2'>
              <div className='formLeft'>尺寸：</div>
              <div className='formRight formRightSize'>
                <Form.Item label='通长' name='sizeL'>
                  <InputNumber
                    readOnly={look}
                    min={0}
                    max={99999999}
                    precision={2}
                    placeholder={look ? '（空）' : '请输入数字，最多两位小数'}
                  />
                </Form.Item>

                <Form.Item label='通宽' name='sizeW'>
                  <InputNumber
                    readOnly={look}
                    min={0}
                    max={99999999}
                    precision={2}
                    placeholder={look ? '（空）' : '请输入数字，最多两位小数'}
                  />
                </Form.Item>
                <Form.Item label='通高' name='sizeH'>
                  <InputNumber
                    readOnly={look}
                    min={0}
                    max={99999999}
                    precision={2}
                    placeholder={look ? '（空）' : '请输入数字，最多两位小数'}
                  />
                </Form.Item>

                <Form.Item name='sizeUnit'>
                  <Cascader
                    disabled={look}
                    options={cascaderObjFu()['尺寸单位']}
                    placeholder={look ? '（空）' : '请选择单位'}
                    fieldNames={{ label: 'name', value: 'id', children: 'children' }}
                  />
                </Form.Item>
              </div>
            </div>

            <div className='B3NrowDing'>
              <Form.Item label='重量' name='quality'>
                <InputNumber
                  readOnly={look}
                  min={0}
                  max={99999999}
                  precision={2}
                  placeholder={look ? '（空）' : '请输入数字，最多两位小数'}
                />
              </Form.Item>

              <Form.Item name='qualityUnit'>
                <Cascader
                  disabled={look}
                  options={cascaderObjFu()['质量单位']}
                  placeholder={look ? '（空）' : '请选择单位'}
                  fieldNames={{ label: 'name', value: 'id', children: 'children' }}
                />
              </Form.Item>

              <div className='B3NrowDing2'>
                <Form.Item label='报价(万元)' name='offer'>
                  <InputNumber
                    readOnly={look}
                    min={0}
                    max={99999999}
                    precision={2}
                    placeholder={look ? '（空）' : '请输入数字，最多两位小数'}
                  />
                </Form.Item>
              </div>
            </div>

            <Form.Item label='介绍' name='intro'>
              <TextArea readOnly={look} maxLength={200} showCount placeholder='请输入内容' />
            </Form.Item>

            <Form.Item label='原持有人' name='holder'>
              <Input readOnly={look} maxLength={30} showCount placeholder='请输入内容' />
            </Form.Item>

            <Form.Item label='征集方式' name='source'>
              <Cascader
                disabled={look}
                options={cascaderObjFu()['来源']}
                placeholder={look ? '（空）' : '请选择'}
                fieldNames={{ label: 'name', value: 'id', children: 'children' }}
              />
            </Form.Item>
            <div className='B1Mrow' style={{ marginTop: -20 }}>
              <div className='B1Mrowll' style={{ top: 20 }}>
                图片：
              </div>
              <div className='B1Mrowrr'>
                <ZupTypes
                  isEdit={false}
                  ref={imgRef}
                  selecFlag='图片'
                  fileCheck={false}
                  isLook={look}
                  imgLength={30}
                  isTypeShow={true}
                  oneIsCover={true}
                  isOneType={true}
                  dirCode='B1collectSon'
                  myUrl='cms/goods/upload'
                />
              </div>
            </div>

            <div className='B1Mrow'>
              <div className='B1Mrowll'>附件：</div>
              <div className='B1Mrowrr'>
                <Z3upFiles
                  max={10}
                  isLook={look}
                  ref={filesRef}
                  fileCheck={false}
                  dirCode='B1collectSon'
                  myUrl='cms/goods/upload'
                  lookData={file}
                  size={500}
                />
              </div>
            </div>
          </div>

          {/* 确定和取消按钮 */}
          <Form.Item className='B1Mbtn'>
            {look ? (
              <Button onClick={closeFu}>关闭</Button>
            ) : (
              <>
                <Button type='primary' htmlType='submit'>
                  提交
                </Button>
                &emsp;
                <MyPopconfirm txtK='取消' onConfirm={closeFu} />
              </>
            )}
          </Form.Item>
        </Form>
      </div>
    </Modal>
  )
}

const MemoB1MoAdd = React.memo(B1MoAdd)

export default MemoB1MoAdd
