<template>
  <cs-page isCustom>
    <template #header>
      <view
        class="wd-flex wd-flex-row wd-items-center"
        style="gap: 8px"
        @click="goBack"
      >
        <view class="icon-box" v-if="form.audit">
          <u-icon name="arrow-left" size="12"></u-icon>
        </view>
        <text class="wd-font-800 wd-text-16">编辑个人信息</text>
      </view>
    </template>
    <view class="container">
      <!-- 我的头像 -->
      <view
        class="section wd-flex wd-flex-row wd-justify-between wd-items-center"
      >
        <text class="wd-font-800">我的头像</text>
        <button
          class="wd-flex wd-flex-row wd-items-center avatarBtn"
          style="gap: 8px"
          type="balanced"
          open-type="chooseAvatar"
          @chooseavatar="chooseAvatar"
        >
          <u-avatar :src="form.avatar"></u-avatar>
          <u-icon name="arrow-right"></u-icon>
        </button>
      </view>
      <!-- 真实姓名 -->
      <view
        class="section wd-flex wd-flex-row wd-justify-between wd-items-center"
      >
        <text class="wd-font-800">姓名</text>
        <view class="wd-flex wd-flex-row wd-items-center" style="gap: 8px">
          <input
            class="wd-text-right"
            type="text"
            placeholder-class="txt"
            placeholder="请输入姓名"
            v-model="form.realName"
          />
          <u-icon name="arrow-right" color="#99A1B7" size="16"></u-icon>
        </view>
      </view>
      <!-- 用户性别 -->
      <view
        class="section wd-flex wd-flex-row wd-justify-between wd-items-center"
        @click="showPicker('system_user_sex', 'sex')"
      >
        <text class="wd-font-800">性别</text>
        <view class="wd-flex wd-flex-row wd-items-center" style="gap: 8px">
          <text v-if="form.sex">
            {{
              $dict.echoDicValue(
                dictMap.system_user_sex,
                form.sex.toString()
              )
            }}
          </text>
          <text class="placeholder" v-else>请选择性别</text>
          <u-icon name="arrow-right" color="#99A1B7" size="16"></u-icon>
        </view>
      </view>
      <!-- 手机号码 -->
      <view
        class="section wd-flex wd-flex-row wd-justify-between wd-items-center"
      >
        <text class="wd-font-800">手机号码</text>
        <view class="wd-flex wd-flex-row wd-items-center" style="gap: 8px">
          <input
            class="wd-text-right"
            type="number"
            placeholder-class="txt"
            placeholder="请输入手机号码"
            v-model="form.mobile"
          />
          <u-icon name="arrow-right" color="#99A1B7" size="16"></u-icon>
        </view>
      </view>
      <!-- 所属部门 -->
      <!-- <view
        class="section wd-flex wd-flex-row wd-justify-between wd-items-center"
        @click="showPicker('dept', 'deptId')"
      >
        <text class="wd-font-800">部门</text>
        <view class="wd-flex wd-flex-row wd-items-center" style="gap: 8px">
          <text v-if="form.deptId">
            {{ $dict.echoDicValue(dictMap.dept, form.deptId) }}
          </text>
          <text class="placeholder" v-else>请选择部门</text>
          <u-icon name="arrow-right" color="#99A1B7" size="16"></u-icon>
        </view>
      </view> -->
      <view class="button-box">
        <button class="button audit" v-if="form.audit == 1">
          {{ $dict.echoDicValue(dictMap.user_audit_type, form.audit) }}
        </button>
        <button class="button submit" @click="submit" v-else>提交</button>
      </view>
    </view>
    <u-picker
      :show="picker.show"
      :columns="picker.data"
      @cancel="closePicker"
      closeOnClickOverlay
      keyName="label"
      ref="uPicker"
      @close="closePicker"
      @confirm="confirmPicker"
    ></u-picker>
  </cs-page>
</template>

