<template>
  <view class="container">
    <view class="title">
    </view>
    <uni-forms ref="userInfoForm" :modelValue="userInfoFormData" :rules="userInfoFormRules">
      <uni-forms-item name="first_name">
        <text class="uni-subtitle">{{ $t('form.firstName.label') }}</text>
        <uni-easyinput
            trim="both"
            primaryColor="#29BBE4"
            v-model="userInfoFormData.first_name"
            :disabled="authStatus.identity === 1"
            @input="(e) => handleNameInput(e, 'first_name')"
        ></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="last_name">
        <text class="uni-subtitle">{{ $t('form.lastName.label') }}</text>
        <uni-easyinput
            trim="both"
            primaryColor="#29BBE4"
            v-model="userInfoFormData.last_name"
            :disabled="authStatus.identity === 1"
            @input="(e) => handleNameInput(e, 'last_name')"
        ></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="birthday">
        <text class="uni-subtitle">{{ $t('form.birthday.label') }}</text>
        <uni-datetime-picker type="date" v-model="userInfoFormData.birthday" :disabled="authStatus.identity === 1" />
      </uni-forms-item>
      <uni-forms-item name="sex">
        <text class="uni-subtitle">{{ $t('form.sex.label') }}</text>
        <uni-data-checkbox selectedColor="#29BBE4" v-model="userInfoFormData.sex" :localdata="sexOptions" :disabled="authStatus.identity === 1" />
      </uni-forms-item>
      <uni-forms-item name="email">
        <text class="uni-subtitle">{{ $t('form.email.label') }}</text>
        <uni-easyinput disabled trim="all" primaryColor="#29BBE4" v-model="userInfoFormData.email"></uni-easyinput>
      </uni-forms-item>
      <view style="display: flex;">
        <uni-forms-item name="phone_prefix" style="width: 120upx;margin-right: 10upx;" >
          <text class="uni-subtitle">{{ $t('form.phoneNumber.label') }}</text>
          <uni-easyinput trim="all" primaryColor="#29BBE4" v-model="userInfoFormData.phone_prefix" :clearable="false" :maxlength="$0" :disabled="authStatus.address === 1"></uni-easyinput>
        </uni-forms-item>
        <uni-forms-item name="phone" style="width: calc(100% - 130upx);" >
          <text class="uni-subtitle">&emsp;</text>
          <uni-easyinput trim="all" primaryColor="#29BBE4" v-model="userInfoFormData.phone" :disabled="authStatus.address === 1"></uni-easyinput>
        </uni-forms-item>
      </view>
      <uni-forms-item name="residence">
        <text class="uni-subtitle">{{ $t('form.residence.label') }}</text>
        <uni-easyinput trim="all" primaryColor="#29BBE4" v-model="userInfoFormData.residence" :disabled="authStatus.address === 1"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="postcode">
        <text class="uni-subtitle">{{ $t('form.postcode.label') }}</text>
        <uni-easyinput trim="all" primaryColor="#29BBE4" v-model="userInfoFormData.postcode" :disabled="authStatus.address === 1"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="country">
        <text class="uni-subtitle">{{ $t('form.country.label') }}</text>
        <uni-data-select :localdata="countryOptions" v-model="userInfoFormData.country" :disabled="authStatus.address === 1"></uni-data-select>
      </uni-forms-item>
      <uni-forms-item name="address_state">
        <text class="uni-subtitle">{{ $t('form.state.label') }}</text>
        <uni-data-select
            :placeholder="$t('form.pleaseSelect')"
            :emptyTips="$t('common.empty')"
            :localdata="stateOptions"
            v-model="userInfoFormData.address_state"
            :disabled="authStatus.address === 1"
        ></uni-data-select>
      </uni-forms-item>
      <uni-forms-item name="address">
        <text class="uni-subtitle">{{ $t('form.city.label') }}</text>
        <uni-data-select
            :placeholder="$t('form.pleaseSelect')"
            :emptyTips="$t('common.empty')"
            :localdata="cityOptions"
            v-model="userInfoFormData.address"
            :disabled="authStatus.address === 1"
        ></uni-data-select>
      </uni-forms-item>
      <uni-forms-item name="address_detailed">
        <text class="uni-subtitle">{{ $t('form.addressDetailed.label') }}</text>
        <uni-easyinput trim="all" primaryColor="#29BBE4" v-model="userInfoFormData.address_detailed" :disabled="authStatus.address === 1"></uni-easyinput>
      </uni-forms-item>
    </uni-forms>
    <view>
      <button :disabled="btnLoading" class="primaryButton" @click="handleSaveUserInfo">
        <image v-show="btnLoading" src="/static/loadingCircle.svg" mode="aspectFit" style="width: 16px; height: 16px"></image>
        {{ $t('form.save') }}
      </button>
    </view>
  </view>
