<template>
  <div class="set-container">
    <div style="width: 100%">
      <div class="user-info">
        <img
          class="certificate"
          v-if="state.info.certificate"
          :src="state.info.certificate"
        />
        <div class="p">
          <div class="flex" >
            <span>用户名</span>
            <span>{{ state.info.NickName }}</span>
          </div>
          <div class="flex items-center" style="margin-left: 10px" >
            <n-image-group   v-if="state.certList.length">
              <n-space
              >
              <n-popover v-for="item in state.certList" class="imgBox"  placement="right" trigger="hover" :show-arrow="false">
                  <template #trigger>
                    <n-image
                      width="18"
                      :class="[ item.isGot=== 1?'':'imgBoxChild']"
                      style="margin-right: 5px;margin-top: 2px"
                      :src="item.thumbnail"
                      preview-disabled
                    />
                  </template>
                  <div >
                    <div style="font-weight: bold" >
                      <span style="padding-right: 8px" >证书名称:</span>
                      <span>{{ item.name }}</span>
                    </div>
                    <div style="font-weight: bold">
                      <span style="padding-right: 8px" >证书来源:</span>
                      <span>{{ item.examTaskName }}</span>
                    </div>
                    <div style="font-weight: bold">
                      <span style="padding-right: 8px">状态:</span>
                      <span>{{ item.validStatus }}</span>
                    </div>
                    <div style="font-weight: bold">
                      <span style="padding-right: 8px">获得时间:</span>
                      <span>{{ item.receiveTime }}</span>
                    </div>
                  </div>
                </n-popover>
                
              </n-space>
            </n-image-group>
          </div>
        </div>
        <div class="p">
          <span>手机号</span>
          <span>{{ state.info.TelNum }}</span>
        </div>
        <!-- <div class="p" v-if="state.info.PositionUsers">
          <span>归属部门及岗位</span>
          <n-grid x-gap="12" :cols="1">
            <n-gi class="theme-color" v-for="item in state.info.PositionUsers" :key="item"
              >{{ item.DepartmentName }} - {{ item.PositionName }}</n-gi
            >
          </n-grid>
        </div>
        <div class="p">
          <span>工作年龄</span>
          <span>{{ state.info.WorkYear || "0" }} 年</span>
        </div> -->
        <!-- <div class="p">
          <span>邮箱</span>
          <span>{{ state.info.MailAccount }}</span>
        </div> -->
        <div class="p">
          <span>固定分辨率</span>
          <span
            ><n-switch
            v-model:value="state.ResolutionRatio"
              @change="changeResolutionRatio"
              class="switch-btn"
          /></span>
        </div>
        <div v-if="state.ResolutionRatio" class="p">
          <span>字体大小</span>
          <div style="width: 300px">    <n-slider v-model:value="fontValue" :step="0.1" @dragend="dragend"  :tooltip="false" :max="0.4" :marks="customMarks" range /></div>
        </div>
        <div class="p">
          <span>员工近照</span>
          <span>
            <n-upload
              class="upload-box"
              v-model:file-list="state.recentImg"
              :custom-request="customRequest"
              :max="1"
              list-type="image-card"
              @before-upload="beforeUpload"
              @remove="handleRemove"
              @finish="handleUploadFinish"
              @error="handleUploadError"
            >
              <n-upload-dragger>
                <div>
                  <n-icon size="45" color="#0067ff" :depth="3">
                    <add-icon />
                  </n-icon>
                </div>
              </n-upload-dragger>
            </n-upload>
          </span>
        </div>
      </div>
      <div class="avatar-top">
        <span>上传头像</span>
        <div class="avatar-box">
          <div class="upload-img">
            <Upload
              ref="uploadImg"
              :maxCount="1"
              v-model:uploadVal="avatarUpload"
              :source="'avatar'"
              :mask="state.uid"
            />
          </div>

          <img
            v-for="(item, index) in imgList"
            :src="item + '?x-oss-process=image/resize,w_158,h_158'"
            :key="index"
            class="img-avatar"
            :class="isCheck == index ? 'border-active' : ''"
            @click="getImg(item, index)"
          />
        </div>
        <div class="btn-box">
          <a-button
            class="set-btn primary-btn"
            @click="updateImg"
            :disabled="!state.avatar"
            >确认</a-button
          >
        </div>
      </div>
    </div>
    <!-- <div>
      <div class="pass-box" v-if="isPwd">
        <img src="@/assets/image/setting/pass.png" alt="" />
        <a-button class="pass-btn primary-btn" @click="updatePwd"
          >设置新密码</a-button
        >
      </div>
      <div class="update-pwd" v-else>
        <div class="title">设置新密码</div>
        <div>
          <div class="item">
            <span>电话号码</span>
            <div class="tel-color">{{ state.info.TelNum }}</div>
          </div>
          <div class="item">
            <span>验证本人</span>
            <div class="ver-code">
              <n-input
                v-model:value="state.code"
                placeholder="在此输入验证码"
                style="width: 180px"
              />
              <n-button class="code-btn" @click="getCode" v-if="canSend"
                >获取验证码</n-button
              >
              <n-button v-else class="code-btn">{{ leftTime }}s</n-button>
            </div>
          </div>
          <div style="height: 40px"></div>
          <div class="item" :style="{ marginBottom: isWarn ? '10px' : '20px' }">
            <span>修改密码</span>
            <div class="ver-code">
              <n-input
                v-model:value="state.pass"
                type="password"
                show-password-on="click"
                style="width: 290px"
                placeholder="长度在6~18之间 由字母、数字、特殊字符组成"
                @blur="onBlur()"
                @change="onBlur()"
              />
              <img
                src="@/assets/image/ok.png"
                style="
                  width: 24px;
                  height: 24px;
                  margin-left: 10px;
                  margin-top: 4px;
                "
                v-if="isTrue"
              />
              <n-popover trigger="hover">
                <template #header>
                  <n-text strong depth="1"> 密码规则说明 </n-text>
                </template>
                <span
                  >密码长度在6-18个字符之间，由数字、字母、特殊字符组成，请勿输入中文特殊字符</span
                >
                <template #trigger>
                  <img
                    src="@/assets/image/warn.png"
                    style="
                      width: 24px;
                      height: 24px;
                      margin-left: 10px;
                      margin-top: 4px;
                      cursor: pointer;
                    "
                    v-if="isWarn"
                  />
                  <div v-else></div>
                </template>
              </n-popover>
            </div>
          </div>
          <div v-show="isWarn" class="passwordTips">
            密码长度在6-18个字符之间，由数字、字母、特殊字符组成，请勿输入中文特殊字符
          </div>
          <div class="item">
            <span>确认密码</span>
            <div>
              <n-input
                type="password"
                show-password-on="click"
                v-model:value="state.comPass"
                style="width: 290px"
                @blur="onConfirmPWBlur()"
                @change="onConfirmPWBlur()"
              />
            </div>
          </div>
          <div v-show="isConfirmPWWarn" class="passwordTips">
            两次密码输入不一致
          </div>
          <div class="btn-box">
            <a-button class="basic-btn" @click="resetForm">取消</a-button>
            <a-button
              class="primary-btn"
              :loading="state.loading"
              @click="doneSet"
              :disabled="isSave || isConfirmPWWarn"
              >保存</a-button
            >
          </div>
        </div>
      </div>
    </div> -->
  </div>
