import { DeleteOutlined } from '@ant-design/icons'

import { Form, Input, Modal, Button } from 'antd'
import styles from './index.module.scss'
import MyPopconfirm from '@/components/MyPopconfirm'
import { B_APIgetServe, B_APIsetServe, B_APIdelServe } from '@/store/action/Breserve'
import { useEffect, useCallback, useState } from 'react'
import { MessageFu } from '@/utils/message'

type C1setServeProps = {
  setIsShowServe: (v: boolean) => void
  isShowServe: boolean
}

const C1setServe = ({ setIsShowServe, isShowServe }: C1setServeProps) => {
  const [form] = Form.useForm()
  const [deleteIds, setDeleteIds] = useState<number[]>([])

  const getServe = useCallback(async () => {
    const res = await B_APIgetServe()
    if (res.code === 0) {
      form.setFieldsValue({
        dynamicItems: [
          ...res.data.map((item: any) => ({
            serverName: item.context,
            price: item.remark,
            id: item.id
          }))
        ]
      })
    }
  }, [form])

  useEffect(() => {
    getServe()
  }, [getServe])

  const submitForm = useCallback(async () => {
    // 校验是否为空
    try {
      await form.validateFields()
    } catch (error) {
      return
    }
    // 同时处理删除和修改，一个操作失败全失败
    const deleteRes = await Promise.all(deleteIds.map(id => B_APIdelServe(id)))
    if (deleteRes.some(item => item.code !== 0)) {
      MessageFu.error('删除讲解服务失败!')
      return
    }

    const setRes = await B_APIsetServe(
      form.getFieldValue('dynamicItems').map((item: any) => ({
        context: item.serverName,
        remark: item.price,
        id: item.id
      }))
    )
    if (setRes.code !== 0) {
      MessageFu.error('设置讲解服务失败!')
      return
    }
    MessageFu.success('设置讲解服务成功!')
    setIsShowServe(false)
  }, [deleteIds, form, setIsShowServe])

  const MyDynamicForm = () => {
    return (
      <Form form={form}>
        <Form.List name='dynamicItems'>
          {(fields, { add, remove }) => (
            <>
              <Button className='addServe' type='primary' onClick={add}>
                新增
              </Button>
              {fields.map(({ key, name, fieldKey, ...restField }) => (
                <div key={key} style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
                  <Form.Item
                    {...restField}
                    name={[name, 'serverName']}
                    rules={[{ required: true, message: '请输入讲解服务' }]}
                  >
                    <Input style={{ width: 500 }} placeholder='请输入讲解服务' />
                  </Form.Item>
                  <Form.Item
                    {...restField}
                    name={[name, 'price']}
                    rules={[{ required: true, message: '请输入价格' }]}
                  >
                    <Input placeholder='请输入价格' />
                  </Form.Item>
                  <Form.Item {...restField} name={[name, 'id']}>
                    <Input hidden />
                  </Form.Item>
                  <Button
                    type='text'
                    danger
                    onClick={() => {
                      // 获取当前行数据
                      const currentId = form.getFieldValue('dynamicItems')[name].id
                      // 记录删除的id
                      if (currentId) {
                        setDeleteIds([...deleteIds, currentId])
                      }
                      remove(name)
                    }}
                    icon={<DeleteOutlined />}
                    title='删除'
                  />
                </div>
              ))}
            </>
          )}
        </Form.List>
      </Form>
    )
  }
  return (
    <Modal
      wrapClassName={styles.C1SetServe}
      width={800}
      title='设置讲解服务'
      open={isShowServe}
      onOk={() => {
        console.log('ok')
      }}
      onCancel={() => setIsShowServe(false)}
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <MyDynamicForm />
      <div className='C1Nbtn'>
        <MyPopconfirm txtK='取消' onConfirm={() => setIsShowServe(false)} />
        &emsp;
        <Button type='primary' onClick={submitForm}>
          提交
        </Button>
      </div>
    </Modal>
  )
}

export default C1setServe
