import React, { useCallback, useEffect, useRef } from 'react'
import styles from './index.module.scss'
import { C1GoodType } from '@/pages/A3_ledger/C1ledger/type'
import { Button, Cascader, Form, FormInstance, Input, InputNumber, Modal, Select } from 'antd'
import { MessageFu } from '@/utils/message'
import ZupTypes from '@/components/ZupTypes'
import { selectObj } from '@/utils/select'
import { cascaderObjFu } from '@/utils/history'
import MyPopconfirm from '@/components/MyPopconfirm'
import TextArea from 'antd/es/input/TextArea'
import { API_C2getListByIds } from '@/store/action/C2files'
import { fileImgArr } from '@/store/action/layout'
import { cascaderChArr } from '@/pages/C_goodsManage/C1register/AddGoods'
import { GoodFileType } from '@/components/Z3upFiles'

type Props = {
  info: C1GoodType
  closeFu: () => void
  succFu: (val: C1GoodType) => void
  look?: boolean
}

function B2MoAdd({ info, closeFu, succFu, look = false }: Props) {
  const getInfoFu = useCallback(async (info: C1GoodType) => {
    const obj: any = { ...info }
    cascaderChArr.forEach(v => {
      if (obj[v]) obj[v] = obj[v].split(',')
    })
    FormBoxRef.current?.setFieldsValue({
      ...obj
    })

    if (info.fileIds) {
      const res = await API_C2getListByIds(info.fileIds.split(','))
      if (res.code === 0) {
        const arr: GoodFileType[] = res.data || []

        const imgArr = arr.filter(v => {
          const txtArr = v.fileName.split('.')
          const txt = txtArr[txtArr.length - 1]
          return v.type === 'img' && fileImgArr.includes(txt)
        })

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

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

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

  // 通过校验点击确定
  const onFinish = useCallback(
    async (values: any) => {
      // 上传图片
      const { sonFileIds, coverUrl, coverPcUrl } = imgRef.current?.fileComFileResFu()

      const obj = {
        ...values,
        id: info.id,
        fileIds: 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(',')
      })
      MessageFu.success('编辑成功')
      succFu(obj)
      closeFu()
    },
    [closeFu, info.id, succFu]
  )

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

  useEffect(() => {
    if (info.id) getInfoFu(info)
  }, [getInfoFu, info])

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

            <div className='B3NrowDing'>
              <Form.Item label='登记号' name='numName'>
                <Select
                  disabled={look}
                  options={selectObj['藏品编号类型']}
                  placeholder={look ? '（空）' : '请选择类型'}
                  allowClear={true}
                />
              </Form.Item>

              <Form.Item name='num'>
                <Input
                  readOnly={look}
                  maxLength={30}
                  showCount
                  placeholder={look ? '（空）' : '请输入内容'}
                />
              </Form.Item>
            </div>

            <Form.Item label='分类号' name='numType'>
              <Input
                readOnly={look}
                maxLength={30}
                showCount
                placeholder={look ? '（空）' : '请输入内容'}
              />
            </Form.Item>

            <div className='B3NrowDing'>
              <Form.Item label='数量' name='pcs'>
                <InputNumber
                  readOnly={look}
                  min={1}
                  max={99999999}
                  precision={0}
                  placeholder={look ? '（空）' : '请输入正整数'}
                />
              </Form.Item>

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

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

            <Form.Item label='年代' name='dictAge'>
              <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>

            <Form.Item label='现状概述' name='dictTorn'>
              <Cascader
                disabled={look}
                options={cascaderObjFu()['完残程度']}
                placeholder={look ? '（空）' : '请选择'}
                fieldNames={{ label: 'name', value: 'id', children: 'children' }}
                allowClear={true}
              />
            </Form.Item>

            <Form.Item label='文物级别' name='dictLevel'>
              <Select
                disabled={look}
                options={selectObj['文物级别']}
                placeholder={look ? '（空）' : '请选择'}
                allowClear={true}
              />
            </Form.Item>

            <Form.Item label='备注' name='intro'>
              <TextArea
                readOnly={look}
                maxLength={200}
                showCount
                placeholder={look ? '（空）' : '请输入内容'}
              />
            </Form.Item>

            <div className='B2Mrow' style={{ marginTop: -20 }}>
              <div className='B2Mrowll' style={{ top: 20 }}>
                图片：
              </div>
              <div className='B2Mrowrr'>
                <ZupTypes
                  isEdit={false}
                  ref={imgRef}
                  selecFlag='图片'
                  fileCheck={false}
                  isLook={look}
                  imgLength={30}
                  isTypeShow={true}
                  oneIsCover={true}
                  isOneType={true}
                  dirCode='B2identifySon'
                  myUrl='cms/goods/upload'
                />
              </div>
            </div>
          </div>

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

const MemoB2MoAdd = React.memo(B2MoAdd)

export default MemoB2MoAdd