</template>

<script setup>
import {useStorage} from '@vueuse/core'

import { useRouter } from "vue-router";
import {
  defineProps,
  defineEmits,
  watch,
  reactive,
  h,
  ref,
  unref,
  onMounted,
  getCurrentInstance,
  onBeforeMount,
} from "vue";
import { Add as AddIcon } from "@vicons/ionicons5";
import { Form, message } from "ant-design-vue";
import Upload from "@/components/upload.vue";
import { Local, Session } from "@/utils/storage.js";
import { updateChatAvatar } from "@/api-norm/chat/index";
import { examV2CertGetMyCert } from "@/api-norm/evaluationResources/certificateMange/index";
import axios from "axios";
const router = useRouter();
const currentInstance = getCurrentInstance();
const { $request } = currentInstance.appContext.config.globalProperties;
const state = reactive({
  avatar: "",
  uid: Local.get("userInfo").ID,
  info: {},
  code: "",
  pass: "",
  comPass: "",
  ResolutionRatio: false,
  recentImg: [],
  uploadUrl: "upload/img",
  certList:[],
});
const isSave = ref(true);
const canSend = ref(true);
const fontValue=useStorage('fontValue',[0],localStorage)
const customMarks=ref({
  0: '标准',
  0.1: '',
  0.2:'',
  0.3:'',
  0.4:()=>{
    return h('div', 'A+');
  }
})
let styleElement=null
const updateFontSize = () => {
  const fs=fontValue.value?.[0]
  if (styleElement && document.head.contains(styleElement)) {
    document.head.removeChild(styleElement);
  }
  if (fs>0){
    styleElement = document.createElement('style');
    document.head.appendChild(styleElement);
    const fontSize = `calc(100% + ${fs}px)`
    styleElement.innerHTML = `body, * { font-size: ${fontSize} !important; }`;
  }

 }

