<template>
  <div class="form-container">
    <div>
      <h2 style="text-align:center">个人中心</h2>
      <div class="header">
        <el-button v-if="isEditing"
                   type="danger" round
                   @click="handleEditSave">保存</el-button>
        <el-button v-if="!isEditing"
                   type="success" round
                   @click="handleEditSave">编辑</el-button>
      </div>
    </div>

    <el-form ref="formRef"
             :model="userInfo"
             :rules="formRules"
             label-width="83px"
             :disabled="!isEditing">
      <!-- 用户名 -->
      <el-form-item label="用户名" prop="userName">
        <!--<el-input v-model="userInfo.userName" readonly disabled />-->
        <el-tag size="large" type="primary">{{ userInfo.userName }}</el-tag>
      </el-form-item>

      <!-- 公司 -->
      <el-form-item label="所属公司" prop="userName">
        <!--<el-input v-model="userInfo.customerName" readonly disabled />-->
        <el-tag size="large" type="success">{{ userInfo.customerName }}</el-tag>
      </el-form-item>

      <!-- 微信 -->
      <el-form-item label="微信" prop="weiXin">
        <el-input v-model="userInfo.weiXin" clearable />
      </el-form-item>

      <!-- 邮箱 -->
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="userInfo.email" clearable />
      </el-form-item>

      <!-- 手机号 -->
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="userInfo.mobile" clearable />
      </el-form-item>

      <!-- 密码 -->
      <el-form-item label="修改密码" prop="password">
        <el-input v-model="userInfo.password"
                  type="password"
                  show-password clearable
                  placeholder="不修改密码则留空" />
      </el-form-item>

      <!-- 确认密码（动态显示） -->
      <el-form-item v-if="userInfo.password"
                    label="确认密码"
                    prop="confPassword">
        <el-input v-model="userInfo.confPassword"
                  type="password"
                  show-password clearable
                  placeholder="请确认密码" />
      </el-form-item>

      <!-- 旧密码（动态显示） -->
      <el-form-item v-if="userInfo.password"
                    label="旧密码"
                    prop="oldPassword">
        <el-input v-model="userInfo.oldPassword"
                  type="password"
                  show-password clearable
                  placeholder="请输入旧密码" />
      </el-form-item>
    </el-form>
  </div>
</template>


