<template>
  <div class="page-content user">
    <div class="content">
      <div class="left-wrap">
        <div class="user-wrap box-style">
          <img class="bg" src="@imgs/user/bg.webp" />
          <el-upload
              :file-list="[]"
              class="upload-demo"
              name="avatar"
              accept="jpg,jpeg,png,webp"
              :show-file-list="false"
              :action="uploadServer"
              :headers="{Authorization: useUserStore().accessToken}"
              :on-success="handleSuccess"
          >
            <img class="avatar" :src="userInfo.avatar || 'https://img.lewaimai.com/zqcrm/avatar/20250926/9PLsci1dwXLcb8Iw.jpg'" title="点击上传"/>
            <template #tip>
              <div class="el-upload__tip">
                点击头像上传
              </div>
            </template>
          </el-upload>
          <h2 class="name">{{ userInfo.username }}</h2>
<!--          <p class="des">逐趣CRM 是一款漂亮的后台管理系统模版.</p>-->

          <div class="outer-info">
            <div>
              <i class="iconfont-sys">&#xe608;</i>
              <span>{{ form.sex ? '女' : '男' }}</span>
            </div>
            <div>
              <i class="iconfont-sys">&#xe6f4;</i>
              <span>{{ form.phone }}</span>
            </div>
            <div>
              <i class="iconfont-sys">&#xe72e;</i>
              <span>{{ form.email }}</span>
            </div>
            <div>
              <i class="iconfont-sys">&#xe811;</i>
              <span>{{ form.descr}}</span>
            </div>
          </div>

