let iv = "2134123412ABCDEF";
let secret_key = "BACDEF1234123412";
function parse(string) {
  return CryptoJS.enc.Utf8.parse(string);
}
function decrypt(code) {
  return CryptoJS.AES.decrypt(code, parse(secret_key), {
    iv: parse(iv),
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  }).toString(CryptoJS.enc.Utf8);
}
function encrypt(data) {
  // Encrypt   
  return CryptoJS.AES.encrypt(parse(data), parse(secret_key), {
    iv: parse(iv),
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  }).toString();
}



//查看ID是否合规，不符合即404
function GetQueryString(name) {
  // 获取当前网页链接str
  var LocString = String(window.document.location.href);
  var rs = new RegExp("(^|)" + name + "=([^&]*)(&|$)", "gi").exec(LocString), tmp;
  if (tmp = rs) {
    return decodeURI(tmp[2]);
  }
  return "";
}
function isValidJsonObject(jsonObj) {
  // 确保输入是一个对象且不是 null
  if (jsonObj && typeof jsonObj === 'object') {
    // 获取对象的键数组
    const keys = Object.keys(jsonObj);
    // 检查对象是否有键，并且键的数量大于1
    return keys.length > 0;
  }
  // 处理非对象或 null 的情况
  return false;
}


//普服设置
// @preserve
function pf_set() {
    swal({
        title: "",
        text: "请输入普服密码:",
        type: "input",
        showCancelButton: true,
        closeOnConfirm: false,
        animation: "slide-from-top",
        inputPlaceholder: "AQ@xxxx"
    },function (inputValue) {
        if (inputValue === false) return false;
        if (inputValue == "") {
            swal.showInputError("输入不能为空!");
            return false;
        }
        swal.close();
        toast.style.display = "flex";
        httpRequest.open('GET', './zy_pf_setpassword?id=' + encodeURIComponent(id_en) + "&password=" + encodeURIComponent(encrypt(inputValue)), true);
        httpRequest.send();
        httpRequest.onreadystatechange = function () {
            if (httpRequest.readyState == 4) {// 请求已完成
                toast.style.display = "none";
                if (httpRequest.status === 200) { // 请求成功
                    var 更新进度 = httpRequest.responseText;
                    swal("", 更新进度, "success");
                } else {
                    swal("", "网络繁忙,请重试!", "warning");
                }
            }
        };
   });
}

//密码设置
// @preserve
function ps_set() {
  swal({
        title: "",
        text: "请输入新的登录网页密码:",
        type: "input",
        showCancelButton: true,
        closeOnConfirm: false,
        animation: "slide-from-top",
        inputPlaceholder: "6位数字"
    },function (inputValue) {
        if (inputValue === false) return false;
        if (inputValue == "") {
            swal.showInputError("输入不能为空!");
            return false;
        }
        if (inputValue.length !== 6) {
            swal.showInputError("请输入6位数字!");
            return false;
        }
        swal.close();
        toast.style.display = "flex";
        httpRequest.open('GET', './zy_ps_setpassword?id=' + encodeURIComponent(id_en) + "&password=" + encodeURIComponent(encrypt(inputValue)), true);
        httpRequest.send();
        httpRequest.onreadystatechange = function () {
            if (httpRequest.readyState == 4) {// 请求已完成
                toast.style.display = "none";
                if (httpRequest.status === 200) { // 请求成功
                    var 更新进度 = httpRequest.responseText;
                    swal("", 更新进度, "success");
                } else {
                    swal("", "网络繁忙,请重试!", "warning");
                }
            }
        };
   });
}