<script setup>
  import { ref, reactive, onMounted, watch, inject, computed } from 'vue';
  import { Toast } from 'tdesign-mobile-vue';
  import { useRouter, useRoute } from 'vue-router'

  // 初始化加载数据
  onMounted(() => {
    loadingUser()
  });

  const $http = inject('$http')
  const router = useRouter()


  const userInfo = ref({
    userName: '',
    companyId: '',
    customerName: '',
    weiXin: '',
    email: '',
    mobile: '',
    password: '',
    confPassword: '',
    oldPassword: '',
    currentPassword: ''
  })
  const companies = ref([])
  // 初始化用户信息
  const loadingUser = () => {

    $http.post('Company/GetCompanyInfo', {
      IsAll: true,
      ID: 0
    })
      .then(rs => {
        //console.log(rs)
        if (rs.data.isok) {
          companies.value = rs.data.response
          companies.value.forEach(item => {
            item.label = item.customerName
            item.value = item.id
            /*            product.options.push({
                          label: item.customerName,
                          value: item.customerName
                        })*/
          });
          var formdata = {
            IsAll: false,
            ID: localStorage.getItem('uid')
          }
          // 调用API获取用户信息
          $http.post('Users/GetUserInfo', formdata)
            .then(rs => {
              //console.log(rs)
              if (rs.data.isok) {
                userInfo.value = rs.data.response
                const companyMap = new Map(companies.value.map(company => [company.id, company.customerName]));
                userInfo.value.customerName = companyMap.get(userInfo.value.companyId);
                //console.log(userInfo.value)
              } else {
                Toast(rs.data.message)
              }
            })
            .catch(error => {
              // 处理错误情况
              console.error(error);
            })
            .finally(() => {

            })
        } else {
          Toast(rs.data.message)
        }
      })
      .catch(error => {
        // 处理错误情况
        console.error(error);
      })
      .finally(() => {

      })

  }


  // TODO 头像修改（未做）
  const openAvatarDialog = (user) => {
    console.log(user)
  }


  // 重置密码
  const handleResetPassword = (user) => {
    // TODO: 调用重置密码API
    var us = {
      id: user.id
    }
    $http.post('Users/NewPassWord', us)
      .then(rs => {
        //console.log(rs)
        if (rs.data.isok) {


        } else {
          Toast(rs.data.message)
        }
      })
      .catch(error => {
        // 处理错误情况
        console.error(error);
      })
  };

  // 表单状态控制
  const isEditing = ref(false)
  const formRef = ref(null)


  // 验证规则
  const validatePassword = (rule, value, callback) => {
    if (value) {
      const reg = /^[\w!@#$%^&*()]{6,20}$/
      if (!reg.test(value)) {
        callback(new Error('6-20位英文/数字/特殊字符'))
      } else if (userInfo.value.confPassword && value != userInfo.value.confPassword) {
        callback(new Error('两次输入密码不一致'))
      }
    }
    callback()
  }

  const formRules = reactive({
    email: [
      { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ],
    mobile: [
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    password: [
      { validator: validatePassword, trigger: 'blur' }
    ],
    confPassword: [
      { required: true, message: '请再次输入密码', trigger: 'blur' },
      {
        validator: (_, value, cb) => {
          if (value !== userInfo.value.password) {
            cb(new Error('两次输入密码不一致'))
          }
          cb()
        }, trigger: 'blur'
      }
    ],
    oldPassword: [
      { required: true, message: '请输入旧密码', trigger: 'blur' }
    ]
  })

  // 处理编辑/保存
  const handleEditSave = () => {
    if (!isEditing.value) {
      isEditing.value = true
      return
    }
    let form = {
      Id: userInfo.value.id,
      UserName: userInfo.value.userName,
      CompanyId: userInfo.value.companyId,
      Mobile: userInfo.value.mobile,
      WeiXin: userInfo.value.weiXin,
      Email: userInfo.value.email,
    }
    //Toast("保存成功！")

    //return
    if (userInfo.value.password) {
      $http.post('Login/Login', {
        username: userInfo.value.userName,
        password: userInfo.value.oldPassword
      })
        .then(rs => {
          //console.log(rs)
          if (rs.data.isok) {
            $http.post('Users/EditUser', form)
              .then(rs => {
                //console.log(rs)
                let psw = {
                  Id: userInfo.value.id,
                  PlaintextPwd: userInfo.value.confPassword
                }
                if (rs.data.isok) {
                  $http.post('Users/ResetPassWord', psw)
                    .then(rs => {
                      //console.log(rs)
                      if (rs.data.isok) {
                        isEditing.value = false
                        Toast("保存成功！")
                        setTimeout(() => {
                          router.push('/login')
                        }, 233)
                      } else {
                        Toast(rs.data.message)
                      }

                    })
                    .catch(error => {
                      // 处理错误情况
                      console.error(error);
                    })

                } else {
                  Toast(rs.data.message)
                }

              })
              .catch(error => {
                // 处理错误情况
                console.error(error);
              })
          } else {
            Toast(rs.data.message)
          }

        })
        .catch(error => {
          // 处理错误情况
          console.error(error);
        })
    } else {

      $http.post('Users/EditUser', form)
        .then(rs => {
          //console.log(rs)
          if (rs.data.isok) {
            isEditing.value = false
            Toast("保存成功！")
          } else {
            Toast(rs.data.message)
          }

        })
        .catch(error => {
          // 处理错误情况
          console.error(error);
        })
    }


  }

</script>


<style scoped>
  .form-container {
    max-width: 600px;
    padding: 20px;
    /*margin: 20px;*/
  }

  .header {
    margin-bottom: 20px;
    text-align: left;
  }

  /* PC端样式 */
  @media (min-width: 1024) {

  }
</style>
