<template>
  <div>
    <div class="userInfoBox">
      <tableTitle :name="tableDivTitle"/>
      <div class="userInfoTabs">
        <el-tabs :tab-position="tabPosition" style="height:550px" class="demo-tabs">
          <el-tab-pane label="用户信息">
            <el-form :model="infoform" ref="infoform" :rules="infoFormRules" autocomplete="off" label-position="left">
              <div class="infoBox">
                <div>
                  <!-- <img :src="user.avatar" class="avatar"> -->
                  <el-form-item label="头像：" prop="avatar" :label-width="formLabelWidth" :class="['custom-form-item']" class="custom-align-right">
                    <div class="uploaderBox">
                      <!--图片上传组件 start ------------------------------------------------------------>
                      <div class="avatar-upload-container" @mouseenter="hovering = true" @mouseleave="hovering = false">
                        <!-- 上传组件 -->
                        <el-upload
                          class="avatar-uploader"
                          action="#"
                          :show-file-list="false"
                          :before-upload="beforeAvatarUpload"
                        >
                          <!-- 预览图片 -->
                          <img v-if="avatarUrl" :src="avatarUrl" class="avatar">
                          <!-- 上传图标 -->
                          <!-- <i v-else class="el-icon-plus avatar-uploader-icon"></i> -->
                          <div v-else class="chooseImgDiv">
                            <div>
                              <img src="@/assets/public/upload/noImage.png">
                              <div>选择图片</div>
                            </div>
                          </div>
                          <input type="hidden" v-model="infoform.avatar">
                        </el-upload>
                        <!-- 删除按钮，当鼠标悬浮时显示 -->
                        <div v-if="hovering && avatarUrl" class="delete-button" @click="handleDelete">
                          <i class="el-icon-delete"></i>
                        </div>
                      </div>
                      <!--图片上传组件 end ------------------------------------------------------------>
                    </div>
                  </el-form-item>
                  <el-form-item label="昵称：" :label-width="formLabelWidth" prop="nickname" class="custom-align-right">
                    <el-input v-model="infoform.nickname" autocomplete="off" placeholder="请输入用户昵称.."></el-input>
                  </el-form-item>
                </div>
              </div>
            </el-form>
            <div class="infoBtnBox">
              <el-button type="primary" @click="changeInfo">保存</el-button>
            </div>
          </el-tab-pane>

          <el-tab-pane label="修改密码">
            <el-form ref="form" :model="form" :rules="loginRules" class="login-form" autocomplete="on" label-position="left">
              <!--现有密码 start------------------------------------------>
              <el-tooltip v-model="capsTooltip1" content="大小写已开启！" placement="right" manual>
                <div class="PasswordBox">
                  <div class="PasswordTitle">现有密码：</div>
                  <el-form-item prop="password">
                    <div class="PasswordBody">
                      <el-input
                        :key="passwordType1"
                        ref="password1"
                        v-model="form.password"
                        :type="passwordType1"
                        placeholder="请输入密码"
                        name="password"
                        tabindex="2"
                        autocomplete="off"
                        @blur="capsTooltip1 = false"
                      />
                      <span class="show-pwd" @click="showPwd(1)">
                        <svg-icon :icon-class="passwordType1 === 'password' ? 'eye' : 'eye-open'" />
                      </span>
                    </div>
                  </el-form-item>
                </div>
              </el-tooltip>
              <!--现有密码 end------------------------------------------>
              <!--新密码 start------------------------------------------>
              <el-tooltip v-model="capsTooltip2" content="大小写已开启！" placement="right" manual>
                <div class="PasswordBox">
                  <div class="PasswordTitle">新密码：</div>
                  <el-form-item prop="new_password">
                    <div class="PasswordBody">
                      <el-input
                        :key="passwordType2"
                        ref="password2"
                        v-model="form.new_password"
                        :type="passwordType2"
                        placeholder="请输入密码"
                        name="password"
                        tabindex="2"
                        autocomplete="off"
                        @blur="capsTooltip2 = false"
                      />
                      <span class="show-pwd" @click="showPwd(2)">
                        <svg-icon :icon-class="passwordType2 === 'password' ? 'eye' : 'eye-open'" />
                      </span>
                    </div>
                  </el-form-item>
                </div>
              </el-tooltip>
              <!--新密码 end------------------------------------------>
              <!--新密码 start------------------------------------------>
              <el-tooltip v-model="capsTooltip3" content="大小写已开启！" placement="right" manual>
                <div class="PasswordBox">
                  <div class="PasswordTitle">确认新密码：</div>
                  <el-form-item prop="new_password1">
                    <div class="PasswordBody">
                      <el-input
                        :key="passwordType3"
                        ref="password3"
                        v-model="form.new_password1"
                        :type="passwordType3"
                        placeholder="请输入密码"
                        name="password"
                        tabindex="2"
                        autocomplete="off"
                        @blur="capsTooltip3 = false"
                      />
                      <span class="show-pwd" @click="showPwd(3)">
                        <svg-icon :icon-class="passwordType3 === 'password' ? 'eye' : 'eye-open'" />
                      </span>
                    </div>
                  </el-form-item>
                </div>
              </el-tooltip>
              <!--新密码 end------------------------------------------>
            </el-form>
            <div class="infoBtnBox">
                <!-- <el-button type="info" @click="clearInput">重置</el-button> -->
                <el-button type="primary" @click="changePassword">保存</el-button>
              </div>
              </el-tab-pane>
              <!--企业信息 start------------------------------------------>
              <el-tab-pane label="企业信息" v-if="creatNews_user_type == '3'">
              <el-form :model="companyform" ref="companyform" :rules="companyRules" autocomplete="off" label-position="left">
                <div class="infoBox">
                <div>
                  <!-- <img :src="user.avatar" class="avatar"> -->
                  <el-form-item label="公司名称：" :label-width="formLabelWidth" prop="business_name" class="custom-align-right">
                  <el-input v-model="companyform.business_name" autocomplete="off" placeholder="请输入公司名称"></el-input>
                  </el-form-item>
                  <el-form-item label="所属行业：" :label-width="formLabelWidth" prop="company_hy_id" class="custom-align-right">
                  <el-select v-model="companyform.company_hy_id" clearable placeholder="请输入所属行业" >
                    <el-option v-for="item in company_hy_id" :key="item.hyid" :label="item.hyname" :value="item.hyid">
                    </el-option>
                  </el-select>
                  </el-form-item>
                  <el-form-item label="公司规模：" :label-width="formLabelWidth" prop="company_size" class="custom-align-right">
                  <el-select v-model="companyform.company_size" clearable placeholder="请输入公司规模" >
                    <el-option v-for="item in company_size" :key="item.evalue" :label="item.ename" :value="item.evalue">
                    </el-option>
                  </el-select>
                  </el-form-item>
                  <el-form-item label="公司性质：" :label-width="formLabelWidth" prop="company_nature" class="custom-align-right">
                  <el-select v-model="companyform.company_nature" clearable placeholder="请输入公司性质" >
                    <el-option v-for="item in company_nature" :key="item.id" :label="item.nature_name" :value="item.id">
                    </el-option>
                  </el-select>
                  </el-form-item>
                  <el-form-item label="公司简介：" :label-width="formLabelWidth" prop="introduction" class="custom-align-right">
                  <el-input v-model="companyform.introduction" autocomplete="off" type="textarea" :rows="2"
                    placeholder="请输入公司简介"> </el-input>
                  </el-form-item>
                  <el-form-item label="公司网址：" :label-width="formLabelWidth" prop="company_url" class="custom-align-right">
                  <el-input v-model="companyform.company_url" autocomplete="off" 
                    placeholder="请输入公司网址"></el-input>
                  </el-form-item>
                  <el-form-item label="地址：" :label-width="formLabelWidth" prop="address_arr_id" class="custom-align-right">
                  <CityCascader v-model="companyform.address_arr_id" @update-city-id="update_city_arr_id" ></CityCascader> 
                  <!-- <el-select v-model="form.address_arr_id" placeholder="请选择省" @change="createjob_pronvice"> -->
                  <!-- <el-option v-for="item in address_arr_id" :key="item.id" :label="item.name" :value="item.id"> -->
                  <!-- </el-option> -->
                  <!-- </el-select> -->
                  <br>
                  <el-input v-model="companyform.address" :label-width="formLabelWidth" placeholder="请输入公司地址"></el-input>
                  </el-form-item>
                </div>
                </div>
              </el-form>
            <div class="infoBtnBox">
              <!-- <el-button type="info" @click="clearInput">重置</el-button> -->
              <el-button type="primary" @click="changeCompany">保存</el-button>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script>
