import {useEffect, useState} from 'react'
import Taro, {getCurrentInstance} from '@tarojs/taro'
import {
  Form,
  Button,
  Input,
  RadioGroup,
  Radio
} from '@nutui/nutui-react-taro'
import {navigateTo} from '@tarojs/taro'
import {addBszxPay,myPageBszxPay} from "@/api/bszx/bszxPay";
import {BszxPay} from "@/api/bszx/bszxPay/model";
import {TenantId} from "@/utils/config";
import {myPageBszxBm} from "@/api/bszx/bszxBm";

const Bm = () => {
  const { router } = getCurrentInstance();
  const [formId, setFormId] = useState<number>()
  const [gradeName, setGradeName] = useState('')
  const [className, setClassName] = useState('')
  const [FormData, setFormData] = useState<BszxPay>(
    {
      name: undefined,
      sex: undefined,
      phone: undefined,
      className: undefined,
      gradeName: undefined,
      address: undefined,
      workUnit: undefined,
      position: undefined,
      present: undefined,
      formId: undefined
    }
  )

  // 提交表单
  const submitSucceed = (values: any) => {
    // if(values.price < 10){
    //   Taro.showToast({
    //     title: '捐款金额不能低于10元',
    //     icon: 'none'
    //   })
    //   return false;
    // }
    Taro.request({
      url: 'https://cms-api.websoft.top/api/shop/shop-order',
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'Authorization': Taro.getStorageSync('access_token'),
        TenantId
      },
      data: {
        totalPrice: values.price,
        payPrice: values.price,
        tenantId: TenantId,
        payType: 1,
        comments: values.comments,
        name: values.name || FormData.name,
        sex: values.sex || FormData.sex,
        phone: values.phone || FormData.phone,
        className: className || FormData.className,
        gradeName: gradeName || FormData.gradeName,
        address: values.address || FormData.address,
        workUnit: values.workUnit || FormData.workUnit,
        position: values.position || FormData.position,
        formId
      },
      success: function (res) {
        const data = res.data.data
        if(data){
          Taro.requestPayment({
            timeStamp: data.timeStamp,
            nonceStr: data.nonceStr,
            package: data.package,
            signType: data.signType,
            paySign: data.paySign,
            success: function (res) {
              if(res.errMsg == "requestPayment:ok"){
                console.log('捐款成功')
                addBszxPay({
                  formId,
                  orderNo: data.orderNo,
                  name: values.name || FormData.name,
                  sex: values.sex || FormData.sex,
                  phone: values.phone || FormData.phone,
                  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 === '能',
                  price: values.price || FormData.price,
                  comments: values.comments,
                }).then((data) => {
                  console.log(data,'payRes')
                  console.log('跳转证书页面')
                  setTimeout(() => {
                    navigateTo({url: `/bszx/pay-cert/pay-cert?id=${data?.id}&orderNo=${data?.orderNo}`});
                  }, 1000)
                }).catch(err => {
                  console.log(err,'errr....')
                })
              }
            },
            fail: function (res) {
              console.log(res)
            }
          })
        }
      }
    })
  }

  const submitFailed = (error: any) => {
    console.log(error,'err...')
    // Taro.showToast({ title: error[0].message, icon: 'error' })
  }
  const reload = () => {
    myPageBszxBm().then(res => {
      if(res.count == 0){
        Taro.showToast({
          title: '请先完善个人资料',
          icon: 'error'
        })
        setTimeout(() => {
          Taro.navigateTo({
            url: '/user/profile/profile'
          })
        }, 1000)
      }
    })
    myPageBszxPay({limit: 1}).then(res => {
      const item = res.list[0];
      if(item){
        setFormData(item)
        if(item.gradeName){
          setGradeName(item.gradeName)
        }
        if(item.className){
          setClassName(item.className)
        }
      }
    })
  }

  useEffect(() => {
    const id = router?.params.id as number | undefined;
    setFormId(id)
    reload()
  }, [])

  return (
    <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
          name="price"
          initialValue={FormData.price}
          rules={[{message: '请选您要择捐款的金额'}]}
        >
          <RadioGroup value={FormData.price} direction="horizontal">
            <Radio shape="button" value="100"><span className={'font-bold text-sm'}>100元</span></Radio>
            <Radio shape="button" value="200"><span className={'font-bold text-sm'}>200元</span></Radio>
            <Radio shape="button" value="300"><span className={'font-bold text-sm'}>300元</span></Radio>
            <Radio shape="button" value="500"><span className={'font-bold text-sm'}>500元</span></Radio>
            <Radio shape="button" value="1000"><span className={'font-bold text-sm'}>1000元</span></Radio>
            <Radio shape="button" value="2000"><span className={'font-bold text-sm'}>2000元</span></Radio>
            <Radio shape="button" value="3000"><span className={'font-bold text-sm'}>3000元</span></Radio>
            <Radio shape="button" value="5000"><span className={'font-bold text-sm'}>5000元</span></Radio>
            <Radio shape="button" value="10000"><span className={'font-bold text-sm'}>10000元</span></Radio>
          </RadioGroup>
        </Form.Item>
        <Form.Item
          label="捐款金额"
          name="price"
          required
          rules={[{ required: true,message: '请输入捐款数额' }]}
        >
          <Input placeholder="请输入捐款数额" />
        </Form.Item>
        <Form.Item
          label="您的心愿"
          name="comments"
          rules={[{ message: '请填写您的心意' }]}
        >
          <Input placeholder="请填写您的心意" />
        </Form.Item>
      </Form>
    </div>
  )
}

export default Bm