//预约模式设置
// @preserve
function call_set() {
  toast.style.display = "flex";
  httpRequest.open('GET', './zy_call_status?id=' + encodeURIComponent(id_en) + "&action=0", true);
  httpRequest.send();
  httpRequest.onreadystatechange = function () {
      if (httpRequest.readyState == 4) {// 请求已完成
          toast.style.display = "none";
          if (httpRequest.status === 200) { // 请求成功
            var 响应结果 = httpRequest.responseText;
            swal({
                title: "",
                text: 响应结果,
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "开启",
                cancelButtonText: "关闭",
                closeOnConfirm: false,
                closeOnCancel: false
            },function(willDelete){
              var status ="";
              if (willDelete) {
                // 用户点击了"确定"
                status ="1"
              } else {
                // 用户点击了"关闭"
                status ="0"
              }

              swal.close();
              toast.style.display = "flex";
              httpRequest.open('GET', './zy_call_status?id=' + encodeURIComponent(id_en)+"&action=1"+"&status="+status, true);
              httpRequest.send();
              httpRequest.onreadystatechange = function () {
                if (httpRequest.readyState == 4) {// 请求已完成
                  toast.style.display = "none";
                  if (httpRequest.status === 200) { // 请求成功
                    var 更新进度 = httpRequest.responseText;
                    swal("", 更新进度, "success");
                  } else {
                    swal("", "网络繁忙,请重试!", "warning");
                  }
                }
              };


            });

             
          } else {
              swal("", "网络繁忙,请重试!", "warning");
          }
      }
  };
}


//续费
// @preserve
function call_auto() {
  swal("", "正在开发中...", "warning");
}

//退出登录
// @preserve
function exitlogin() {
toast.style.display = "flex";
httpRequest.open('GET', './zy_loginout?id=' + encodeURIComponent(id_en), true);
httpRequest.send();
httpRequest.onreadystatechange = function () {
  if (httpRequest.readyState == 4) {// 请求已完成
    toast.style.display = "none";
    if (httpRequest.status === 200) { // 请求成功
      var 退出结果 = httpRequest.responseText;
      if ((退出结果 || "").indexOf('成功') > -1) {
        swal("", 退出结果, "success");
        //获取当前 cookie 的名称
        var cookies = document.cookie.split(";");
        //遍历 cookies 删除
        for (let i = 0; i < cookies.length; i++) {
            const cookieName = cookies[i].split("=")[0].trim();
            // 通过设置到过去的过期时间来删除 cookies
            document.cookie = cookieName + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
        }
        //到另一个页面
        window.location.href = "./login"; // 修改为需要跳转的     URL
      }else{
        swal("", 退出结果, "warning");
      }
      
    } else {
      swal("", "网络繁忙,请重试!", "warning");
    }
  }
}; 
}


