<template>
  <view class="HomeItem">
    <view v-if="!online && online !== undefined && workSchemeType == 1">
      <view class="goWork" @click="GoWork()">
        <view class="goWork_btn_E">
          <view class="goWork_btn_W"> 上班 </view>
        </view>
      </view>
      <view class="goWork_text">
        <view class="goWork_text-p">上班提醒</view>
        <view>请点击" 上班 "开始接单!</view>
      </view>
    </view>
    <view v-if="!online && online !== undefined && workSchemeType == 2" class="goWorkAll">
      <view class="goWorkSelect combination">
        <view class="goWorkSelect-head">上班选择工作组合</view>
        <scroll-view class="goWorkSelect-list scroll" scroll-y :refresher-enabled="scroll_refresher_enabled"
          :refresher-triggered="triggered" @refresherrefresh="refresherrefresh" @refresherrestore="refresherrestore"
          @scrolltolower="scrolltolower" :scroll-top="scroll_top" @refresherabort="refresherabort" @scroll="scroll">
          <radio-group @change="radioChange1">
            <label class="goWorkSelect-item relative" v-for="item in zxzData" :key="item.str">
              <radio :value="item.str" :checked="item.checked" />
              <picker class="picker" v-if="item.ruleType == 4" @change="bindPickerChange" :value="index" :range="groups"
                range-key="groupName">
                <view>{{ item.configName }}</view>
              </picker>
              <view v-else>{{ item.configName }}</view>
            </label>
          </radio-group>
        </scroll-view>
      </view>
      <view class="goWorkSelect history">
        <view class="goWorkSelect-head"> 历史上班记录 </view>
        <view class="goWorkSelect-list">
          <radio-group @change="radioChange2">
            <label class="goWorkSelect-item" v-for="(item, index) in historys" :key="index">
              <radio :value="item.str" :checked="item.checked" />
              <view>{{ item.useTime }}上班记录快捷上班</view>
              <button @click="lock(item)">
                {{ item.locking == 1 ? "解锁" : "锁定" }}
              </button>
            </label>
          </radio-group>
        </view>
      </view>
    </view>
    <!-- APP或H5账号密码登录页面 start -->
    <view class="login" v-if="!workSchemeType && (isApp||isH5AndPwd)">
      <view class="title"> 医疗服务中心转运系统 </view>
      <input class="login_input" v-model="username" placeholder="请输入用户名" />
      <input class="login_input" password v-model="password" placeholder="请输入密码" />
      <input class="login_input" v-show="!isH5AndPwd" v-model="ip" placeholder="请输入域名或IP地址,如:http(s)://192.168.3.108" />
      <view class="savePassword">
        <checkbox-group @change="checkboxChange">
          <label>
            <checkbox v-for="(item,index) in savePassword" :key="item.value" color="#42b983" :value="item.value"
              :checked="item.checked" />记住密码
          </label>
        </checkbox-group>
      </view>
      <view class="page_item_btn" @click="login()"> 登录 </view>
      <view class="tips" v-show="isH5AndPwd">
        (此系统为服务中心及药房人员使用,其他科室人员请勿进行操作)
      </view>
    </view>
    <!-- APP或H5账号密码登录页面 end -->
    <view class="botImg" v-if="online || (!online && online !== undefined && workSchemeType == 1)">
      <view class="img"></view>
    </view>
    <!-- 弹窗 -->
    <showModel :title="models.title" :icon="models.icon" :disjunctor="models.disjunctor" :content="models.content"
      @ok="ok" @cancel="cancel" :operate="models.operate" :phone="models.phone" @know="know"></showModel>
    <!-- 锁定-弹窗 -->
    <showModel :title="modelsLock.title" :icon="modelsLock.icon" :disjunctor="modelsLock.disjunctor"
      :content="modelsLock.content" @ok="okLock" @cancel="cancelLock" :operate="modelsLock.operate" @know="knowLock">
    </showModel>
    <!-- 自选排班-科室绑定分组-弹窗 -->
    <showModel :title="models2.title" :icon="models2.icon" :disjunctor="models2.disjunctor" :content="models2.content"
      @ok="ok2" @cancel="cancel2" :operate="models2.operate">
    </showModel>
  </view>
</template>

