<template>
  <div>
    <el-row :gutter="20" style="margin-top: 10px">
      <el-col :span="8" v-for="(item, index) in userinfo" :key="index">
        <div class="grid-content bg-purple">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>个人中心</span>
            </div>
            <div class="name-role">
              <el-row>
                <el-avatar
                  @click="triggerFileInput('avatar')"
                  :src="Avatar"
                  style="width: 100px; height: 100px; cursor: pointer"
                ></el-avatar>
                <!-- 头像文件输入框 -->
                <input
                  ref="avatarInput"
                  type="file"
                  accept="image/*"
                  @change="handleFileChange($event, 'avatar')"
                  style="
                    position: absolute;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    opacity: 0;
                    cursor: pointer;
                    border-radius: 50%;
                  "
                />
              </el-row>
              <span class="sender">姓名 - {{ item.userName }}</span>
            </div>
            <div class="registe-info">
              <span class="registe-info">
                状态：
                <li class="fa fa-clock-o"></li>
                {{
                  item.idCard == null || item.idCard == "" ? "未实名" : "已实名"
                }}
              </span>
            </div>
            <el-divider></el-divider>
            <div class="personal-relation">
              <div class="relation-item">
                手机号:
                <div style="float: right; padding-right: 20px">
                  {{ item.phone }}
                </div>
              </div>
            </div>
            <div class="personal-relation">
              <div class="relation-item">
                驾驶证:
                <div style="float: right; padding-right: 20px">
                  <img
                    v-if="dataForm.DriverLicense"
                    :src="dataForm.DriverLicense"
                    style="width: 50%"
                  />
                  <span v-else>未上传</span>
                </div>
              </div>
            </div>
            <div class="personal-relation">
              <div class="relation-item">
                身份信息:
                <div style="float: right; padding-right: 20px">
                  {{ item.idCard }}
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </el-col>
      <el-col :span="16">
        <div class="grid-content bg-purple">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>实名认证</span>
            </div>
            <div>
              <el-form
                label-width="80px"
                v-model="dataForm"
                size="small"
                label-position="right"
              >
                <el-form-item label="姓名" prop="nickName">
                  <el-input
                    auto-complete="off"
                    v-model="dataForm.UserName"
                  ></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                  <el-input
                    auto-complete="off"
                    v-model="dataForm.Phone"
                  ></el-input>
                </el-form-item>
                <el-form-item label="身份证" prop="idCard">
                  <el-input maxlength="18" v-model="dataForm.idCard"></el-input>
                </el-form-item>
                <el-form-item label="驾驶证" prop="DriverLicense">
                  <div class="upload-container">
                    <el-input
                      v-model="dataForm.DriverLicense"
                      placeholder="请上传驾驶证照片"
                      readonly
                    ></el-input>
                    <el-button
                      type="primary"
                      size="small"
                      style="margin-left: 10px"
                      @click="triggerFileInput('license')"
                    >
                      上传驾驶证
                    </el-button>
                    <!-- 驾驶证文件输入框 -->
                    <input
                      ref="licenseInput"
                      type="file"
                      accept="image/*"
                      style="display: none"
                      @change="handleFileChange($event, 'license')"
                    />
                  </div>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button size="mini" type="primary" @click="RealUser"
                  >提交</el-button
                >
                <el-button size="mini" type="warning" @click="resetForm"
                  >重置</el-button
                >
              </div>
            </div>
          </el-card>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  data() {
    return {
      userinfo: [],
      Avatar:
        "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",
      dataForm: {
        UserName: "",
        RealUser: "",
        idCard: "",
        DriverLicense: "",
        Phone: "",
      },
      uploadAPI: "http://8.141.3.231:40061/api/index.php",
    };
  },

  created() {
    this.fetchOrderPact();
  },

  methods: {
    // 触发文件选择
    triggerFileInput(type) {
      console.log(2222);
      if (type === "avatar") {
        this.$refs.avatarInput.click();
      } else if (type === "license") {
        this.$refs.licenseInput.click();
      }
    },

    // 处理文件上传
    async handleFileChange(event, type) {
      try {
        const file = event.target.files[0];
        if (!file) return;

        // 验证文件类型
        if (!file.type.startsWith("image/")) {
          this.$message.error("请上传图片文件");
          return;
        }

        // 验证文件大小（最大5MB）
        if (file.size > 5 * 1024 * 1024) {
          this.$message.error("图片大小不能超过5MB");
          return;
        }

        const formData = new FormData();
        formData.append("image", file);
        formData.append("token", "1c17b11693cb5ec63859b091c5b9c1b2");

        // 显示上传加载状态
        const loading = this.$loading({
          lock: true,
          text: "上传中...",
          spinner: "el-icon-loading",
        });

        const response = await fetch(this.uploadAPI, {
          method: "POST",
          body: formData,
        });

        const data = await response.json();

        if (data.code === 200 && data.url) {
          if (type === "avatar") {
            this.Avatar = data.url;
            // 这里可以添加更新用户头像的API调用
            this.$message.success("头像上传成功");
          } else if (type === "license") {
            this.dataForm.DriverLicense = data.url;
            this.$message.success("驾驶证上传成功");
          }
        } else {
          throw new Error(data.message || "上传失败");
        }
      } catch (error) {
        console.error("上传失败:", error);
        this.$message.error(error.message || "上传失败，请重试");
      } finally {
        // 关闭加载状态
        if (this.$loading) {
          this.$loading().close();
        }
        // 清空文件输入框
        event.target.value = "";
      }
    },

    // 获取用户信息
    async fetchOrderPact() {
      try {
        const userId = window.localStorage.getItem("userId");
        if (!userId) {
          this.$message.warning("请先登录");
          return;
        }

        const result = await this.$API.userinfo.getInfo({ UserId: userId });

        if (result.status === 200 && result.data && result.data.length > 0) {
          this.userinfo = result.data;
          const userData = result.data[0];

          // 更新表单数据
          this.dataForm = {
            UserName: userData.userName || "",
            idCard: userData.idCard || "",
            DriverLicense: userData.driverLicense || "",
            Phone: userData.phone || "",
          };

          // 如果有头像，更新头像
          if (userData.avatar) {
            this.Avatar = userData.avatar;
          }
        } else {
          throw new Error(result.message || "获取用户信息失败");
        }
      } catch (error) {
        console.error("获取用户信息失败:", error);
        this.$message.error(error.message || "获取用户信息失败，请重试");
      }
    },

    // 提交实名认证
    async RealUser() {
      try {
        if (!this.validateForm()) {
          return;
        }

        const userId = window.localStorage.getItem("userId");
        if (!userId) {
          this.$message.warning("请先登录");
          return;
        }

        const data = {
          UserId: userId,
          Phone: this.dataForm.Phone,
          UserName: this.dataForm.UserName,
          idCard: this.dataForm.idCard,
          DriverLicense: this.dataForm.DriverLicense,
          avatar: this.Avatar,
        };

        const result = await this.$API.userinfo.RealUser(data);

        if (result.status === 200) {
          window.localStorage.setItem("userName", this.dataForm.UserName);
          this.$message.success(result.message || "实名认证成功");
          await this.fetchOrderPact(); // 刷新用户信息
        } else {
          throw new Error(result.message || "实名认证失败");
        }
      } catch (error) {
        console.error("实名认证失败:", error);
        this.$message.error(error.message || "实名认证失败，请重试");
      }
    },

    // 表单验证
    validateForm() {
      if (!this.dataForm.UserName) {
        this.$message.warning("请输入姓名");
        return false;
      }
      if (!this.dataForm.Phone) {
        this.$message.warning("请输入手机号");
        return false;
      }
      if (!this.dataForm.idCard) {
        this.$message.warning("请输入身份证号");
        return false;
      }
      if (!this.dataForm.DriverLicense) {
        this.$message.warning("请上传驾驶证照片");
        return false;
      }
      return true;
    },

    // 重置表单
    resetForm() {
      this.dataForm = {
        UserName: "",
        RealUser: "",
        idCard: "",
        DriverLicense: "",
        Phone: "",
      };
      this.Avatar =
        "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png";
    },
  },
};
</script>

<style lang="scss" scoped>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

.box-card {
  width: 100%;
}

.name-role {
  font-size: 16px;
  padding: 5px;
  text-align: center;
}

.sender {
  text-align: center;
}

.registe-info {
  text-align: center;
  padding-top: 10px;
}

.personal-relation {
  font-size: 16px;
  padding: 0px 5px 15px;
  margin-right: 1px;
  width: 100%;
}

.relation-item {
  padding: 12px;
}

.dialog-footer {
  padding-top: 10px;
  padding-left: 10%;
}

.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}

.el-col {
  border-radius: 4px;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}

.upload-container {
  display: flex;
  align-items: center;
}
</style>
