<template>
  <view class="register">
    <view class="registerIndex">
      <nut-form :model-value="formData" ref="formRef" :rules="rules">
        <nut-form-item label="头像：">
          <button class="buttonChoose" open-type="chooseAvatar" @chooseAvatar="onChooseAvatar">
            <view class="contact">
              <image :src="formData.avatar" mode="scaleToFill" class="image"/>
            </view>
          </button>
        </nut-form-item>
        <nut-form-item label="姓名：" prop="name">
          <nut-input
            v-model="formData.name"
            placeholder="请输入您的昵称"
            type="text"
          />
        </nut-form-item>
        <nut-form-item label="性别：" prop="sex">
          <nut-radio-group v-model="formData.sex" direction="horizontal">
            <nut-radio v-for="item in SEX" :key="item.value" :label="item.value"
            >{{ item.label }}
            </nut-radio>
          </nut-radio-group>
        </nut-form-item>
        <nut-form-item label="身份：">
          <nut-radio-group v-model="formData.identity">
            <nut-radio
              v-for="item in IDENTITY"
              :key="item.value"
              :label="item.value"
            >{{ item.label }}
            </nut-radio>
          </nut-radio-group>
        </nut-form-item>

        <nut-form-item label="行政区划：" prop="name">
          <view @click="visible = true" style="color: #808080">
            {{ streetCommunitySmallCommunityLabel || "请选择行政区划" }}
          </view>
        </nut-form-item>
        <nut-form-item label="单位：" name="unitId">
          <view @click="unitsList" style="color: #808080">
            {{ selectedLabel || '请选择单位' }}
          </view>
        </nut-form-item>
      </nut-form>
      <nut-cascader
        v-model:visible="visible"
        v-model="TreeValue"
        title="选择地址"
        @change="change"
        lazy
        :lazy-load="lazyLoad"
        text-key="label"
      ></nut-cascader>
      <nut-popup v-model:visible="show" position="bottom">
        <nut-picker
          :field-names="{
               text: 'label',
               children: 'extData'
    }" v-model="formData.unitId" :columns="columns" title="请选择单位" @confirm="confirm" @cancel="show = false"/>
      </nut-popup>
      <view class="registerBtn">
        <nut-button block type="success" @click="register">注册</nut-button>
      </view>
    </view>
  </view>
</template>
<script setup lang="ts">
import './register.scss'
import {onMounted, ref, watch} from "vue";
import {enumSelectNodes} from "@/enums";
import Taro from "@tarojs/taro";
import api from '@/request/index'
import type {FormInstance} from "@nutui/nutui-taro";
import {FormRules} from "@nutui/nutui-taro/dist/types/__VUE/form/types";
import {RegisterParams} from "@/types/pages/register";

const IDENTITY = enumSelectNodes('MiniProgramUserIdentity')
const SEX = enumSelectNodes('Sex')

const formData = ref<RegisterParams>({
  avatar: "https://img12.360buyimg.com/imagetools/jfs/t1/196430/38/8105/14329/60c806a4Ed506298a/e6de9fb7b8490f38.png",
  name: "",
  sex: 0,
  telephone: '',
  identity: 'police',
  unitId: ''
});
const show = ref(false)
const visible = ref(false)

const TreeValue = ref<Record<string, any>[]>([])
// const TreeData = ref([]);

const streetCommunitySmallCommunityLabel = ref<string>("");
const getAdministrativeDivisionTree = async (value:string) => {
  const resp = await api.get<TreeNodeVo<string>[]>('/common/administrativeDivisionByParentCode',{parentCode:value})
  return resp.data as any
}


const change = async (value: string, pathNodes: Record<string, any>[]) => {
  streetCommunitySmallCommunityLabel.value = pathNodes.map((e) => e.text).join(",");
  TreeValue.value = value as any
}
const lazyLoad = async (node:any, resolve:any)=>{
    if (node.root) {
       await resolve(getAdministrativeDivisionTree ('0'))
    } else {
        await resolve(getAdministrativeDivisionTree (node.value))
    }
}
const columns = ref([])
const unitsList = async () => {
  if (streetCommunitySmallCommunityLabel.value !== '') {
    show.value = true
    const queryUnitListByIdentityQueryParams = {
      identity: formData.value.identity,
      administrativeDivisionCodes: TreeValue.value
    }
    const resp = await api.post<TreeNodeVo<string>[]>('/common/queryUnitListByIdentity', queryUnitListByIdentityQueryParams)
    columns.value = resp.data as any
  } else {
    Taro.showToast({
      title: '请先选择行政区划',
    })
  }
}


const selectedLabel = ref('')
const confirm = ({selectedOptions}) => {
  Object.keys(selectedOptions).forEach((e) => {
    selectedLabel.value = selectedOptions[e].label
    formData.value.unitId = selectedOptions[e].value
  })
  console.log(formData.value.unitId, selectedLabel.value)
  show.value = false
}

// 身份
watch(() => formData.value.identity, () => {
  formData.value.unitId = ''
  selectedLabel.value = ''
})
const formRef = ref<FormInstance>()
// 注册之前先调用login拿取code 传递给后端
// 注册
const register = async () => {
  await Taro.login({
    success: async function (res) {
      if (res.code) {
        const miniProgramUserRegisterParams = {
          code: res.code,
          name: formData.value.name,
          telephone: formData.value.telephone,
          sex: formData.value.sex,
          identity: formData.value.identity,
          unitId: formData.value.unitId
        }
        const resp = await api.post<string>('/miniProgramUser/register', miniProgramUserRegisterParams, {loading: true})
        Taro.showToast({
          title: "注册成功",
          icon: 'success',
          duration: 2000,
          mask: true,
        }).then()
        await Taro.setStorage({
          key: "token",
          data: resp.data,
          success() {
            Taro.navigateTo({
              url: '/pages/login/login'
            })
          },
        })
      } else {
        Taro.showToast({
          title: res.errMsg,
          icon: 'error',
          duration: 2000,
          mask: true
        }).then()
      }
    }
  })
}

const rules: FormRules = {
  name: [
    {required: true, message: "请输入姓名"},
    {
      validator: (value) => {
        return !(value.length < 2 || value.length >= 20);
      },
      message: "名字在2~20字符之间",
    },
  ],
  sex: [{required: true, message: "请选择性别"}],
  telephone: [
    {required: true, message: "请输入手机号码"},
    {
      regex: /^400(-?)[0-9]{7}$|^1\d{10}$|^0[0-9]{2,3}-[0-9]{7,8}$/,
      message: "手机格式错误",
    },
  ],
};

// 获取头像
const onChooseAvatar = (e) => {
  const {avatarUrl} = e.detail
  formData.value.avatar = avatarUrl
}
// 获取昵称
// const getNickname = (e) => {
//   formData.value.name = e.detail.value
//   console.log(formData.value.name)
// }

onMounted(async () => {
  await getAdministrativeDivisionTree()
})
</script>
