import React, { useCallback, useEffect, useRef } from 'react'
import styles from './index.module.scss'
import { Button, Cascader, Form, FormInstance, Modal, Select } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import { selectObj } from '@/utils/select'
import { API_C2setFile } from '@/store/action/C2files'
import { MessageFu } from '@/utils/message'
import { cascaderObjFu } from '@/utils/history'

export type infoType = {
  ids: number[]
  type: string
  effect: string | null
  flag: '单个' | '多个'
}

type Props = {
  info: infoType
  closeFu: () => void
  succFu: () => void
}

function Y33setType({ info, closeFu, succFu }: Props) {
  useEffect(() => {
    if (info.flag === '单个') {
      FormBoxRef.current?.setFieldsValue({
        ...info,
        effect: info.effect ? info.effect.split(',') : []
      })
    }
  }, [info])

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

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

  // 通过校验点击确定
  const onFinish = useCallback(
    async (values: any) => {
      const obj = {
        effect: values.effect ? values.effect.join(',') : '',
        type: values.type,
        ids: info.ids
      }
      const res = await API_C2setFile(obj)
      if (res.code === 0) {
        MessageFu.success('设置成功')
        succFu()
        closeFu()
      }
    },
    [closeFu, info.ids, succFu]
  )

  return (
    <Modal
      wrapClassName={styles.Y33setType}
      destroyOnClose
      open={true}
      title='设置'
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className='Y33sMain'>
        <Form
          scrollToFirstError={true}
          ref={FormBoxRef}
          name='basic'
          labelCol={{ span: 3 }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete='off'
        >
          <Form.Item label='类型' name='type' rules={[{ required: true, message: '请输入类型!' }]}>
            <Select options={selectObj['附件类型']} placeholder='请选择' />
          </Form.Item>

          <Form.Item label='用途' name='effect'>
            <Cascader
              changeOnSelect
              fieldNames={{ label: 'name', value: 'id', children: 'children' }}
              options={cascaderObjFu()['附件用途']}
              placeholder='请选择'
            />
          </Form.Item>
          {/* 确定和取消按钮 */}
          <br />
          <Form.Item wrapperCol={{ offset: 9, span: 16 }}>
            <Button type='primary' htmlType='submit'>
              提交
            </Button>
            &emsp;
            <MyPopconfirm txtK='取消' onConfirm={closeFu} />
          </Form.Item>
        </Form>
      </div>
    </Modal>
  )
}

const MemoY33setType = React.memo(Y33setType)

export default MemoY33setType