<script>
  import {
    get,
    post,
    changeIP,
    webHandle
  } from "../../http/http.js";
  import showModel from "../../components/showModel/showModel.vue";
  import {
    AES,
    mode,
    pad,
    enc
  } from "crypto-js";
  export default {
    data() {
      return {
        //#ifdef H5
        type: "",
        //#endif
        //记住密码
        savePassword: [{
          value: 'savePassword',
          name: '记住密码',
          checked: true
        }],
        // 是否上班了
        online: undefined,
        // 是否是app
        isApp: false,
        // 是否是H5,账号密码登录
        isH5AndPwd: false,
        // 用户名
        username: "",
        // 密码
        password: "",
        //ip地址或域名
        ip: "hsms.dashitech.com",
        scroll_refresher_enabled: true, //是否开启自定义下拉刷新
        triggered: false, //下拉刷新状态
        freshing: false, //上拉加载开关
        scroll_top: 0, //距离顶部的距离
        //分页页码
        idx: 0,
        // 列表项总数
        totalNum: -1,
        // 上班选择工作组合列表
        zxzData: [],
        workSchemeId: "", //启动中工作分配方案id
        workSchemeType: "", //启动中工作分配方案类型
        ruleType: "", //工作分配方案规则、、例如自由抢单等
        // 上班历史记录列表
        historys: [],
        // 弹窗model
        models: {
          disjunctor: false,
        },
        //锁定的选项
        itemLock: {},
        // 弹窗model--锁定
        modelsLock: {
          disjunctor: false,
        },
        groups: [],
        index: 0,
        quickObj: {}, //选择的上班快捷组合
        // 自选排班-科室绑定分组-弹窗model
        models2: {
          disjunctor: false,
        },
        objHistory: {}
      };
    },
    methods: {
      //aes加密
      encryptByEnAES(data) {
        let Key = "dsadmin";
        let tmpAES = AES.encrypt(data, Key, {
          mode: mode.CBC,
          padding: pad.Pkcs7,
        });
        return tmpAES.toString();
      },
      //aes加密-登录
      encryptByEnAESLogin(data) {
        data = enc.Utf8.parse(data);
        let Key = enc.Utf8.parse('Aes2Util666AQWER');
        let tmpAES = AES.encrypt(data, Key, {
          mode: mode.ECB,
          padding: pad.Pkcs7,
        });
        return tmpAES.toString();
      },
      //aes解密
      encryptByDeAES(data) {
        let Key = "dsadmin";
        let tmpDeAES = AES.decrypt(data, Key, {
          mode: mode.CBC,
          padding: pad.Pkcs7,
        });
        return tmpDeAES.toString(enc.Utf8);
      },
      //记住密码
      checkboxChange(e) {
        console.log(e.detail.value);
        let arr = e.detail.value;
        if (arr.length) {
          this.savePassword.forEach(v => {
            v.checked = true;
          })
        } else {
          this.savePassword.forEach(v => {
            v.checked = false;
          })
        }
        console.log(this.savePassword)
      },
      // 锁定
      lock(data) {
        console.log(data);
        // 如果不是科室绑定人员,则提示
        if (data.workAllocationQuick.ruleType != 3) {
          this.modelsLock = {
            disjunctor: true,
            title: "提示",
            content: `需科室绑定人员模式下才可快捷上班!`,
            icon: "warn",
          };
          return;
        }
        this.itemLock = data;
        this.modelsLock = {
          disjunctor: true,
          title: "提示",
          content: `是否${
          this.itemLock.locking == 1 ? "解锁" : "锁定"
        }该上班记录`,
          icon: "warn",
          operate: {
            ok: "确定",
            cancel: "取消",
          },
        };
      },
      //知道了
      knowLock() {
        this.modelsLock.disjunctor = false;
        let userId = uni.getStorageSync("userData").user.id;
        this.getHistorys(userId); //获取上班历史记录
      },
      //确定
      okLock() {
        this.modelsLock.disjunctor = false;
        let postData = {
          workConfigHistory: {
            id: this.itemLock.id,
            locking: this.itemLock.locking == 1 ? 0 : 1,
          },
        };
        uni.showLoading({
          title: "加载中",
          mask: true,
        });
        post("/configuration/updData/workConfigHistory", postData).then(
          (result) => {
            uni.hideLoading();
            if (result.status == 200) {
              this.modelsLock = {
                disjunctor: true,
                title: "提示",
                content: `${this.itemLock.locking == 0 ? "锁定" : "解锁"}成功`,
                icon: "success",
                operate: {
                  know: "知道了",
                },
              };
            } else {
              uni.showToast({
                icon: "none",
                title: result.msg || "接口获取数据失败!",
              });
            }
          }
        );
      },
      //取消
      cancelLock() {
        this.modelsLock.disjunctor = false;
      },
      // 选择历史上班记录
      radioChange2(value) {
        this.objHistory = JSON.parse(value.target.value);
        console.log(this.objHistory);
        // 如果不是科室绑定人员,则提示
        if (this.objHistory.workAllocationQuick.ruleType != 3) {
          this.models = {
            disjunctor: true,
            title: "提示",
            content: `需科室绑定人员模式下才可快捷上班!`,
            icon: "warn",
          };
          return;
        }
        if (!this.objHistory.deptList) {
          this.objHistory.deptList = [];
        }
        let depts = this.objHistory.deptList.map((item) => item.dept).join();
        this.models = {
          disjunctor: true,
          title: "提示",
          content: `组合名称是【${this.objHistory.workAllocationQuick.configName}】;选择的科室是【${depts}】`,
          icon: "warn",
          operate: {
            ok: "快捷上班",
            cancel: "取消",
          },
        };
      },
      //知道了
      know() {
        this.models.disjunctor = false;
      },
      //确定
      ok() {
        this.models.disjunctor = false;
        this.ruleType = 3;
        uni.setStorageSync("setDepts", this.objHistory.deptList); //存科室列表
        uni.setStorageSync("setDeptConfg", {
          //存设置科室的配置信息
          configName: this.objHistory.workAllocationQuick.configName, //组合名称
          workSchemeType: 2, //方案类型
          ruleType: 3, //方案规则,科室绑定人员
          id: this.objHistory.workAllocationQuick.id, //组合id
          classesId: this.objHistory.classId,
        });
        this.GoWork();
      },
      //取消
      cancel() {
        this.models.disjunctor = false;
        let userId = uni.getStorageSync("userData").user.id;
        this.historys = [];
        this.getHistorys(userId); //获取上班历史记录
      },
      // 获取上班历史记录
      getHistorys(id) {
        let postData = {
          idx: 0,
          sum: 3,
          workConfigHistory: {
            hosId: uni.getStorageSync("userData").user.currentHospital.id,
            user: {
              id: id,
            },
          },
        };
        post("/configuration/fetchDataList/workConfigHistory", postData).then(
          (res) => {
            if (res.status == 200) {
              this.historys = res.list;
              this.historys.forEach((item) => {
                let d = new Date(item.useTime);
                let month = (d.getMonth() + 1 + "").padStart(2, "0");
                let day = (d.getDate() + "").padStart(2, "0");
                item.useTime = `${month}月${day}日`;
                let o = JSON.parse(JSON.stringify(item));
                item.str = JSON.stringify(o);
                item.checked = false;
              });
            } else {
              uni.showToast({
                icon: "none",
                title: res.msg || "接口获取数据失败!",
              });
            }
          }
        );
      },
      //确定
      ok2() {
        uni.setStorageSync("manager", this.groups[this.index].manager); //储存分组组长
        this.models2.disjunctor = false;
        //进入设置科室界面
        uni.setStorageSync("setDeptConfg", {
          //存设置科室的配置信息
          configName: this.quickObj.configName,
          workSchemeType: this.workSchemeType,
          ruleType: this.quickObj.ruleType,
          id: this.quickObj.id,
          classesId: this.quickObj.classes.id,
          selectGroupId: this.groups[this.index].id,
        });
        uni.navigateTo({
          url: `../setDept/setDept?configName=${this.quickObj.configName}&id=${this.quickObj.id}`,
        });
      },
      //取消
      cancel2() {
        this.models2.disjunctor = false;
      },
      //工作组合的工作模式是2(科室绑定分组)或4(绑定分组)
      bindPickerChange: function(e) {
        console.log('picker发送选择改变,携带值为', e.detail.value)
        this.index = e.target.value;
        let userId = uni.getStorageSync("userData").user.id;
        let groupObj = this.groups[this.index];
        if (groupObj.manager == userId) {
          //当前登陆人是该分组组长-弹窗确定
          this.models2 = {
            disjunctor: true,
            title: "提示",
            content: `请确认您选择了‘${this.quickObj.classes.name}’班次,并选择了‘${groupObj.groupName}’分组!`,
            icon: "warn",
            operate: {
              ok: "确定",
              cancel: "取消",
            },
          };
        } else {
          //当前登陆人不是该分组组长
          uni.setStorageSync("setDeptConfg", {
            //存设置科室的配置信息
            configName: this.quickObj.configName,
            workSchemeType: this.workSchemeType,
            ruleType: this.quickObj.ruleType,
            id: this.quickObj.id,
            classesId: this.quickObj.classes.id,
          });
          this.GoWork([groupObj]);
        }
      },
      // 选择上班快捷组合
      radioChange1(value) {
        let obj = JSON.parse(value.target.value);
        console.log(obj);
        this.quickObj = obj;
        this.ruleType = obj.ruleType;
        if (uni.getStorageSync("setDeptConfg")) {
          uni.removeStorageSync("setDeptConfg"); //清空选择的科室配置,初始化
        }
        if (obj.ruleType == 1) {
          uni.setStorageSync("setDeptConfg", {
            configName: this.quickObj.configName,
            workSchemeType: this.workSchemeType,
            ruleType: this.quickObj.ruleType,
            id: this.quickObj.id,
            classesId: this.quickObj.classes.id,
          });
          //自由抢单,直接上班
          this.GoWork();
        } else if (obj.ruleType == 3) {
          //科室绑定人员,进入设置科室界面
          uni.setStorageSync("setDeptConfg", {
            //存设置科室的配置信息
            configName: this.quickObj.configName,
            workSchemeType: this.workSchemeType,
            ruleType: this.quickObj.ruleType,
            id: this.quickObj.id,
            classesId: this.quickObj.classes.id,
          });
          uni.navigateTo({
            url: `../setDept/setDept?configName=${this.quickObj.configName}&id=${this.quickObj.id}`,
          });
        } else if (obj.ruleType == 2) {
          //绑定分组,直接上班
          uni.setStorageSync("setDeptConfg", {
            //存设置科室的配置信息
            configName: this.quickObj.configName,
            workSchemeType: this.workSchemeType,
            ruleType: this.quickObj.ruleType,
            id: this.quickObj.id,
            classesId: this.quickObj.classes.id,
          });
          this.GoWork(obj.groups);
        } else if (obj.ruleType == 4) {
          //科室绑定分组,弹出分组选择
          this.groups = obj.groups;
        }
      },
      // 连接上下班的websocket  baba type如果是wx则是微信,app则是app;有app必有ip
      offWork(type, ip) {
        let ipp, wws;
        if (type == "wx") {
          wws = document.location.protocol === "http:" ? "ws" : "wss"; //ws协议
          ipp = document.domain;
        } else if (type == "app") {
          wws = ip.split(":")[0] === "http" ? "ws" : "wss"; //ws协议
          ipp = ip.split(":")[1];
        }
        console.log(ipp, wws);
        uni.connectSocket({
          url: `${wws}://${ipp}:8080/webSocket/message/onlineStatus`,
          // url: `${wws}://192.168.3.74:8080/webSocket/message/onlineStatus`,
        });
        uni.onSocketOpen(function(res) {
          console.log("WebSocket连接已打开!");
          let userid = uni.getStorageSync("userData").user.id;
          uni.sendSocketMessage({
            data: JSON.stringify({
              userid,
            }),
            success: function(res) {
              console.log(res, "传参");
            },
            fail: function(err) {
              console.log(err, "传参错误");
            },
          });
        });
        uni.onSocketError(function(res) {
          console.log("WebSocket连接打开失败,请检查!");
        });
        uni.onSocketMessage((res) => {
          console.log("收到服务器内容:" + res.data);
          if (res.data == "ok") {
            this.goOffWork();
          }
        });
      },
      // 下班
      goOffWork() {
        let setDeptConfg = uni.getStorageSync("setDeptConfg");
        if (setDeptConfg.workSchemeType == 2 && setDeptConfg.ruleType == 3) {
          post("/auth/onOrOffLine", {
            type: "off",
            customWorking: "off",
            classId: uni.getStorageSync("setDeptConfg").classesId
          }).then((res) => {
            if (res.status == 200) {
              if (uni.getStorageSync("setDeptConfg")) {
                uni.removeStorageSync("setDeptConfg"); //清空选择的科室配置,初始化
              }
              uni.showToast({
                icon: "none",
                title: "您已被强制下班!",
                mask: true,
                duration: 5000,
              });
              setTimeout(() => {
                uni.redirectTo({
                  url: "../mypage/mypage",
                });
              }, 5000);
            } else {
              uni.showToast({
                icon: "none",
                title: res.msg || "接口获取数据失败!",
              });
            }
          });
        } else {
          post("/auth/onOrOffLine", {
            type: "off",
            classId: uni.getStorageSync("setDeptConfg").classesId
          }).then((res) => {
            if (res.status == 200) {
              if (uni.getStorageSync("setDeptConfg")) {
                uni.removeStorageSync("setDeptConfg"); //清空选择的科室配置,初始化
              }
              uni.showToast({
                icon: "none",
                title: "您已被强制下班!",
                mask: true,
                duration: 5000,
              });
              setTimeout(() => {
                uni.redirectTo({
                  url: "../mypage/mypage",
                });
              }, 5000);
            } else {
              uni.showToast({
                icon: "none",
                title: res.msg || "接口获取数据失败!",
              });
            }
          });
        }
      },
      // 上班
      GoWork(groups) {
        console.log(groups)
        uni.showLoading({
          title: "加载中",
          mask: true,
        });
        //自选排班,科室绑定人员,科室绑定分组,绑定分组
        if (this.workSchemeType == 2 && (this.ruleType == 1 || this.ruleType == 2 || this.ruleType == 3 || this
            .ruleType == 4)) {
          let userId = uni.getStorageSync("userData").user.id;
          let setDeptConfg = uni.getStorageSync("setDeptConfg");
          let postData = {
            type: "on",
            customWorking: "on",
            userId: userId,
          };
          console.log(postData, this.objHistory)
          if (this.ruleType == 3 || this.ruleType == 4) {
            if (!this.objHistory.deptList) {
              this.objHistory.deptList = [];
            }
            let depts = this.objHistory.deptList.map((item) => item.id).join();
            postData.deptIds = depts;
            postData.quickId = setDeptConfg.id;
            postData.classId = setDeptConfg.classesId;
          } else if (this.ruleType == 2 || this.ruleType == 1) {
            postData.quickId = setDeptConfg.id;
            postData.classId = setDeptConfg.classesId;
          }
          console.log(postData, this.ruleType, setDeptConfg)
          if (groups) {
            postData.groupIds = groups.map(v => v.id).toString();
            if (this.ruleType == 4) {
              //科室绑定分组,并且当前登陆人不是组长
              delete postData.deptIds;
            }
          }
          post("/auth/onOrOffLine", postData).then((result) => {
            uni.hideLoading();
            if (result.status == 200) {
              let obj = uni.getStorageSync("userData");
              obj.user.online = true;
              uni.setStorageSync("userData", obj);
              uni.redirectTo({
                url: "../receiptpage/receiptpage",
              });
            } else if (result.status == 504) {
              let dept = result.department.dept;
              let user = result.user.name;
              let phone = result.user.phone;
              this.models = {
                disjunctor: true,
                title: "提示",
                content: `您选择的科室已经被使用,请换个科室,或者联系:科室[${dept}]人员[${user}]号码[${phone}] 切换科室解决`,
                icon: "warn",
                phone,
                operate: {
                  know: "知道了",
                },
              };
            } else {
              uni.showToast({
                icon: "none",
                title: result.msg || "接口获取数据失败!",
              });
            }
          });
        } else {
          let postData = {
            type: "on",
            classId: uni.getStorageSync("setDeptConfg").classesId
          };
          if (groups) { //caocao
            postData.groupIds = groups.map(v => v.id).toString();
          }
          post("/auth/onOrOffLine", postData).then((res) => {
            uni.hideLoading();
            if (res.status == 200) {
              let obj = uni.getStorageSync("userData");
              obj.user.online = true;
              uni.setStorageSync("userData", obj);
              uni.redirectTo({
                url: "../receiptpage/receiptpage",
              });
            } else {
              uni.showToast({
                icon: "none",
                title: res.msg || "接口获取数据失败!",
              });
            }
          });
        }
      },
      // 登录
      login() {
        // 用户名,密码,域名(ip)不能为空
        if (
          this.username.trim() === "" ||
          this.password.trim() === "" ||
          this.ip.trim() === ""
        ) {
          uni.showToast({
            icon: "none",
            title: "请输入用户名,密码,域名或IP",
          });
          return;
        }
        // 域名ip正则验证
        let regUrl =
          /^https?:\/\/([\w-]+\.)+((com)|(net)|(org)|(gov\.cn)|(info)|(cc)|(com\.cn)|(net\.cn)|(org\.cn)|(name)|(biz)|(tv)|(cn)|(mobi)|(name)|(sh)|(ac)|   (io)|(tw)|(com\.tw)|(hk)|(com\.hk)|(ws)|(travel)|(us)|(tm)|(la)|(me\.uk)|(org\.uk)|(ltd\.uk)|(plc\.uk)|(in)|(eu)|(it)|(jp))(\:([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-5]{2}[0-3][0-5]))?$/;
        let regIp =
          /^https?:\/\/((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]\d)|\d)(\.((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]\d)|\d)){3}(\:([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-5]{2}[0-3][0-5]))?$/;
        if (!regUrl.test(this.ip.trim()) && !regIp.test(this.ip.trim())) {
          uni.showToast({
            icon: "none",
            title: "请输入正确的域名或IP",
          });
          return;
        }
        if (this.savePassword[0].checked) {
          //记住密码
          uni.setStorageSync("ip", this.ip);
        } else {
          // 不记住密码
          uni.removeStorageSync('ip');
        }
        changeIP(this.ip);
        uni.showLoading({
          title: "登录中",
          mask: true,
        });
        
        let data = {
          username: this.username.trim(),
          password: this.password.trim(),
          type: 'APP'
        };
        data = {
          k: this.encryptByEnAESLogin(JSON.stringify(data))
        };
        post("/auth/login", data).then((res) => {
          uni.hideLoading();
          if (res.status == 200) {
            //获取角色信息
            let role = res.user.user.role;
            // 配药师和配送人员才能登录
            let workerFlag = role.some((item) => item.rolecode === "worker");
            let pharmacistFlag = role.some((item) => item.rolecode === "pharmacist");
            if (!workerFlag && !pharmacistFlag) {
              uni.showToast({
                icon: "none",
                title: "暂无权限登录!",
              });
              return;
            }
            if (this.savePassword[0].checked) {
              //记住密码
              uni.setStorageSync("username", this.encryptByEnAES(this.username)); //存储用户名
              uni.setStorageSync("password", this.encryptByEnAES(this.password)); //存储密码
              uni.setStorageSync("savePasswordTime", Date.now()); //存储当前时间戳
            } else {
              uni.removeStorageSync('username');
              uni.removeStorageSync('password');
              uni.removeStorageSync('savePasswordTime');
            }
            uni.setStorageSync("userData", res.user);
            this.getWorkScheme(false, res.user.user.currentHospital.id); //获取当前启动中的工作分配方案
            this.getHistorys(res.user.user.id); //获取上班历史记录
            this.offWork("app", this.ip);
            if (workerFlag) { //有配药师角色
              if (!res.user.user.online) {
                this.online = false;
              } else {
								this.online = true;
								let menu = res.user.menu.filter(i=>i.parentid=='278')
								if(menu){
									let isSpecimen = menu.filter(i=>i.title=='标本间')
									if(isSpecimen.length>0){
										// 建立websocket连接
										webHandle("specimenPort", "app");
										uni.setStorageSync("isSpecimen", '1');
									}else{
										// 建立websocket连接
										webHandle("receiptpage", "wx");
										uni.setStorageSync("isSpecimen", '0');
									}
								}else{
									// 建立websocket连接
									webHandle("receiptpage", "wx");
									uni.setStorageSync("isSpecimen", '0');
								}
              }
            } else {
              webHandle("pharmacy", "app", this.ip);
            }
          } else if (!res.status && !res.remarks) {
            //如果乱填写域名或ip
            uni.showToast({
              icon: "none",
              title: "服务器连接失败!请检查输入的域名(IP)及端口号",
            });
          } else {
            uni.showToast({
              icon: "none",
              title: res.remarks || "接口获取数据失败!",
            });
          }
        });
        
      },
      // 微信登录公用方法
      // user:当前登录用户对象
      // type:有值的话则是从菜单访问的
      // workerFlag:是否有配送人员角色
      // pharmacistFlag:是否有配药师角色
      submCommon(user, type, workerFlag, pharmacistFlag) {
        //从药房菜单过来的
        if (type === "pharmacy") {
          //药房来
          // 药房才能登录
          if (!pharmacistFlag) {
            uni.showToast({
              icon: "none",
              title: "暂无权限登录!",
            });
            return;
          }
        } else if (type === "mypage") { //从我的菜单过来的
          if (!workerFlag) {
            uni.showToast({
              icon: "none",
              title: "暂无权限登录!",
            });
            return;
          }
        } else {
          //正常进入
          if (!workerFlag && !pharmacistFlag) {
            uni.showToast({
              icon: "none",
              title: "暂无权限登录!",
            });
            return;
          }
        }
        uni.setStorageSync("userData", user);
        this.getWorkScheme(false, user.user.currentHospital.id); //获取当前启动中的工作分配方案
        this.getHistorys(user.user.id); //获取上班历史记录
        this.offWork("wx");
        // uni.setStorageSync('type', '')
        if (type === "pharmacy") {
          // 建立websocket连接
          webHandle("pharmacy", "wx");
        } else if (type === "mypage") {
          // 建立websocket连接
          webHandle("mypage", "wx");
        } else {
          if (workerFlag) { //有配送人员的角色
            if (!user.user.online) {
              this.online = false;
            } else {
							this.online = true;
							let menu = user.menu.filter(i=>i.parentid=='278')
							if(menu){
								let isSpecimen = menu.filter(i=>i.title=='标本间')
								if(isSpecimen.length>0){
									// 建立websocket连接
									webHandle("specimenPort", "app");
									uni.setStorageSync("isSpecimen", '1');
								}else{
									// 建立websocket连接
									webHandle("receiptpage", "wx");
									uni.setStorageSync("isSpecimen", '0');
								}
								console.log(88888,isSpecimen)
							}else{
								// 建立websocket连接
								webHandle("receiptpage", "wx");
								uni.setStorageSync("isSpecimen", '0');
							}
            }
          } else { //只有药房橘色
            webHandle("pharmacy", "wx");
          }
        }
      },
      //微信
      subm() {
        uni.showLoading({
          title: "登录中",
          mask: true,
        });
        var href = location.href; //获取链接地址
        console.log(href, "href");
        var href_wenhao = href.indexOf("?code="); //判断有没有问号,没有是-1
        var wenhaohoumian = location.href.split("?code="); //截取问号地址数组
        this.arr_last = wenhaohoumian[1]; //地址数组赋值
        if (href_wenhao == -1) {
          post("/auth/wxlogin").then((res) => {
            this.url = res.url;
            this.state = res.status;
            uni.setStorageSync("type", this.type); //存储来源type
            uni.hideLoading();
            if (this.state == "200") {
              //获取角色信息
              let role = res.user.user.role;
              let workerFlag = role.some((item) => item.rolecode === "worker");
              let pharmacistFlag = role.some((item) => item.rolecode === "pharmacist");
              this.submCommon(res.user, this.type, workerFlag, pharmacistFlag);
            } else if (this.state == "501") {
              uni.showModal({
                title: '提示',
                content: res.remarks,
                showCancel: false,
                confirmColor: '#49b856',
                success: function(res) {
                  if (res.confirm) {
                    console.log('用户点击确定');
                  } else if (res.cancel) {
                    console.log('用户点击取消');
                  }
                }
              });
            } else if (this.state == "555") {
              // 如果需要绑定账号 并且 没有微信号
              if (this.type) {
                uni.redirectTo({
                  url: `../bindUser/bindUser?type=${this.type}`
                })
              } else {
                uni.redirectTo({
                  url: `../bindUser/bindUser`
                })
              }
            } else {
              console.log(this.url, "url");
              // https://open.weixin.qq.com/connect/oauth2/authorize?appid=ww2506abad3086cfab&redirect_uri=http://weixintest2.ngser.dashitech.com/app&response_type=code&scope=snsapi_base&agentid=1000013&state=STATE&connect_redirect=1#wechat_redirect
              location.assign(this.url);
            }
          });
        } else if (href_wenhao != -1) {
          this.arr_last = this.arr_last.split("&");
          this.arr_last = this.arr_last[0];
          post("/auth/wxlogina", {
            code: this.arr_last,
          }).then((res) => {
            this.state = res.status;
            uni.hideLoading();
            if (this.state == "200") {
              this.type = uni.getStorageSync("type"); //刷新页面后获取type
              console.log(this.type);
              //获取角色信息
              let role = res.user.user.role;
              let workerFlag = role.some((item) => item.rolecode === "worker");
              let pharmacistFlag = role.some((item) => item.rolecode === "pharmacist");
              this.submCommon(res.user, this.type, workerFlag, pharmacistFlag);
            } else if (this.state == "501") {
              uni.showModal({
                title: '提示',
                content: res.remarks,
                showCancel: false,
                confirmColor: '#49b856',
                success: function(res) {
                  if (res.confirm) {
                    console.log('用户点击确定');
                  } else if (res.cancel) {
                    console.log('用户点击取消');
                  }
                }
              });
            } else if (this.state == "555") {
              this.type = uni.getStorageSync("type"); //刷新页面后获取type
              // 如果需要绑定账号 并且 没有微信号
              if (this.type) {
                uni.redirectTo({
                  url: `../bindUser/bindUser?type=${this.type}`
                })
              } else {
                uni.redirectTo({
                  url: `../bindUser/bindUser`
                })
              }
            } else {
              uni.showToast({
                icon: "none",
                title: res.msg || "接口获取数据失败!",
              });
            }
          });
        }
      },
      // 获取工作组合列表
      getCombinationById(idx, type) {
        console.log(this.type);
        if (this.zxzData.length == this.totalNum && !type) {
          uni.showToast({
            icon: "none",
            title: "没有更多数据了!",
          });
          this.freshing = true;
          return;
        }
        let data = {
          workAllocationQuickConfig: {
            workSchemeId: this.workSchemeId,
          },
          idx: idx,
          sum: 20,
        };
        uni.showLoading({
          title: "加载中",
          mask: true,
        });
        // 请求列表数据
        post("/configuration/fetchDataList/workAllocationQuickConfig", data).then(
          (res) => {
            uni.hideLoading();
            if (res.status == 200) {
              this.triggered = false;
              this.freshing = true;
              this.totalNum = res.totalNum;
              if (idx === 0) {
                res.list.forEach((item) => {
                  let o = JSON.parse(JSON.stringify(item));
                  item.str = JSON.stringify(o);
                  item.checked = false;
                });
                this.zxzData = res.list;
              } else {
                res.list.forEach((item) => {
                  let o = JSON.parse(JSON.stringify(item));
                  item.str = JSON.stringify(o);
                  item.checked = false;
                });
                this.zxzData.push(...res.list);
              }
            } else {
              uni.showToast({
                icon: "none",
                title: res.msg || "接口获取数据失败!",
              });
            }
          }
        );
      },
      //刷新
      refresherrefresh() {
        if (this.triggered) {
          return;
        }
        console.log("下拉刷新");
        this.triggered = true;
        this.idx = 0;
        this.totalNum = -1;
        this.getCombinationById(0);
      },
      // 下拉刷新复位
      refresherrestore() {
        this.triggered = false;
        console.log("下拉刷新复位");
      },
      //下拉刷新中止
      refresherabort() {
        this.triggered = false;
        console.log("下拉刷新中止");
      },
      //分页,上拉加载
      scrolltolower() {
        if (this.freshing) {
          console.log("上拉加载");
          this.freshing = false;
          this.getCombinationById(++this.idx);
        }
      },
      // 滚动
      scroll(e) {
        if (e.detail.scrollTop < 20) {
          this.scroll_refresher_enabled = true;
        } else {
          this.scroll_refresher_enabled = false;
        }
      },
      // 获取启动中的工作分配方案
      getWorkScheme(type, hosId) {
        let postData = {
          idx: 0,
          workScheme: {
            status: 1,
            hosId
          },
          sum: 1,
        };
        post("/simple/data/fetchDataList/workScheme", postData).then((res) => {
          if (res.status == 200) {
            if(Array.isArray(res.list) && res.list.length){
              this.workSchemeId = res.list[0].id;
              this.workSchemeType = res.list[0].workType;
              if (type) {
                if (this.workSchemeType == 2) {
                  this.getCombinationById(0, "no");
                } else if (this.workSchemeType == 1) {
                  if (uni.getStorageSync("setDeptConfg")) {
                    uni.removeStorageSync("setDeptConfg"); //清空选择的科室配置,初始化
                  }
                }
              } else {
                this.getCombinationById(0);
              }
            }
          } else {
            uni.showToast({
              icon: "none",
              title: res.msg || "接口获取数据失败!",
            });
          }
        });
      },
      // 阻止浏览器滑动
      stop(e) {
        e.preventDefault();
      },
      //获取查询参数
      GetQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = location.search.substr(1).match(reg);
        if (r != null) {
          return unescape(r[2]);
        }
        return null;
      }
    },
		onBackPress(e) {
			// backbutton:物理按键返回
			if (e.from === 'backbutton') {
				return true 
			}
		},
    onHide() {
      this.zxzData = [];
      this.historys = [];
      // #ifdef H5
      document.body.removeEventListener("touchmove", this.stop, {
        passive: false,
      });
      // #endif
    },
    onShow() {
      console.log('onShow');
      // let flag = true;
      if (uni.getStorageSync("userData")) {
        this.online = uni.getStorageSync("userData").user.online;
      }
      if (!this.workSchemeType) {
        return;
      }
      // if (this.workSchemeType == 2 && !this.online) {
      //   let userId = uni.getStorageSync('userData').user.id;
      //   this.getCombinationById(this.idx, 'no');
      //   this.getHistorys(userId); //获取上班历史记录
      // }
      let userId = uni.getStorageSync("userData").user.id;
      this.getWorkScheme(true, uni.getStorageSync("userData").user.currentHospital.id);
      this.getHistorys(userId); //获取上班历史记录
      // #ifdef APP-PLUS
      uni.closeSocket();
      // #endif
      // #ifdef H5
      document.body.addEventListener("touchmove", this.stop, {
        passive: false,
      });
      // #endif
    },
    onLoad(options) {
      if (uni.getStorageSync("setDepts")) {
        uni.removeStorageSync("setDepts"); //清空选择的科室,初始化
      }
      console.log(options);
      console.log(typeof uni.getStorageSync("savePasswordTime"));
      if (Date.now() - uni.getStorageSync("savePasswordTime") < 10 * 24 * 60 * 60 * 1000) {
        //记住密码,10天内有效
        this.ip = uni.getStorageSync("ip") || this.ip;
        if (uni.getStorageSync("username")) {
          this.username = this.encryptByDeAES(uni.getStorageSync("username"));
        }
        if (uni.getStorageSync("password")) {
          this.password = this.encryptByDeAES(uni.getStorageSync("password"));
        }
      }
      //#ifdef H5
      this.isApp = false;
      this.type = options.type || "";
      console.log(this.type);
      if (this.GetQueryString('login') === '1') {
        //H5页面账号密码登录
        this.isH5AndPwd = true;
        this.ip = location.origin;
      } else {
        this.isH5AndPwd = false;
        this.subm();
      }
      //#endif
      // #ifdef APP-PLUS
      this.isApp = true;
      // 通知权限 start
      // var main = plus.android.runtimeMainActivity();
      // var pkName = main.getPackageName();
      // var NotificationManagerCompat = plus.android.importClass(
      //   "android.support.v4.app.NotificationManagerCompat"
      // );
      // var packageNames = NotificationManagerCompat.from(main);
      // console.log(JSON.stringify(packageNames));
      // if (packageNames.areNotificationsEnabled()) {
      //   console.log("已开启通知权限");
      // } else {
      //   uni.showModal({
      //     title: "提示",
      //     content: "请先打开APP通知权限",
      //     showCancel: true,
      //     success: function(res) {
      //       if (res.confirm) {
      //         var Intent = plus.android.importClass("android.content.Intent");
      //         var intent = new Intent(
      //           "android.settings.APP_NOTIFICATION_SETTINGS"
      //         ); //可设置表中所有Action字段
      //         intent.putExtra("android.provider.extra.APP_PACKAGE", pkName);
      //         main.startActivity(intent);
      //       }
      //     },
      //   });
      // }
      // 通知权限 end
      // #endif
    },
  };
