import {
  Button,
  Cell,
  CellGroup,
  Field,
  Picker,
  Popup,
  Switch,
  Toast
} from 'vant'
import { defineComponent, onMounted, reactive } from 'vue'
import styles from './index.module.less'
import { areas } from '@/helpers/area'
import { verifiyNumberInteger } from '@/helpers/toolsValidate'
import { useRoute, useRouter } from 'vue-router'
import request from '@/helpers/request'
import ColSticky from '@/components/col-sticky'
import ColHeader from '@/components/col-header'

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) {
          Toast('请选择收货人')

          return
        }
        if (
          !state.phoneNumber ||
          !/^((13[0-9])|(14(0|[5-7]|9))|(15([0-3]|[5-9]))|(16(2|[5-7]))|(17[0-8])|(18[0-9])|(19([0-3]|[5-9])))\d{8}$/.test(
            state.phoneNumber as any
          )
        ) {
          Toast('手机号输入有误')
          return
        }
        if (!state.pcrStr) {
          Toast('请选择所在地区')
          return
        }
        if (!state.detailAddress) {
          Toast('请输入详细地址')
          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-mall-portal/member/address/update/' + route.query.id,
            {
              hideLoading: false,
              data: {
                ...params
              }
            }
          )
        } else {
          await request.post('/api-mall-portal/member/address/add', {
            hideLoading: false,
            data: {
              ...params
            }
          })
        }

        state.isClick = false
        router.back()
      } catch (e: any) {
        //
        state.isClick = false
      }
    }

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

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

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

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