const dragend=()=>{
  updateFontSize()
}
const leftTime = ref(60);
const isPwd = ref(true);
const isTrue = ref(false);
const isWarn = ref(false);
const isConfirmPWWarn = ref(false);
const imgList = [
  
  "https://cdn-test.szjixun.cn/fonchain-main/test/image/3734/avatar/afd1d2f5-7b04-4f60-a6f2-cd1ba6a20c1c.png",
  "https://cdns.fontree.cn/fonchain-main/prod/runtime/file/avart/11/48ae18e2-37a4-4eab-bd03-5fe1099892c3.jpg",
  "https://cdns.fontree.cn/fonchain-main/prod/runtime/file/avart/11/0a53fd8a-951e-4a8e-8d71-0198dad5e7ae.jpg",
];
const isCheck = ref(-1);
const avatarUpload = ref(null);

watch(
  () => avatarUpload.value,
  (val) => {
    if (val) {
      state.avatar = val;
      isCheck.value = -1;
    }
  }
);

const onBlur = () => {
  isTrue.value = false;
  isWarn.value = false;
  if (state.pass == "" || state.pass.length < 5) {
    isWarn.value = true;
    isSave.value = true;
    return;
  }
  let reg =
    /^(?=.*[A-Za-z])(?=.*\d)(?=.*[`~!@#$%^&*()_+<>?:"{},.\/\\;'[\]])[A-Za-z\d`~!@#$%^&*()_+<>?:"{},.\/\\;'[\]]{6,18}$/;
  if (reg.test(state.pass)) {
    isTrue.value = true;
    isSave.value = false;
  } else {
    isWarn.value = true;
    isSave.value = true;
  }
};

const onConfirmPWBlur = () => {
  if (JSON.stringify(state.pass) !== JSON.stringify(state.comPass)) {
    isConfirmPWWarn.value = true;
  } else {
    isConfirmPWWarn.value = false;
  }
};

const getImg = (item, index) => {
  state.avatar = item;
  isCheck.value = index;
};

const updateImg = () => {
  let data = {
    ID: state.info.ID,
    Avatar: state.avatar,
    NickName: state.info.NickName,
  };
  $request.HTTP.permission
    .userUpdate(data)
    .then(async(res) => {
      if (res.status == 0) {
        message.success({
          content: "修改头像成功",
          duration: 2,
        });
        //修改头像成功后，同步更新聊天系统的头像
        // const updateChatAvatarRes = await updateChatAvatar({
        //   erpUserId: state.info.ID, //erp用户id
        //   avatar: state.avatar, //头像url
        //   type: "" //送空，那就只更新聊天系统这边的头像，送erp，就erp的头像也更新
        // })
        // if(updateChatAvatarRes.status === 0){
        //   message.success("更新聊天系统头像成功")
        // } else {
        //   message.error(updateChatAvatarRes.msg)
        // }
        state.avatar = "";
      } else {
        message.error(res.msg);
      }
    })
    .catch((e) => {
      message.error(e.response.data.msg || "操作失败，请稍后再试");
    });
};
const updatePwd = () => {
  isPwd.value = false;
};
const getCode = () => {
  $request.HTTP.login
    .getCode({ TelNum: state.info.TelNum })
    .then((res) => {
      if (res.status == 0) {
        // 倒计时逻辑
        canSend.value = false;
        let timer = setInterval(() => {
          leftTime.value--;
          if (leftTime.value <= 0) {
            canSend.value = true;
            clearInterval(timer);
            leftTime.value = 60;
          }
        }, 1000);
        message.success("验证码已发送");
      } else {
        message.error(res.msg);
      }
    })
    .catch((e) => {
      message.error(e.response.data.msg || "操作失败，请稍后再试");
    });
};
const verCode = async () => {
  if (state.code.length !== 6) {
    return null;
  }
  let data = {
    TelNum: state.info.TelNum,
    Code: state.code,
  };
  let res = null;
  res = await $request.HTTP.login.verCode(data).catch((e) => {
    message.error(e.response.data.msg || "操作失败，请稍后再试");
    res = null;
  });
  return res;
};
const resetForm = () => {
  isPwd.value = true;
};
const doneSet = async () => {
  if (state.pass == "" || state.comPass == "") {
    message.warning("请输入密码！");
    return;
  }
  if (JSON.stringify(state.pass) !== JSON.stringify(state.comPass)) {
    message.warning("两次密码输入不一致！");
    isConfirmPWWarn.value = true;
    return;
  }
  const verCodeRes = await verCode();
  if (verCodeRes?.status == 0) {
    // message.success("验证码校验成功");
  } else {
    message.error(verCodeRes?.msg || "验证码校验失败");
    return false;
  }
  let data = {
    ID: state.info.ID,
    Password: state.pass,
    NickName: state.info.NickName,
  };
  $request.HTTP.permission
    .userUpdate(data)
    .then((res) => {
      if (res.status == 0) {
        message.success({
          content: "修改密码成功",
          duration: 2,
          onClose() {
            isPwd.value = false;
          },
        });
        message.success({
          content: "请重新登录！自动跳转登录页面",
          duration: 2,
          onClose() {
            Session.clear();
            Local.clear();
            router.push("/login");
          },
        });
      } else {
        message.error(res.msg);
      }
    })
    .catch((e) => {
      message.error(e.response.data.msg || "操作失败，请稍后再试");
    });
};
const changeResolutionRatio = (val) => {
  console.log(val);
  let data = {
    ID: state.info.ID,
    Extend: {
      ResolutionRatio: val,
      CanScan: state.info.Extend.CanScan,
      JumpTo: state.info.Extend.JumpTo,
      Lang: state.info.Extend.Lang,
    },
  };
  $request.HTTP.permission
    .userUpdate(data)
    .then((res) => {
      if (res.status == 0) {
        message.success({
          content: "修改成功",
          duration: 2,
        });
        location.reload();
      } else {
        message.error(res.msg);
      }
    })
    .catch((e) => {
      message.error(e.response.data.msg || "操作失败，请稍后再试");
    });
};
const getUser = () => {
  $request.HTTP.permission
    .userDetail({ ID: state.uid })
    .then((res) => {
      if (res.status == 0) {
        state.info = res.data;
        state.ResolutionRatio = state.info.Extend.ResolutionRatio;
        //如果勾选了固定分辨率，那么打开字体大小调整
        if (state.ResolutionRatio){
          updateFontSize()
        }
        state.recentImg = [
          { url: state.info.RecentImg, status: "finished", id: "c" },
        ];
      } else {
        message.error(res.msg);
      }
    })
    .catch((e) => {
      message.error(e.response.data.msg || "操作失败，请稍后再试");
    });
};
//上传组件-beforeUpload
const beforeUpload = (data) => {
  const fileType = ["image/png", "image/jpeg", "image/jpeg"];
  if (data.file.file.size > 1024 * 1024 * 50) {
    message.error("文件大小不能大于50MB，请重新选择");
    return false;
  }
  if (fileType.indexOf(data.file.type) === -1) {
    message.error("请选择png,jpg,jpeg格式的文件");
    return false;
  }
  return true;
};
//上传组件-handleRemove
const handleRemove = (data) => {
  if (data.file.status === "uploading") {
    if (state.source) {
      state.source.cancel("取消上传");
    }
  }
};
const handleUploadFinish = () => {
  // state.isUploading = false;
};
const handleUploadError = () => {
  // state.isUploading = false;
};

// 文件上传
const customRequest = async ({
  file,
  data,
  headers,
  withCredentials,
  action,
  onFinish,
  onError,
  onProgress,
}) => {
  // state.isUploading = true;
  state.source = axios.CancelToken.source();
  const formData = new FormData();
  formData.append("file", file.file);
  formData.append("source", "setting");
  formData.append("type", "file");
  const options = {
    url: import.meta.env.VITE_API_URL + state.uploadUrl,
    method: "POST",
    data: formData,
    headers: {
      Authorization: Local.get("token"),
    },
    onUploadProgress: (progressEvent) => {
      onProgress({
        percent: Math.round((progressEvent.loaded * 100) / progressEvent.total),
      });
    },
    cancelToken: state.source.token,
  };
  const res = await axios(options);
  if (res.data.status === 0) {
    let updateData = {
      ID: state.info.ID,
      RecentImg: res.data.data.ori_url,
    };
    $request.HTTP.permission
      .userUpdate(updateData)
      .then((res) => {
        if (res.status == 0) {
          message.success({
            content: "修改成功",
            duration: 2,
          });
        } else {
          message.error(res.msg);
          state.recentImg.value = [];
        }
      })
      .catch((e) => {
        message.error(e.response.data.msg || "操作失败，请稍后再试");
        state.recentImg = [];
      });
    onFinish();
  } else {
    onError();
  }
};

const getCertList = async () => {
  const res = await examV2CertGetMyCert({
    page:1,
    pageSize:999999,
    type:'all',
  })
  if (res.status === 0) {
    state.certList = res.data?.myCertResponses?.length ?res.data.myCertResponses:[]
  }
}

onBeforeMount(() => {
  getUser();
  // getCertList();
});
</script>

<style lang="scss" scoped>
.set-container {
  display: flex;
}
.certificate {
  position: absolute;
  width: 300px;
  right: 30px;
  top: 30px;
}
.user-info {
  // width: 60%;
  // width: 500px;
  position: relative;
  overflow-y: scroll;
  height: 500px;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16);
  margin: 40px;
  padding: 20px;
  .p {
    display: flex;
    margin: 30px 0;
    color: $theme-primary;
    span {
      
      &:first-child {
        flex-shrink: 0;
        display: block;
        width: 128px;
        margin-right: 30px;
        font-size: 15px;
        font-weight: 600;
      }
      &:last-child {
        font-size: 14px;
        font-weight: 400;
      }
    }
  }
}
.avatar-top {
  // width: 500px;
  color: $theme-primary;
  height: 200px;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16);
  margin: 40px;
  padding: 20px;
  .btn-box {
    display: flex;
    justify-content: end;
  }
  .set-btn {
    width: 100px;
  }
  .avatar-box {
    display: flex;
    .img-avatar {
      width: 90px;
      height: 90px;
      border-radius: 50%;
      margin: 0 10px;
      cursor: pointer;
    }
    .upload-img {
      width: 90px;
      height: 90px;
      margin-right: 20px;
      :deep(.item-img) {
        width: 90px;
        height: 90px;
      }
      :deep(.ant-image) {
        width: 90px;
        height: 90px;
      }
      :deep(.ant-image-img) {
        object-fit: cover;
      }
    }
  }
  .border-active {
    border: 2px solid $theme-primary;
  }
}