//引入公用样式
import '@/styles/global.less';
//表格标题
import tableTitle from './components/tableTitle';
import CityCascader from './components/CityCascader';
import { formatLocalDate } from '@/utils/public';
import { getWebSiteId, getUseType } from '@/utils/auth'
export default {
  components: {
    tableTitle,//表格标题
    CityCascader,//城市选择器
  },
  data() {
    // 配置验证规则：用于表单验证
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码不能低于6位！'))
      } else {
        callback()
      }
    }
    const validateEmpty = (rule,value,callback) => {
      if (!value || value.trim() === "") {
        callback(new Error('该项不能为空！'));
      } else {
        callback();
      }
    }
    //表单验证
    const validateCompanyEmpty = (rule, value, callback) => {
      if (value.length == 0) {
      callback(new Error('该项不能为空！'))
      } else {
      callback()
      }
    }
    return {
      tableDivTitle:"修改个人信息",
      tabPosition:"left",
      formLabelWidth:"120px",
      //修改用户信息
      infoform:{
        avatar:"",
        nickname:""
      },
      avatarUrl:"",//头像缩略图
      hovering:false,//鼠标悬浮状态
      infoFormRules:{
        avatar: [{ required: true, trigger: 'blur', validator: validateEmpty }],
        nickname: [{ required: true, trigger: 'blur', validator: validateEmpty }]
      },
      //修改密码
      form:{
        password:"",
        new_password:"",
        new_password1:""
      }, 
      // 修改企业信息
      companyform:{
        business_name:"",//公司名称
        company_hy_id:"",//所属行业
        company_size:"",//公司规模
        company_nature:"",//公司性质
        introduction:"",//公司简介
        real_name:"",//联系人
        mobile:"",//联系电话
        company_url:"",//公司网址
        address_arr_id:[],//地址 
        address:""//具体地址
      },
      creatNews_user_type: '0',//判断用户类型'
      capsTooltip1: false,//显示大小写提示
      capsTooltip2: false,
      capsTooltip3: false,
      passwordType1: 'password',//密码域默认type 当显示密码的时候改为text
      passwordType2: 'password',//密码域默认type 当显示密码的时候改为text
      passwordType3: 'password',//密码域默认type 当显示密码的时候改为text
      loginRules: { //配置from表单验证规则
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        new_password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        new_password1: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      companyRules: { //配置from表单验证规则
        // 公司名称
        business_name: { required: true, trigger: 'blur', validator: validateCompanyEmpty },
        // 所属行业
        company_hy_id: { required: true, trigger: 'blur', validator: validateCompanyEmpty },
        // 公司规模
        company_size: { required: true, trigger: 'blur', validator: validateCompanyEmpty },
        // 公司简介
        introduction: { required: true, trigger: 'blur', validator: validateCompanyEmpty },
        // 联系人
        real_name: { required: true, trigger: 'blur', validator: validateCompanyEmpty },
        // 联系电话
        mobile: { required: true, trigger: 'blur', validator: validateCompanyEmpty },
        // 地址
        address_arr_id: { required: true, trigger: 'blur', validator: validateCompanyEmpty },
        // 具体地址
        address: { required: true, trigger: 'blur', validator: validateCompanyEmpty },
      },
    }
  },
  mounted() {
    this.creatNews_user_type = getUseType()
    this.getUserInfo()
    this.company_hy_id()
    this.company_size()
    this.company_nature()
    this.address_arr_id()
    this.getCompanyInfo()
  },
  methods: {
    //0.全局操作 start ---------------------------------------->
    //获取用户身份信息
    getUserInfo(){
      this.$store.dispatch('public/getInfo').then(res=> {
        console.log(res)
        this.avatarUrl = res.data.avatar;
        this.infoform.avatar = res.data.avatar;
        this.infoform.nickname = res.data.nickname;
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '网络错误，请重试！'
        });
      })
    },
    //0.全局操作 end ---------------------------------------->
    //1.修改密码 start ---------------------------------------->
    //1.1 修改用户密码
    changePassword(){
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$store.dispatch('public/changePassword',this.form).then(res=> {
            //console.log(res)
            if(res.code == 200){
              this.$message({
                type: 'success',
                message: "密码修改成功！"
              });
              this.clearInput();
            }else{
              this.$message({
                type: 'warning',
                message: res.message
              });
            } 
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '网络错误，请重试！'
            });
          })
        }else{
          this.$message.error('请填写完整信息！');
        }
      })
    },
    // 切换密码框的显示与隐藏
    showPwd(num) {
      const passwordTypeKey = 'passwordType' + num; // 动态生成 passwordType 的键
      const passwordRefKey = 'password' + num; // 动态生成 password 的引用

      // 切换密码类型
      if (this[passwordTypeKey] === 'password') {
        this[passwordTypeKey] = ''; // 显示密码
      } else {
        this[passwordTypeKey] = 'password'; // 隐藏密码
      }

      // 使用 $nextTick 聚焦到对应的密码输入框
      this.$nextTick(() => {
        this.$refs[passwordRefKey].focus(); // 聚焦到对应的密码输入框
      });
    },
    //清空输入列表
    clearInput(){
      this.form = {
        password:"",
        new_password:"",
        new_password1:""
      }
    },
    //1.修改密码 end ---------------------------------------->
    //2.修改头像和昵称 start ---------------------------------------->
    //2.1上传图片操作
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
        return false;
      }

      const formData = new FormData();
      formData.append('file', file);

      this.$store.dispatch('pool/uploadFile',formData).then(res=> {
        this.avatarUrl = res.data.imgUrl;//显示缩略图
        this.infoform.avatar = res.data.imgUrl;//提供表单地址
        console.log(res.data.imgUrl)
        console.log(this.infoform.avatar)
      }).catch(() => {
        this.$message({
          type: 'warning',
          message: '网络错误，请重试！'
        });
      })

      // 阻止默认的上传行为
      return false;
    },
    //2.2 删除图片
    handleDelete() {
      // 删除图片
      this.avatarUrl = ''; // 清空图片 URL
    },
    //2.3 修改用户信息
    changeInfo(){
      console.log(this.infoform)
      this.$refs.infoform.validate(valid => {
        if (valid) {
          this.$store.dispatch('user/updateUserAvatarNickname',this.infoform).then(res=> {
            if(res.code == 200){
              this.$message.success("修改成功！");
              //更新store中的头像和昵称
              this.$store.commit('user/SET_AVATAR', this.infoform.avatar);
              this.$store.commit('user/SET_NAME', this.infoform.nickname);
            }
          }).catch(() => {  
            this.$message.error('网络错误，请重试！');
          })
        }else{
          this.$message.error('请填写完整信息！');
        }
      })
    },
    //2.修改头像和昵称 end ---------------------------------------->
    // 3.企业信息 start ---------------------------------------->//1.4更新详细地址
      // 12.获取公司分类
      company_hy_id(value) {
      this.$store.dispatch('news/getIndustry').then(res => {
        this.company_hy_id = res.data;
      })
      },
      //13.获取公司规模
      company_size(value) {
      this.$store.dispatch('news/getCompanySize').then(res => {
        this.company_size = res.data;
      })
      },
      //14.获取公司性质
      company_nature(value) {
      this.$store.dispatch('news/getCompanyNature').then(res => {
        this.company_nature = res.data;
      })
      },
      // 15.获取地址
      address_arr_id(value) {
      this.$store.dispatch('news/getJobRecruitingArea').then(res => {
        this.address_arr_id = res.data;
      })
      },
      getCompanyInfo(){
        this.$store.dispatch('news/getJobCompany', {}).then(res => {
        console.log('-----------res------------------',res);
        
        this.companyform.address_arr_id = Array.isArray(res.data.address_arr_id) ? res.data.address_arr_id : JSON.parse(res.data.address_arr_id);
        this.companyform.business_name = res.data.business_name;
        this.companyform.company_hy_id = res.data.company_hy_id;
        this.companyform.company_size = res.data.company_size;
        this.companyform.company_nature = res.data.company_nature;
        this.companyform.introduction = res.data.introduction;
        this.companyform.company_url = res.data.company_url;
        this.companyform.address = res.data.address;
        })
      },
      update_city_arr_id(value) {
      console.log("行政区划ID已更新:", value);
      this.form.city_arr_id = value;
      },
      //1.3 清理表单
      cleatForm(type) {
      if (type == 2) {
        //使用了外链，进行部分表单清理
        //this.form.cat_arr_id = "";
        this.form.address_arr_id = [];
        this.form.business_name = "";
        this.form.company_hy_id = "";
        this.form.company_size = "";
        this.form.company_nature = "";
        //this.form.author = "";
        this.form.introduction = "";
        this.form.company_url = "";
        this.form.address = "";
      }
      },
      changeCompany(value){
      console.log(this.companyform)
      
      this.$store.dispatch('news/upJobCompany', this.companyform).then(res => {
        if (res.code == 200) { 
        //汇报结果
        this.$message({
          type: 'success',
          message: '已成功修改公司信息！'
        });
        this.cleatForm(2);
        //返回列表页
        // this.returnPage()
        } else {
        this.$message({
          type: 'error',
          message: ": '发布失败！'.".this.$message
        });
        }
      }).catch(() => {
        this.$message({
        type: 'info',
        message: '网络错误，请重试！'
        });
      })
      }
  //3.企业信息 end ---------------------------------------->
  }
}
</script>