//切换替班
// @preserve
function change_org() {
  var 所属机构信息="";

  for (var 机构 in 机构数组) {
    // var 单体信息 = {
    //   id: 机构,
    //   orgname: substitutionOrgList[机构].orgname,
    //   orgCode: substitutionOrgList[机构].orgCode
    // }
    // 机构数组.push(单体信息)
    所属机构信息=所属机构信息+`<li data-id="${机构}"><a>${机构数组[机构].orgname}</a></li>`;
  }

  if(所属机构信息===""){
    所属机构信息='<li data-id="0000"><a>无机构可切换</a></li>';
  }
  所属机构信息=所属机构信息+'<li data-id="0000"><a>取消</a></li>';

const menuContainerele = document.getElementById('menuContainer');
if (menuContainerele) {
    document.body.removeChild(menuContainerele);
}
const overlayele = document.getElementById('overlay');
if (overlayele) {
    document.body.removeChild(overlayele);
}

const overlay = document.createElement('div');
overlay.className = 'overlay';
overlay.id = 'overlay';
document.body.appendChild(overlay);

const menuContainer = document.createElement('nav');
menuContainer.className = 'bottom-menu';
menuContainer.id = 'menuContainer';

// menuContainer.innerHTML = `
//                 <ul>
//                   <li data-id="NotAvailable"><a>机构1</a></li>
//                   <li data-id="Other"><a>机构2</a></li>
//                 </ul> 
//             `;
menuContainer.innerHTML = '<ul>'+所属机构信息+'</ul>';
      
document.body.appendChild(menuContainer);

var overlayElement = document.getElementById('overlay');
var menuContainerElement = document.getElementById('menuContainer');
menuContainerElement.classList.add('active');
menuContainerElement.style.visibility = 'visible';
overlayElement.classList.add('show');

overlay.addEventListener('click', () => {
    menuContainer.style.visibility = 'hidden';
    overlay.classList.remove('show');
});

document.querySelector('.bottom-menu').addEventListener('click', function (event) {
    var liElement = event.target.closest('li');
    if(liElement.dataset.id!=="0000"){
      toast.style.display = "flex";
      httpRequest.open('GET', './zy_change_org?id=' + encodeURIComponent(id_en)+"&orgid=" + encodeURIComponent(encrypt(liElement.dataset.id)), true);
      httpRequest.send();
      httpRequest.onreadystatechange = function () {
        if (httpRequest.readyState == 4) {// 请求已完成
          toast.style.display = "none";
          if (httpRequest.status === 200) { // 请求成功
            var 切换结果 = httpRequest.responseText;
            swal("", 切换结果, "success");
          } else {
            swal("", "网络繁忙,请重试!", "warning");
          }
        }
      };
    }
    menuContainerElement.style.visibility = 'hidden';
    overlayElement.classList.remove('show');
    menuContainerElement.classList.remove('active');
});
}


var id_en = GetQueryString('id')
document.getElementById('yy-link').href = './call?id=' + encodeURIComponent(id_en);
document.getElementById('dk-link').href = './sign?id=' + encodeURIComponent(id_en);
document.getElementById('xd-link').href = './scan?id=' + encodeURIComponent(id_en);
document.getElementById('gr-link').href = './info?id=' + encodeURIComponent(id_en);

var 机构数组 = {};
var httpRequest = new XMLHttpRequest();
toast.style.display = "flex";
httpRequest.open('GET', './zy_login_check?id=' + encodeURIComponent(id_en), true);
httpRequest.send();
httpRequest.onreadystatechange = function () {
  if (httpRequest.readyState == 4) {// 请求已完成
    if (httpRequest.status === 200) { // 请求成功
      var 凭证 = httpRequest.responseText;
      if ((凭证 || "").indexOf('有效') > -1) {
        toast.style.display = "flex";
        httpRequest.open('GET', './zy_personinfo?id=' + encodeURIComponent(id_en), true);
        httpRequest.send();
        httpRequest.onreadystatechange = function () {
          if (httpRequest.readyState == 4) {// 请求已完成
            toast.style.display = "none";
            if (httpRequest.status === 200) { // 请求成功
              var 个人信息 = httpRequest.responseText;
              if ((个人信息 || "").indexOf('person_name') > -1) {
                var 数组 = JSON.parse(个人信息);
                if (isValidJsonObject(数组)) {
                  document.getElementById("person_name").innerHTML = `${数组.person_name}`;
                  document.getElementById("simple_name_cn").innerHTML = `<a href="javascript:void(0)" onclick="change_org()" class="link">${数组.simple_name_cn}</a>`;
                  document.getElementById("ExpirationDate").textContent = '有效期： '+数组.ExpirationDate;
                  机构数组=数组.substitutionOrgList;
                } else {
                  swal("", "获取个人信息失败!", "warning");
                }
              } else {
                swal("", "获取个人信息失败!", "warning");
              }

              
            } else {
              swal("", "网络繁忙,请重试!", "warning");
            }
          }
        };
      
      } else {
        toast.style.display = "none";
        window.location = './login'
        // window.location = 'https://gz.360300.xyz/?redirect=1&id='+encodeURIComponent(id_en)
      }

    } else {
      toast.style.display = "none";
      swal("", "网络繁忙,请重试!", "warning");
    }
  }
};