<script>
import { getUserProfile, updateUserProfile } from '@/api/system/user.js'
import { uploadFile } from '@/api/system/file.js'
import { getDictBatchByType, getDeptTree } from '@/api/system/dict.js'
export default {
  data() {
    return {
      dictMap: {},
      deptTree: [],
      form: {
        avatar: undefined,
        realName: undefined,
        mobile: undefined,
        deptId: undefined,
        sex: undefined
      },
      picker: {
        show: false,
        key: '',
        data: []
      }
    }
  },
  async onLoad(options) {
    if (options.audit) {
      this.form.audit = options.audit
    }
    await this.getDict()
  },
  onShow() {
    this.init()
  },
  methods: {
    showPicker(type, key) {
      this.picker.data.push(this.dictMap[type])
      this.picker.key = key
      this.picker.show = true
    },
    closePicker() {
      this.picker = {
        show: false,
        key: '',
        data: []
      }
    },
    init() {
      console.log('登录信息', this.$store.getters)
      if (this.$store.getters.userId) {
        getUserProfile().then(res => {
          this.form = res.data
        })
      }
    },
    async getDict() {
      const dict = await getDictBatchByType({
        type: ['system_user_sex', 'user_audit_type'].join(',')
      })

      const dept = await getDeptTree()
      this.dictMap = {
        ...dict.data,
        dept: dept.data.map(i => {
          return {
            ...i,
            label: i.name,
            value: i.id
          }
        })
      }
    },
    chooseAvatar(e) {
      const data = {
        name: 'file',
        filePath: e.detail.avatarUrl
      }
      uploadFile(data).then(res => {
        this.form.avatar = res.data.url
      })
    },
    validateForm() {
      const requiredFields = [
        {
          key: 'avatar',
          message: '请上传头像'
        },
        {
          key: 'realName',
          message: '真实姓名不能为空'
        },
        {
          key: 'sex',
          message: '请选择性别'
        },
        {
          key: 'mobile',
          message: '手机号码不能为空'
        }
        // {
        //   key: 'deptId',
        //   message: '请选择所属部门'
        // }
      ]

      for (const field of requiredFields) {
        if (!this.form[field.key]) {
          uni.showToast({
            title: field.message,
            icon: 'none'
          })
          return false
        }
      }

      const mobilePattern = /^1[3-9]\d{9}$/ // 中国手机号正则表达式
      if (!mobilePattern.test(this.form.mobile)) {
        uni.showToast({
          title: '请输入有效的手机号',
          icon: 'none'
        })
        return false
      }

      return true
    },
    submit() {
      uni.showLoading({
        mask: true,
        title: '提交中...'
      })
      if (!this.validateForm()) return
      updateUserProfile(this.form).then(res => {
        uni.hideLoading()
        uni.showToast({
          title: '操作成功',
          icon: 'success',
          duration: 500
        })
        this.init()
      })
    },
    confirmPicker(e) {
      const { value } = e
      this.form[this.picker.key] = value[0].value
      this.closePicker()
    },
    goBack() {
      if (this.form.audit) {
        uni.switchTab({
          url: '/pages/owner'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  height: 100%;
  padding: 32rpx;
  position: relative;
  .section {
    border-radius: 16rpx;
    background: #fff;
    margin-bottom: 32rpx;
    padding: 24px;
    height: 140rpx;
    font-size: 30rpx;
  }
  .button-box {
    position: fixed;
    bottom: 116rpx;
    right: 10px;
    left: 10px;
    .button {
      width: 60vw;
      border-radius: 30px;
      font-size: 32rpx;
      font-weight: bold;
      height: 40px;
      line-height: 40px;
      box-sizing: border-box;
    }
    .submit {
      color: #fff;
      background: #17c653;
    }
    .audit {
      color: #17c653;
      background: #eafff1;
    }
  }
  .placeholder {
    color: $uni-text-color-grey;
  }
  button {
    padding-left: 0;
    padding-right: 0;
  }
  .avatarBtn {
    background-color: #fff;
    flex: 1;
    justify-content: flex-end;
    &::after {
      content: '';
      display: none;
    }
  }
}
</style>