</template>

<script>
import { useUserStore } from '@/stores/user';
import { getCountryList, getStateList, getCityList } from '@/services/common.ts';
import { getUserBaseInfo, saveUserBaseInfo } from '@/services/user';
import { patterns } from '@/utils/const';
export default {
  data() {
    return {
      authStatus: {},
      btnLoading: false,
      countryOptions: [],
      stateOptions: [],
      cityOptions: [],
      sexOptions: [
        { text: this.$t('form.sex.radio1'), value: 0 }, // 0-男
        { text: this.$t('form.sex.radio2'), value: 1 } // 1-女
      ],
      userInfoFormData: {},
      userInfoFormRules: {}
    };
  },
  methods: {
    handleNameInput(val, field) {
      setTimeout(() => {
        this.userInfoFormData[field] = val.replaceAll(patterns.name, '').trim();
      }, 0);
    },
    async getUserInfo() {
      const res = await getUserBaseInfo();
      if (res && res.code === 0) {
        this.userInfoFormData = { ...this.userInfoFormData, ...res.data };
      }
    },
    async getCountryOptions() {
      const res = await getCountryList();
      if (res && res.code === 0) {
        this.countryOptions = res.data?.map((country) => ({
          text: country.name,
          value: country.id
        }));
      }
    },
    async getStateOptions(pid) {
      const res = await getStateList(pid);
      if (res && res.code === 0) {
        this.stateOptions = res.data?.map((state) => ({
          text: state.name,
          value: state.id?.toString()
        }));
      }
    },
    async getCityOptions(pid) {
      const res = await getCityList(pid);
      if (res && res.code === 0) {
        this.cityOptions = res.data?.map((city) => ({
          text: city.name,
          value: city.id?.toString()
        }));
      }
    },
    async handleSaveUserInfo() {
      this.$refs.userInfoForm.validate(async (fields) => {
        delete this.userInfoFormData.email;
        Object.keys(this.userInfoFormData).forEach((key) => {
          this.userInfoFormData[key] = this.userInfoFormData[key] ?? '';
        });
        this.btnLoading = true;
        const res = await saveUserBaseInfo(this.userInfoFormData);
        this.btnLoading = false;
        if (res && res.code === 0) {
          this.$cusModal.showModal({
            type: 'message',
            status: 'success',
            contentText: res.msg ?? this.$t('common.success.action'),
            onClose() {
              uni.navigateBack();
            }
          });
        } else {
          this.$cusModal.showModal({
            type: 'message',
            status: 'warning',
            contentText: res.msg ?? this.$t('common.error.sysError')
          });
        }
      });
    }
  },
  created() {
    const userStore = useUserStore();
    this.userInfoFormData.email = userStore.userInfo.email;
    this.getUserInfo();
    this.getCountryOptions();
  },
  watch: {
    'userInfoFormData.country': {
      handler(newVal, oldVal) {
        if (oldVal) {
          this.userInfoFormData.address_state = undefined;
          this.userInfoFormData.address = undefined;
        }
        this.getStateOptions(newVal);
      }
    },
    'userInfoFormData.address_state': {
      handler(newVal, oldVal) {
        if (oldVal) {
          this.userInfoFormData.address = undefined;
        }
        this.getCityOptions(newVal);
      }
    }
  },
  onLoad(params) {
    this.authStatus = JSON.parse(params.authStatus);
  }
};
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
