import {useEffect, useState} from 'react'
import Taro, {getCurrentInstance} from '@tarojs/taro'
import {
  Form,
  Button,
  Input,
  Radio,
  SideNavBar,
  SubSideNavBar,
  SideNavBarItem
} from '@nutui/nutui-react-taro'
import {DictData} from "@/api/system/dict-data/model";
import {Picker} from '@nutui/nutui-react-taro'
import {pageDictData} from "@/api/system/dict-data";
import {addBszxBm, myPageBszxBm} from "@/api/bszx/bszxBm";
import {BszxBm} from "@/api/bszx/bszxBm/model";
import {getBszxClassForTree} from "@/api/bszx/bszxClass";
// import {User} from "@/api/system/user/model";
// import Banner from "../pages/index/Banner";

const {router} = getCurrentInstance()
const Bm = () => {
  const formId = Number(router?.params.id)

  const [form] = Form.useForm()
  const [sex, setSex] = useState<DictData[]>()
  const [gradeName, setGradeName] = useState<string>('')
  const [className, setClassName] = useState<string>('')
  const [phone, setPhone] = useState<string>('')
  const [classList, setClassList] = useState<any[]>()
  const [gradeList, setGradeList] = useState<any[]>()
  const [present, setPresent] = useState<DictData[]>()
  const [isVisibleClass, setIsVisibleClass] = useState(false)
  const [isVisibleGrade, setIsVisibleGrade] = useState(false)
  const [FormData, setFormData] = useState<BszxBm>(
    {
      type: 0,
      name: undefined,
      sex: undefined,
      phone: undefined,
      className: undefined,
      gradeName: undefined,
      address: undefined,
      workUnit: undefined,
      position: undefined,
      present: undefined,
      formId: undefined,
      comments: undefined
    }
  )

  // 提交表单
  const submitSucceed = (values: any) => {
    addBszxBm({
      formId,
      name: values.name || FormData.name,
      sex: values.sex || FormData.sex,
      phone: phone,
      type: values.type || FormData.type,
      className: className || FormData.className,
      gradeName: gradeName || FormData.gradeName,
      address: values.address || FormData.address,
      workUnit: values.workUnit || FormData.workUnit,
      position: values.position || FormData.position,
      present: values.present ? '能' : '',
      comments: values.comments || FormData.comments
    }).then((data) => {
      if (data) {
        console.log(data,'data')
        Taro.showToast({title: `报名成功`, icon: 'success'})
        // setFormData();
        Taro.setStorageSync('NickName', values.name || FormData.name)
        setTimeout(() => {
          Taro.navigateTo({
            url: '/bszx/bm-cert/bm-cert'
          })
        }, 1000)
      }
    }).catch(() => {
      Taro.showToast({
        title: '请勿重复报名',
        icon: 'error'
      });
    })
  }

  const submitFailed = (error: any) => {
    console.log(error, 'err...')
    // Taro.showToast({ title: error[0].message, icon: 'error' })
  }

  const classConfirmPicker = (
    options: any[]
  ) => {
    let description = ''
    options.forEach((option: any) => {
      description += ` ${option.text}`
    })
    setClassName(description)
  }
  const gradeNameConfirmPicker = (
    options: any[]
  ) => {
    let description = ''
    options.forEach((option: any) => {
      description += ` ${option.text}`
    })
    setGradeName(description)
  }
  const changePicker = (options: any[], values: any, columnIndex: number) => {
    form.setFieldValue('className', values)
    console.log(options, columnIndex)
  }

  const [navBarState, setNavBarState] = useState({
    visible: false
  })
  const changeNarBar = (visible) => {
    setNavBarState({
      visible
    })
  }

  const onClassChange = (gradeName: string, className: string) => {
    console.log(gradeName,className)
    setGradeName(gradeName);
    setClassName(className);
    setFormData({
      ...FormData,
      gradeName,
      className
    })
    setNavBarState({
      visible: false
    })
  }

  const reload = () => {
    if (!Taro.getStorageSync('access_token')) {
      Taro.showModal({
        title: '提示',
        content: '请先登录',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            Taro.switchTab({
              url: '/pages/user/user'
            })
          }
        }
      })
      return false;
    }
    myPageBszxBm().then(res => {
      const item = res.list[0];
      console.log(item, 'myPageBszxBm')
      if (item) {
        setFormData(item)
        if (item.gradeName) {
          setGradeName(item.gradeName)
        }
        if (item.className) {
          setClassName(item.className)
        }
      }
    })
    getBszxClassForTree().then(res => {
      console.log(res, 'setClassList');
      setClassList(res);
    })
    pageDictData({limit: 200}).then(res => {
      setSex(res?.list.filter((item) => item.dictCode === 'sex'))
      setPresent(res?.list.filter((item) => item.dictCode === 'present'))
      // setClassList([res?.list.filter((item) => item.dictCode === 'Class')])
      setGradeList(res?.list.filter((item) => {
        if (item.dictCode === 'Grade') {
          item.value = item.dictDataCode;
          item.text = item.dictDataName;
          return item
        }
      }))
    })
    setPhone(Taro.getStorageSync('Phone'))
    form.setFieldValue('phone', Taro.getStorageSync('Phone')) // 确保 form 已经初始化
  }

  useEffect(() => {
    reload()
  }, [form]) // 确保 form 已经初始化

  return (
    <>
      {/*<Banner/>*/}
      {/*<div className={'fixed top-14 left-4 text-white'}>*/}
      {/*  <image src={{ 'https://oss.wsdns.cn/20250224/5187dab5bc5047bda4521069696fd4dd.png' }} />*/}
      {/*  <span>返回</span>*/}
      {/*</div>*/}
      <div className={'p-4'}>
        <Form
          divider
          initialValues={FormData}
          labelPosition="left"
          onFinish={(values) => submitSucceed(values)}
          onFinishFailed={(errors) => submitFailed(errors)}
          footer={
            <div
              style={{
                display: 'flex',
                justifyContent: 'center',
                width: '100%',
              }}
            >
              <Button nativeType="submit" block type="primary">
                提交
              </Button>
            </div>
          }
        >
          <Form.Item
            label="类型"
            name="type"
            style={{marginTop: '10px'}}
            required
            initialValue={FormData.type}
          >
            <Radio.Group defaultValue={FormData.type} direction="horizontal">
              <Radio value={0}>校友</Radio>
              <Radio value={1}>单位</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            label="姓名"
            name="name"
            required
            initialValue={FormData.name}
            rules={[{message: '请输入你的真实姓名'}]}
          >
            <Input placeholder="请输入姓名" type="text"/>
          </Form.Item>
          <Form.Item
            label="性别"
            name="sex"
            required
            initialValue={FormData.sex}
            rules={[
              {message: '请选择性别'}
            ]}
          >
            <Radio.Group defaultValue={FormData.sex} direction="horizontal">
              {
                sex?.map((item, index) => (
                  <Radio key={index} value={item.dictDataCode}>
                    {item.dictDataName}
                  </Radio>
                ))
              }
            </Radio.Group>
          </Form.Item>
          <Form.Item
            label="手机号码"
            name="phone"
            required
            initialValue={phone}
            rules={[{max: 11, message: '请输入手机号码'}]}
          >
            <Input placeholder="手机号码" maxLength={11} type="number"/>
          </Form.Item>
          <Form.Item
            label="所在班级"
            name="className"
            required
            initialValue={FormData.className}
            rules={[{message: '请输入您的年级'}]}
          >
            <Button onClick={() => changeNarBar(true)}>{ className ? gradeName + ' ' + className : '请选择班级' }</Button>
          </Form.Item>
          <Form.Item
            label="居住地"
            name="address"
            initialValue={FormData.address}
            rules={[{message: '请输入现居住地'}]}
          >
            <Input placeholder="请输入现居住地" type="text"/>
          </Form.Item>
          <Form.Item
            label="工作单位"
            name="workUnit"
            required
            initialValue={FormData.workUnit}
            rules={[{message: '请输入您就职工作单位'}]}
          >
            <Input placeholder="请输入您就职工作单位" type="text"/>
          </Form.Item>
          <Form.Item
            label="职务"
            name="position"
            required
            initialValue={FormData.position}
            rules={[{message: '请输入您的职务'}]}
          >
            <Input placeholder="请输入您的职务" type="text"/>
          </Form.Item>
          <Form.Item
            label="是否能到场"
            name="present"
            required
            rules={[{required: true, message: '请选择是否能到场'}]}
          >
            <Radio.Group direction="horizontal">
              {
                present?.map((item, index) => (
                  <Radio key={index} value={item.dictDataCode}>
                    {item.dictDataName}
                  </Radio>
                ))
              }
            </Radio.Group>
          </Form.Item>
          <Form.Item
            label="备注信息"
            name="comments"
            initialValue={FormData.comments}
            rules={[{message: '备注信息'}]}
          >
            <Input placeholder="如找不到或忘记所在班级请备注一下" type="text"/>
          </Form.Item>
        </Form>
        <Picker
          visible={isVisibleClass}
          options={classList}
          onConfirm={(list) => classConfirmPicker(list)}
          defaultValue={[2]}
          threeDimensional={false}
          duration={1000}
          onClose={() => setIsVisibleClass(false)}
          onChange={changePicker}
        />
        <Picker
          visible={isVisibleGrade}
          options={gradeList}
          onConfirm={(list) => gradeNameConfirmPicker(list)}
          defaultValue={[2]}
          threeDimensional={false}
          duration={1000}
          onClose={() => setIsVisibleGrade(false)}
          onChange={changePicker}
        />
        <SideNavBar
          title="选择班级"
          visible={navBarState.visible}
          onClose={() => {
            changeNarBar(false)
          }}
        >
          {
            classList?.map((item) => {
              return (
                <SubSideNavBar title={item.name} open={false} value={item.id}>
                  {
                    item.children?.map((sub) => {
                      return (
                        <>
                          <SubSideNavBar title={sub.name} open={false} value={item.id + '-' + sub.id}>
                            {
                              sub.children?.map((sub2) => {
                                return (
                                  <SideNavBarItem title={sub2.name} value={item.id + '-' + sub.id + '-' + sub2.id} onClick={() => {
                                    onClassChange(sub.name,sub2.name)
                                  }}/>
                                )
                              })
                            }
                          </SubSideNavBar>
                        </>
                      )
                    })
                  }
                </SubSideNavBar>
              );
            })
          }
        </SideNavBar>
      </div>
    </>
  )
}

export default Bm
