import React, { useState } from 'react'
import Taro from '@tarojs/taro'
import { View, Picker } from '@tarojs/components'
import { AtButton, AtIcon, } from 'taro-ui'
import request from '@/services/request'
import { roadSpotPrepare, roadSpotConfirm } from '@/services/api'
import './index.scss'

function Index() {
  const rateArr = ['50%', '75%'];
  const [rate, setRate] = useState('50%')
  const [prepare, setPrepare] = useState({
    previewId: null,
    spotCountyRoadCount: null,
    spotTownRoadCount: null,
    spotVillageRoadCount: null,
  })

  const startSpotCheck = () => {
    request.post(roadSpotPrepare(), { countyPercentage: rate === '50%' ? 50 : 75 }).then(res => {
      if (res.statusCode === 200 || res.statusCode === 204) {
        Taro.showToast({ title: '抽取成功', icon: 'success' })
        setPrepare(res.data)
      } else {
        Taro.showToast({ title: '抽取失败', icon: 'error' })
        console.log(res.errMsg)
      }
    })
  }

  const onSubmit = () => {
    if (!prepare.previewId) {
      Taro.showToast({ title: '请先抽取道路' })
      return
    }
    request.post(roadSpotConfirm(), { previewId: prepare.previewId }).then(res => {
      if (res.statusCode === 204) {
        Taro.showToast({ title: '提交成功', icon: 'success' })
        setTimeout(() => {
          Taro.navigateBack()
        }, 1500)
      } else {
        Taro.showToast({ title: '提交失败', icon: 'error' })
        console.log(res.errMsg)
      }
    })
  }

  return (
    <View className='page'>
      <View className='content'>
        <View className='fs24'>默认抽查乡道比例为25%，村道比例为10%</View>
        <View className='item'>
          <View className='title'>抽查县道比例（%）:</View>
          <Picker mode='selector'
            range={rateArr}
            onChange={e => setRate(rateArr[e.detail.value])}
          >
            <View className='input'>
              {rate || '请选择'}
              <AtIcon value='chevron-down' size='20' color='#ccc' />
            </View>
          </Picker>
        </View>
        <AtButton type='primary' className='start-btn' size='small'
          onClick={startSpotCheck}
        >开始抽取</AtButton>
        <View className='item'>
          <View className='title'>抽查县道（条）：</View>
          <View className='input disabled'>{prepare.spotCountyRoadCount}</View>
        </View>
        <View className='item'>
          <View className='title'>抽查乡道（条）：</View>
          <View className='input disabled'>{prepare.spotTownRoadCount}</View>
        </View>
        <View className='item'>
          <View className='title'>抽查村道（条）：</View>
          <View className='input disabled'>{prepare.spotVillageRoadCount}</View>
        </View>
        <AtButton type='primary' className='submit-btn' onClick={onSubmit}>提交</AtButton>
      </View>
    </View>
  )
}
export default Index