.pass-box {
  width: 500px;
  height: 750px;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16);
  margin: 40px 40px 40px 0;
  img {
    width: 80%;
    margin: 80px 10%;
  }
  .pass-btn {
    width: 80%;
    margin: 0 10%;
  }
}
.update-pwd {
  width: 500px;
  height: 750px;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16);
  padding: 0 30px;
  margin: 40px 40px 40px 0;
  .title {
    color: $theme-primary;
    padding: 30px 0;
    text-align: center;
    border-bottom: 1px solid $border-theme;
    font-size: 16px;
  }
  .item {
    display: flex;
    align-items: center;
    margin: 10px 0;
    .ver-code {
      display: flex;
      .code-btn {
        border-radius: 18px;
        font-size: 12px;
        color: $theme-primary;
        background: $btn-basic;
        width: 100px;
        height: 34px;
        margin-left: 10px;
      }
    }
    span {
      flex-shrink: 0;
      width: 80px;
    }
  }
  .btn-box {
    margin-top: 50px;
    display: flex;
    justify-content: center;
    button {
      width: 100px;
    }
  }
}
.ant-btn[disabled],
.ant-btn[disabled]:hover,
.ant-btn[disabled]:focus,
.ant-btn[disabled]:active {
  background: $theme-dark;
  color: $theme-primary;
}
.passwordTips {
  line-height: 1.25;
  color: red;
  margin-left: 70px;
}
:deep(.imgBoxChild) {
  img {
    -webkit-filter: grayscale(1); /* Webkit */
    filter: gray; /* IE6-9 */
    filter: grayscale(1); /* W3C */
  }
}
div{
  font-size:100%
}
.theme-color {
  color: $theme-primary;
}
.tel-color {
  color: $theme-darker;
}
.switch-btn {
  color: $theme-primary;
}
</style>