</script>

<style lang="less" scoped>
  .HomeItem {
    height: 100vh;

    .login {
      height: 420rpx;
      padding: 0 32rpx;
      padding-top: 164rpx;
      position: relative;
      z-index: 999;

      .savePassword {
        margin-top: 32rpx;
      }

      /deep/ uni-checkbox:not([disabled]) .uni-checkbox-input:hover {
        border-color: #42b983 !important;
      }

      .login_input {
        margin-top: 32rpx;
        background-color: #ffffff;
        height: 72rpx;
        box-sizing: border-box;
        padding: 16rpx;
      }

      .title {
        font-size: 36rpx;
        color: #42b983;
        text-align: center;
      }

      .tips {
        font-size: 28rpx;
        color: red;
        margin-top: 16rpx;
      }

      .page_item_btn {
        height: 88rpx;
        background-image: linear-gradient(to right, #72c172, #3bb197);
        border-radius: 8rpx;
        line-height: 88rpx;
        color: #fff;
        font-size: 36rpx;
        font-weight: 700;
        margin-top: 64rpx;
        text-align: center;
      }
    }

    //上班页面
    .goWorkAll {
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      /deep/ .uni-radio-input-checked {
        background-color: #42b983 !important;
        border-color: #42b983 !important;
      }

      .goWorkSelect {
        &.history {
          height: 356rpx;
          padding-bottom: 16rpx;
        }

        &.combination {
          .goWorkSelect-head {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
          }

          .goWorkSelect-list {
            margin-top: 82rpx;
          }
        }

        .goWorkSelect-head {
          font-size: 36rpx;
          padding: 16rpx 0;
          color: #42b983;
          border-bottom: 2rpx solid #42b983;
          text-align: center;
        }

        .goWorkSelect-list {
          &.scroll {
            height: calc(100vh - 356rpx - 82rpx);
            // height: calc(100vh - 82rpx);
          }

          .goWorkSelect-item {
            height: 52rpx;
            display: flex;
            align-items: center;
            border-bottom: 2rpx solid #e5e9ed;
            padding: 16rpx;

            &.relative {
              position: relative;

              .picker {
                position: absolute;
                width: 100%;
                padding-left: 64rpx;
              }
            }

            button {
              font-size: 32rpx;
              height: 52rpx;
              line-height: 52rpx;
              margin: 0;
              margin-left: 16rpx;
              color: rgb(7, 134, 60);
              font-weight: 700;
            }
          }
        }
      }
    }

    .goWork {
      margin: 0 auto 48rpx;
      width: 240rpx;
      height: 240rpx;

      .goWork_btn_E {
        width: 100%;
        height: 100%;
        background: #bee1a7;
        border-radius: 30%;

        .goWork_btn_W {
          width: 75%;
          height: 75%;
          background-image: linear-gradient(to right, #72c172, #3bb197);
          border-radius: 30%;
          margin: 0 auto;
          position: relative;
          top: 12.5%;
          line-height: 180rpx;
          color: #fff;
          font-size: 36rpx;
          text-align: center;
        }
      }
    }

    .goWork_text {
      width: 100%;

      view {
        text-align: center;
      }

      .goWork_text-p {
        font-size: 36rpx;
        margin-bottom: 48rpx;
      }
    }

    .botImg {
      height: 600rpx;
      width: 100%;
      position: fixed;
      bottom: 0;

      .img {
        height: 100%;
        background: url("../../static/img/BG.png") no-repeat center center;
        background-size: 100% 100%;
      }
    }
  }
</style>