<!--          <div class="lables">
            <h3>标签</h3>
            <div>
              <div v-for="item in lableList" :key="item">
                {{ item }}
              </div>
            </div>
          </div>-->
        </div>

        <!-- <el-carousel class="gallery" height="160px"
          :interval="5000"
          indicator-position="none"
        >
          <el-carousel-item class="item" v-for="item in galleryList" :key="item">
            <img :src="item"/>
          </el-carousel-item>
        </el-carousel> -->
      </div>
      <div class="right-wrap">
        <div class="info box-style">
          <h1 class="title">基本设置</h1>

          <ElForm
            :model="form"
            class="form"
            ref="ruleFormRef"
            :rules="rules"
            label-width="86px"
            label-position="top"
          >
            <ElRow>
              <ElFormItem label="用户名" prop="realName">
                <el-input v-model="form.username" :disabled="!isEdit" />
              </ElFormItem>
              <ElFormItem label="性别" prop="sex" class="right-input">
                <ElSelect v-model="form.sex" placeholder="Select" :disabled="!isEdit">
                  <ElOption
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </ElSelect>
              </ElFormItem>
            </ElRow>

            <ElRow>
              <ElFormItem label="手机" prop="phone">
                <ElInput v-model="form.phone" :disabled="!isEdit" />
              </ElFormItem>
              <ElFormItem label="邮箱" prop="email" class="right-input">
                <ElInput v-model="form.email" :disabled="!isEdit" />
              </ElFormItem>
            </ElRow>

            <ElFormItem label="个人介绍" prop="des">
              <ElInput type="text" v-model="form.descr" :disabled="!isEdit" />
            </ElFormItem>

            <div class="el-form-item-right">
              <ElButton type="primary" style="width: 90px" v-ripple @click="edit">
                {{ isEdit ? '保存' : '编辑' }}
              </ElButton>
            </div>
          </ElForm>
        </div>

        <div class="info box-style" style="margin-top: 20px">
          <h1 class="title">更改密码</h1>

          <ElForm ref="pwdFormRef" :model="pwdForm" :rules="pwdRules" class="form" label-width="86px" label-position="top">
            <ElFormItem label="当前密码" prop="password">
              <ElInput
                v-model="pwdForm.password"
                type="password"
                :disabled="!isEditPwd"
                show-password
              />
            </ElFormItem>

            <ElFormItem label="新密码" prop="newPassword">
              <ElInput
                v-model="pwdForm.newPassword"
                type="password"
                :disabled="!isEditPwd"
                show-password
              />
            </ElFormItem>

            <ElFormItem label="确认新密码" prop="confirmPassword">
              <ElInput
                v-model="pwdForm.confirmPassword"
                type="password"
                :disabled="!isEditPwd"
                show-password
              />
            </ElFormItem>

            <div class="el-form-item-right">
              <ElButton type="primary" style="width: 90px" v-ripple @click="editPwd">
                {{ isEditPwd ? '保存' : '编辑' }}
              </ElButton>
            </div>
          </ElForm>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { useUserStore } from '@/store/modules/user'
  import {ElForm, ElMessage, FormInstance, FormRules, UploadProps} from 'element-plus'
  import {commonApi} from "@/api/commonApi";
  import {UserService} from "@/api/usersApi";
  import {computed} from "vue";

  defineOptions({ name: 'UserCenter' })

  const uploadServer = computed(() => import.meta.env.VITE_API_URL + import.meta.env.VITE_UPLOAD_URL)
  const userStore = useUserStore()
  const userInfo = computed(() => userStore.getUserInfo)

  const isEdit = ref(false)
  const isEditPwd = ref(false)
  const date = ref('')
  const form = reactive<Form.User>({
    username: userInfo.value.username || '',
    email: userInfo.value.email || '',
    phone: userInfo.value.phone || '',
    sex: userInfo.value.sex || 0,
    descr: userInfo.value.descr || '',
  })

  const handleSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
    if (response.code === 200) {
      ElMessage.success('上传成功!')
      userInfo.value.avatar = response.data.url
    } else {
      ElMessage.error(response.msg)
    }
  }

  const pwdForm = reactive<Form.ChangePassword>({
    password: '',
    newPassword: '',
    confirmPassword: ''
  })

  const ruleFormRef = ref<FormInstance>()
  const pwdFormRef = ref<FormInstance>()

  const pwdRules = reactive<FormRules>({
    password: [
      {required: true, message: '请输入密码', trigger: 'blur'},
      {min: 1, max: 12, message: '长度在 1 到 12 个字符', trigger: 'blur'}
    ],
    newPassword: [
      {required: true, message: '请输入新密码', trigger: 'blur'},
      {min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur'}
    ],
    confirmPassword: [{required: true, message: '请确认新密码', trigger: 'blur'}],
  })

  const rules = reactive<FormRules>({
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    descr: [
      { max: 20, message: '长度最多20个字符', trigger: 'blur' }
    ],
    phone: [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
    email: [{ type: 'email', message: '请输入正确邮箱', trigger: 'blur' }],
  })

  const options = [
    {
      value: 0,
      label: '男'
    },
    {
      value: 1,
      label: '女'
    }
  ]

  const lableList: Array<string> = ['专注设计', '很有想法', '辣~', '大长腿', '川妹子', '海纳百川']

  onMounted(() => {
    getDate()
  })

  const getDate = () => {
    const d = new Date()
    const h = d.getHours()
    let text = ''

    if (h >= 6 && h < 9) {
      text = '早上好'
    } else if (h >= 9 && h < 11) {
      text = '上午好'
    } else if (h >= 11 && h < 13) {
      text = '中午好'
    } else if (h >= 13 && h < 18) {
      text = '下午好'
    } else if (h >= 18 && h < 24) {
      text = '晚上好'
    } else if (h >= 0 && h < 6) {
      text = '很晚了，早点睡'
    }

    date.value = text
  }

  const edit = async () => {
    isEdit.value = !isEdit.value
    if (!isEdit.value) {
      if (!ruleFormRef.value) return
      await ruleFormRef.value.validate((valid) => {
        if (valid) {
          commonApi.editUSer(form)
              .then(() => {
                ElMessage.success('修改成功')
                userStore.setUserForm(form)
              })
              .catch(() => {
                ElMessage.error('操作失败')
              })
        }
      })
    }
  }

  const editPwd = async () => {
    isEditPwd.value = !isEditPwd.value
    if (!isEditPwd.value) {
      if (!pwdFormRef.value) return
      // 保存密码
      await pwdFormRef.value.validate((valid) => {
        if (valid) {
          commonApi.changePassword(pwdForm)
              .then(() => {
                ElMessage.success('密码修改成功')
              })
              .catch(() => {
                ElMessage.error('操作失败')
              })
        }
      })
    }
  }
</script>

<style lang="scss">
  .user {
    .icon {
      width: 1.4em;
      height: 1.4em;
      overflow: hidden;
      vertical-align: -0.15em;
      fill: currentcolor;
    }
  }
</style>

<style lang="scss" scoped>
  .page-content {
    width: 100%;
    height: 100%;
    padding: 0 !important;
    background: transparent !important;
    border: none !important;
    box-shadow: none !important;

    $box-radius: calc(var(--custom-radius) + 4px);

    .box-style {
      border: 1px solid var(--art-border-color);
    }

    .content {
      position: relative;
      display: flex;
      justify-content: space-between;
      margin-top: 10px;

      .left-wrap {
        width: 450px;
        margin-right: 25px;

        .user-wrap {
          position: relative;
          height: 600px;
          padding: 35px 40px;
          overflow: hidden;
          text-align: center;
          background: var(--art-main-bg-color);
          border-radius: $box-radius;

          .bg {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 200px;
            object-fit: cover;
          }

          .avatar {
            position: relative;
            z-index: 10;
            width: 80px;
            height: 80px;
            margin-top: 120px;
            object-fit: cover;
            border: 2px solid #fff;
            border-radius: 50%;
          }

          .name {
            margin-top: 20px;
            font-size: 22px;
            font-weight: 400;
          }

          .des {
            margin-top: 20px;
            font-size: 14px;
          }

          .outer-info {
            width: 300px;
            margin: auto;
            margin-top: 30px;
            text-align: left;

            > div {
              margin-top: 10px;

              span {
                margin-left: 8px;
                font-size: 14px;
              }
            }
          }

          .lables {
            margin-top: 40px;

            h3 {
              font-size: 15px;
              font-weight: 500;
            }

            > div {
              display: flex;
              flex-wrap: wrap;
              justify-content: center;
              margin-top: 15px;

              > div {
                padding: 3px 6px;
                margin: 0 10px 10px 0;
                font-size: 12px;
                background: var(--art-main-bg-color);
                border: 1px solid var(--art-border-color);
                border-radius: 2px;
              }
            }
          }
        }

        .gallery {
          margin-top: 25px;
          border-radius: 10px;

          .item {
            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }
          }
        }
      }

      .right-wrap {
        flex: 1;
        overflow: hidden;
        border-radius: $box-radius;

        .info {
          background: var(--art-main-bg-color);
          border-radius: $box-radius;

          .title {
            padding: 15px 25px;
            font-size: 20px;
            font-weight: 400;
            color: var(--art-text-gray-800);
            border-bottom: 1px solid var(--art-border-color);
          }

          .form {
            box-sizing: border-box;
            padding: 30px 25px;

            > .el-row {
              .el-form-item {
                width: calc(50% - 10px);
              }

              .el-input,
              .el-select {
                width: 100%;
              }
            }

            .right-input {
              margin-left: 20px;
            }

            .el-form-item-right {
              display: flex;
              align-items: center;
              justify-content: end;

              .el-button {
                width: 110px !important;
              }
            }
          }
        }
      }
    }
  }

  @media only screen and (max-width: $device-ipad-vertical) {
    .page-content {
      .content {
        display: block;
        margin-top: 5px;

        .left-wrap {
          width: 100%;
        }

        .right-wrap {
          width: 100%;
          margin-top: 15px;
        }
      }
    }
  }
</style>
