import OSticky from '@/components/o-sticky'
import { Button, Cell, CellGroup, Field, Picker, Popup, showToast, Switch } from 'vant'
import { defineComponent, onMounted, reactive } from 'vue'
import request from '../request-music'
import styles from './index.module.less'
import { areas } from '@/helpers/area'
import { verifiyNumberInteger } from '@/helpers/toolsValidate'
import { router } from '@/router/routes-common'
import { useRoute, useRouter } from 'vue-router'

export default defineComponent({
  name: 'address-operation',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const state = reactive({
      isClick: false,
      showPicker: false,
      defaultStatus: false,
      phoneNumber: null,
      province: null,
      city: null,
      region: null,
      pcrStr: '',
      name: null,
      detailAddress: null
    })

    const onFormatterInt = (val: any) => {
      if (val && val >= 1) {
        return verifiyNumberInteger(val)
      } else {
        return ''
      }
    }

    const onSubmit = async () => {
      try {
        if (!state.name) {
          showToast('请选择收货人')
          return
        }
        if (!state.phoneNumber && !/^1(3|4|5|6|7|8|9)\d{9}$/.test(state.phoneNumber as any)) {
          showToast('手机号输入有误')
          return
        }
        if (!state.pcrStr) {
          showToast('请选择所在地区')
          return
        }
        if (!state.detailAddress) {
          showToast('请输入详细地址')
          return
        }
        state.isClick = true
        const params: any = {
          name: state.name,
          phoneNumber: state.phoneNumber,
          province: state.province,
          city: state.city,
          region: state.region,
          detailAddress: state.detailAddress,
          defaultStatus: state.defaultStatus
        }
        if (route.query.id) {
          await request.post('/api-student/userReceiveAddress/update', {
            data: {
              id: route.query.id,
              ...params
            }
          })
          setTimeout(() => {
            showToast('修改成功')
          }, 100)
        } else {
          await request.post('/api-student/userReceiveAddress/save', {
            data: {
              ...params
            }
          })
          setTimeout(() => {
            showToast('添加成功')
          }, 100)
        }

        setTimeout(() => {
          state.isClick = false
          router.back()
        }, 1100)
      } catch (e: any) {
        //
        state.isClick = false
        console.log(e)
      }
    }

    const getDetails = async () => {
      try {
        const { data } = await request.get(
          '/api-student/userReceiveAddress/detail/' + route.query.id
        )

        state.name = data.name
        state.phoneNumber = data.phoneNumber
        state.province = data.province
        state.city = data.city
        state.region = data.region ? data.region : ''
        state.pcrStr = (data.provinceName || '') + (data.cityName || '') + (data.regionName || '')
        state.detailAddress = data.detailAddress
        state.defaultStatus = data.defaultStatus
      } catch {
        //
      }
    }
    onMounted(() => {
      // 判断是否有编号，有则为修改
      if (route.query.id) {
        getDetails()
      }
    })
    return () => (
      <div class={styles.operation}>
        <CellGroup inset class={styles.form}>
          <Field label="收货人" placeholder="请输入收货人姓名" v-model={state.name} />
          <Field
            label="手机号"
            placeholder="请输入收货人手机号"
            v-model={state.phoneNumber}
            maxlength={11}
            type="tel"
            formatter={onFormatterInt}
          />
          <Field
            label="所在地区"
            placeholder="省、市、区、街道"
            readonly
            isLink
            modelValue={state.pcrStr}
            onClick={() => {
              state.showPicker = true
            }}
          />
          <Field
            label="详细地址"
            placeholder="小区楼栋/乡村名称"
            type="textarea"
            rows={3}
            v-model={state.detailAddress}
            maxlength={100}
          />
        </CellGroup>

        <CellGroup inset style={{ marginTop: '12px' }}>
          <Cell title="设置为默认地址" center class={styles.default}>
            {{ value: () => <Switch v-model={state.defaultStatus} size="23px" /> }}
          </Cell>
        </CellGroup>

        <OSticky position="bottom">
          <div class="btnGroup">
            <Button type="primary" block round onClick={onSubmit} disabled={state.isClick}>
              确认
            </Button>
          </div>
        </OSticky>

        <Popup v-model:show={state.showPicker} position="bottom" round>
          <Picker
            showToolbar
            columns={areas}
            columnsFieldNames={{ text: 'name', value: 'code', children: 'areas' }}
            onCancel={() => (state.showPicker = false)}
            onConfirm={(val: any) => {
              console.log(val, 'val')
              const selectedOptions = val.selectedOptions || []
              // 因为有的只
              state.pcrStr = ''
              if (selectedOptions.length === 2) {
                selectedOptions.forEach((item: any, index: number) => {
                  state.pcrStr += item.name
                  if (index === 0) {
                    state.province = item.code
                  } else if (index === 1) {
                    state.city = item.code
                  }
                })
              } else {
                selectedOptions.forEach((item: any, index: number) => {
                  state.pcrStr += item.name
                  if (index === 0) {
                    state.province = item.code
                  } else if (index === 1) {
                    state.city = item.code
                  } else if (index === 2) {
                    state.region = item.code
                  }
                })
              }

              state.showPicker = false
            }}
          />
        </Popup>
      </div>
    )
  }
})