<style scoped lang="less">
  @avatarBorderColor:#E1E2E9;
  @spacingPx:30px;

  .userInfoBox {
    margin: @spacingPx;
    border-radius: 20px;
    background: #fff;
    border: 1px solid #E9EDF7;
    padding: @spacingPx - 10px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    padding-bottom: @spacingPx;
    .userInfoTabs {
      padding: 20px 40px 20px 0;
      background: #F5F7FB
    }
    .avatar {
      border-radius: 50%;
      width: 140px;
      height: 140px;
      border: 1px solid @avatarBorderColor;
      border-radius: 12px;
      padding:15px;
    }
    .show-pwd{
      margin-left: @spacingPx;
    }
    .infoBox {
      margin-top: @spacingPx;
    }
    
    .infoInput {
      flex: 1;
    }
    .infoPassword {
      display: flex;
      align-items: center;
    }
  }

  .inputBox {
    margin-bottom: @spacingPx;
    .inputIcon {
      width: 24px;
      height: 24px;
      margin: 0 @spacingPx - 10px;
    }
    .inputIconSmall {
      width: 18px;
      height: 18px;
    }
  }
  .PasswordBox {
    display: flex;
    align-items: center;
    margin-top: @spacingPx;
    .el-form-item {
      flex: 1;
    }
    .PasswordTitle {
      width:120px;
      text-align: right;
      margin-right: 10px;
      margin-bottom:22px;
      font-size: 14px;
      color: #666;
      font-weight: bold;
    }
    .PasswordBody {
      flex: 1;
      display: flex;
      align-items: center;
    }
  }
  .infoBtnBox {
    margin-top: @spacingPx;
    padding-bottom: @spacingPx;
    text-align: center;
  }
  // ----------------------企业信息下拉框宽度---------------------->
  .el-select {
    // text-align: right; /* 设置标签文字右对齐 */
    width: 100%; /* 设置标签宽度 */; 
  }
  // ----------------------企业信息下拉框宽度---------------------->
  //执行v-deep穿透scope选择器 start------------------------------------------------------------>*/
  ::v-deep .custom-form-item > .el-form-item__label {
    line-height: 140px !important;
  }
  ::v-deep .custom-textarea .el-textarea__inner {
    resize: none; /* 禁止用户拖拽调整大小 */
  }
  ::v-deep .custom-align-right .el-form-item__label {
    text-align: right; /* 设置标签文字右对齐 */
  }
  //执行v-deep穿透scope选择器 end------------------------------------------------------------>*/
</style>