<template>
  <view>
    <view class="reader-box" v-if="isScaning">
      <view class="reader" id="reader"></view>
    </view>
    <view class="content" v-else>

      <view class="filter_container" style="width: 20%;">
        <view class="search_container" @click="toSearch()">
          <uni-icons class="search_icon" type="search" size="20" color="#fff"></uni-icons>
          搜索
        </view>
      </view>
      <xinsoft-sl-filter ref="slFilter" :menuList.sync="menuList" @result="getFilter"></xinsoft-sl-filter>
      <view class="otherFixed98">
        <view class="text" @click="selectOperater">{{ user.name }}</view>
      </view>
      <view v-for="(item, index) in listCards" :key="index" class="example-box" style="position: relative; flex: 1"
        @click="toDetail(index, item)">
        <dev-block :title="item.title" :titleNumber="item.titleNumber" :note="item.note" :extra="item.extra"
          :tagType="item.tagType" :contentList="item.contentList"></dev-block>
        <uni-icons type="arrowright" size="20" color="#666" class="arrowright"></uni-icons>
      </view>
      <view @click="getList" style="text-align: center;color:#333">点击加载更多</view>
      <!-- <uni-load-more :status="loading_status"></uni-load-more> -->
      <view class="goHome" @click="goMain()">
        <img src="../../static/img/gohome.png" />
      </view>
      <view class="mysearchlist" style="z-index: 10000">
        <chooseUserSingle ref="mysearchlist" :showsearch.sync="show_search_user" :itemInfo_.sync="search_value_user">
        </chooseUserSingle>
      </view>
    </view>
  </view>
</template>

<script>
import xinsoftSlFilter from "@/components/xinsoft-sl-filter/xinsoft-sl-filter.vue";
import devBlock from "@/components/xinsoft-dev-block/xinsoft-dev-block.vue";
import uniIcons from "@/components/uni-icons/uni-icons.vue";
import uniLoadMore from "@/components/uni-load-more/uni-load-more.vue";
import jweixin from "@/jweixin-module/index.js";
import chooseUserSingle from "@/components/xinsoft-search-list/chooseUserSingle.vue";
import { Html5Qrcode } from 'html5-qrcode';

export default {
  components: {
    chooseUserSingle,
    xinsoftSlFilter,
    devBlock,
    uniIcons,
    uniLoadMore,
  },
  data() {
    return {
      html5Qrcode:null,
      isScaning:false,
      show_search_user: false,
      search_value_user: "",
      listCards: [],
      engineerId: "",
      status: "",
      // status: 56,
      pagenumber: 1, //当前第几页
      pagesize: 5, //每页加载数据条数
      menuList: [
        {
          title: "状态",
          isMutiple: false,
          key: "status",
          isSort: true,
          detailList: [
            {
              title: "全部",
              value: '',
            },
            {
              title: "待处理",
              value: 56,
            },
            {
              title: "关闭",
              value: 167,
            },
            {
              title: "超期未处理",
              value: 999,
            },
            {
              title: "已完成",
              value: 131,
            }
            
          ],
          defaultSelectedIndex: [],
        },
        // {
        // 	'title': '巡检人',
        // 	'isMutiple': false,
        // 	'key': 'user',
        // 	'detailList': [],
        // 	'defaultSelectedIndex': []
        // }
      ],
      user: {
        value: "",
        name: "巡检人员",
      },
      loading_status: "more", //more（loading前）、loading（loading中）、noMore（没有更多了）
    };
  },
  onShow() {
    var _this = this;
    this.$eventHub.$on("changestate", function (data) {
      var datajson = data;
      if (datajson.id) {
        for (var i = 0; i < _this.listCards.length; i++) {
          if (_this.listCards[i].id == datajson.id) {
            var str = _this.listCards[i].title;
            _this.listCards[i].title = str.split("-")[0] + "-" + datajson.state;
          }
        }
      }
      _this.$eventHub.$off("changestate");
    });
  },
  created() {
    var userInfo = uni.getStorageSync("userInfo");
    this.getDateList();
  },
  //滚动到底部加载下一页
  // onReachBottom(obj) {
  //   if (this.loading_status == "noMore") {
  //     return false;
  //   }
  //   this.pagenumber++;
  //   this.getDateList();
  // },
  //下拉刷新
  onPullDownRefresh() {
    this.listCards = [];
    this.pagenumber = 1;
    this.loading_status = "more";
    this.getDateList();
  },
  mounted() {
    // this.initiateWX();
  },
  watch: {
    search_value_user(newv) {
      // this.$set(this.dataList[this.currentIndex],'operator',newv.userId);
      this.$set(this.user, "name", newv.NAME);
      // this.filter.userName = newv.NAME;
      this.engineerId = newv.userId;
      this.listCards = [];
      this.pagenumber = 1;
      this.loading_status = "more";
      this.getDateList();
    },
  },
  methods: {
	  getList(){
		 this.pagenumber++;
		 this.getDateList(); 
	  },
    openQrcode() {
      this.isScaning = true;
      Html5Qrcode.getCameras().then((devices) => {
        if (devices && devices.length) {
          this.html5Qrcode = new Html5Qrcode("reader");
          this.html5Qrcode.start(
            {
              facingMode: "environment",
            },
            {
              focusMode: "continuous", //设置连续聚焦模式
              fps: 5, //设置扫码识别速度
              qrbox: 280, //设置二维码扫描框大小
            },
            (decodeText, decodeResult) => {
              if (decodeText) {
                let data = JSON.parse(decodeText);
                if(data.serialNo){
                  this.getQrCodeInfo(data.serialNo);
                  this.stopScan(); //关闭扫码功能
                }
              }
            },
            (err) => {
              // this.stopScan();
              // console.log(err);  //错误信息
            }
          );
        }
      });
    },
    stopScan() {
      this.isScaning = false;
      if (this.html5Qrcode) {
        this.html5Qrcode.stop();
      }
    },
    // 选择责任人
    selectOperater() {
      this.show_search_user = true;
    },
    //获取微信相关
    initiateWX() {
      this.$http
        .request({
          url: "/apis/weChat/getSignature",
          params: {
            // url:"http://120.132.17.220:18093/gyhl-app/"
            url: window.location.href.split("#")[0],
          },
        })
        .then((res) => {
          if (res.data.code == 0) {
            var s = res.data;
            console.log("测试前————————————————");
            jweixin.config({
              beta: true,
              // debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
              appId: s.corpId, // 必填，公众号的唯一标识
              timestamp: s.timestamp, // 必填，生成签名的时间戳
              nonceStr: s.nonceStr, // 必填，生成签名的随机串
              signature: s.signature.toLowerCase(), // 必填，签名，见附录1
              jsApiList: [
                "onMenuShareTimeline",
                "onMenuShareAppMessage",
                "onMenuShareQQ",
                "onMenuShareWeibo",
                "onMenuShareQZone",
                "scanQRCode",
              ],
            });
            console.log("测试后————————————————");
          } else {
            uni.showToast({
              title: res.msg ? res.msg : "获取微信配置失败",
              icon: "none",
              duration: 2000,
            });
          }
        })
        .catch((err) => {
          uni.showToast({
            title: err,
            icon: "none",
            duration: 2000,
          });
        });
    },
    onNavigationBarButtonTap(){
      this.openQrcode();
    },
    // onNavigationBarButtonTap() {
    //   const that = this;
    //   // 允许从相机和相册扫码
    //   // #ifdef APP-PLUS
    //   uni.scanCode({
    //     success: function (res) {
    //       // console.log('条码内容：' + res.result)
    //       that.scanWord = res.result;
    //     },
    //   });
    //   // #endif
    //   // #ifdef H5
    //   that.imgUp();
    //   // #endif
    // },
    // h5选择二维码并解析
    imgUp() {
	  let qrcode = require("../../reqrcode/webcode");
      let that = this;
      uni.chooseImage({
        sizeType: ["original"],
        count: 1,
        success: function (res) {
          const tempFilePaths = res.tempFilePaths;
          qrcode.decode(tempFilePaths[0]);
          qrcode.callback = function (res) {
            const data = JSON.parse(res);
            const result = data;
            if (!data) {
              uni.showToast({
                title: "识别二维码失败，请重新上传！",
                duration: 2000,
                icon: "none",
              });
            } else {
              if (result.serialNo) {
                that.getQrCodeInfo(result.serialNo);
              } else {
                uni.showToast({
                  icon: "none",
                  title: "二维码未识别到正确的信息",
                  duration: 1000,
                });
                return false;
              }
            }
          };
        },
      });
    },

    /** 点击顶部按钮的方法 */
    onNavigationBarButtonTap1() {
      console.log("你点击了按钮");

      console.log(jweixin.config); // 允许从相机和相册扫码
      let _this = this;
      jweixin.scanQRCode({
        desc: "scanQRCode desc",
        needResult: 1, // 默认为0，扫描结果由企业微信处理，1则直接返回扫描结果，
        scanType: ["qrCode"], // 可以指定扫二维码还是条形码（一维码），默认二者都有"qrCode", "barCode"
        success: function (res) {
          if (res.errMsg != "scanQRCode:ok") {
            uni.showToast({
              title: "扫描结果:" + res.resultStr,
              icon: "none",
              duration: 2000,
            });
          } else {
            //扫码正确
            let resultStr = res.resultStr;
            try {
              resultStr = JSON.parse(resultStr);

              if (resultStr.serialNo) {
                _this.getQrCodeInfo(resultStr.serialNo);
              } else {
                uni.showToast({
                  title: "二维码错误，请扫描正确的二维码",
                  icon: "none",
                  duration: 2000,
                });
              }
            } catch (e) {
              uni.showToast({
                title: "二维码错误，请扫描正确的二维码",
                icon: "none",
                duration: 2000,
              });
            }
          }
          // 回调
        },
        error: function (res) {
          uni.showToast({
            title: "error:" + res,
            icon: "none",
            duration: 2000,
          });
          if (res.errMsg.indexOf("function_not_exist") > 0) {
            alert("版本过低请升级");
          }
        },
      });
    },

    //调用接口获取二维码信息
    getQrCodeInfo(serialNo) {
      this.getDateList(serialNo);
    },

    //获取列表数据
    getDateList(n) {
      if (n) {
        this.pagenumber = 1;
        this.listCards = [];
      }
      this.loading_status = "loading";
      var filterRes = {};
      filterRes.pageno = this.pagenumber;
      filterRes.pagesize = this.pagesize;
      // filterRes.engineerId = this.engineerId;
      filterRes.singleStatus = this.status;
      // filterRes.singleStatus = this.singleStatus;
      filterRes.deviceCode = n ? n : "";
      filterRes.isShowTs = 1;
      this.$http
        .request({
          url: "/apis/patrolRecord/recordList",
          params: filterRes,
        })
        .then((res) => {
          uni.stopPullDownRefresh();
          if (!res.data.data) {
            this.loading_status = "noMore";
          } else if (res.data.data.datas.length < this.pagesize) {
            this.loading_status = "noMore";
          } else {
            this.loading_status = "more";
          }

          if (res.data.code == 0) {
            this.listCards = this.listCards.concat(
              this.formaterData(res.data.data.datas)
            );
          }
        })
        .catch((err) => {
          this.loading_status = "noMore";
        });
    },
    //设置状态颜色
    setTag(val) {
      if (val == 50) {
        return "106";
      } else if (val == 999) {
        return "108";
      } else {
        return "106";
      }
    },
    //筛选条件
    getFilter(filterRes) {
      this.engineerId = filterRes.user;
      this.status = filterRes.status;
      this.listCards = [];
      this.pagenumber = 1;
      this.loading_status = "more";
      this.getDateList();
    },
    //列表数据格式化
    formaterData(data) {
      var resData = [];
      data.forEach((vals, index) => {
        // var WorkOrderNo=vals.id?vals.recordWorkOrderNo:'';//巡检单号
        // var patrolName=vals.id?vals.patrolRecordName:'';//巡检名称
        var combineJSON = {
          id: vals.id,
          noticeId: vals.reportStatusId,
          patrolPlanId: vals.patrolPlanId,
          patrolPlanId: vals.patrolPlanId,
					title: (vals.deviceName||'--')+'/'+(vals.sblxmc||'--'),
					titleNumber:vals.recordWorkOrderNo,
          // title: (vals.recordWorkOrderNo || "") + "-" + vals.reportStatusName,
          // // titleNumber: vals.patrolPlanName,
          // titleNumber: "[" + vals.deviceSerialno + "]" + vals.deviceName,
          contentList: [
            // {
            //   id: 1,
            //   isDouble: true,
            //   labelName: "计划单号",
            //   labelContent: vals.planWorkOrderNo,
            // },
            // {
            //   id: 2,
            //   isDouble: true,
            //   labelName: "设备编号",
            //   labelContent: vals.deviceSerialno,
            // },
            // {
            //   id: 3,
            //   isDouble: true,
            //   labelName: "设备名称",
            //   labelContent: vals.deviceName,
            // },
		
            {
              id: 3,
              isDouble: true,
              labelName: "巡检名称",
              labelContent: vals.patrolRecordName,
            },
            {
              id: 2,
              isDouble: true,
              labelName: "巡检人员",
              labelContent: vals.patrolPersonName,
            },
            {
              id: 4,
              isDouble: false,
              labelName: "计划开始时间",
              labelContent:vals.sortTime || "-",
            },
            {
              id: 5,
              isDouble: false,
              labelName: "计划完成时间",
              labelContent: vals.endTime,
            },
          ],
          extra: vals.reportStatusName,
					tagType: this.setTag(vals.reportStatusId)
        };
        resData.push(combineJSON);
      });
      return resData;
    },
    //查看详情
    toDetail(index, item) {
      //这里需要判断是否是超期未处理。如果是那么就需要传标记，因为后台没有办法处理。
      if (item.noticeId == 999) {
        //超器未处理
        uni.navigateTo({
          url: "patrolDetail?id=" + item.id + "&flag=cq", // 超期 chaoqi
        });
      } else {
        uni.navigateTo({
          url: "patrolDetail?id=" + item.id,
        });
      }
    },
    //搜索巡检
    toSearch() {
      uni.navigateTo({
        url: "patrolSearch",
      });
    },
  },
  onNavigationBarButtonTap(obj) {},
  onBackPress(options) {
    //取消默认的返回事件.
    uni.switchTab({
      url: "../main/main",
    });
    return true;
  },
};
</script>

<style>
page {
  height: 100%;
}
</style>
<style scoped>
.reader-box {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.reader {
  width: 100%;
  /* width: 540rpx; */
  /* /height: 540rpx; */
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.content {
  position: relative;
}

.filter_container {
  position: fixed;
  width: 50%;
  top: var(--window-top);
  background-color: #fff;
  height: 40px;
  z-index: 2;
  padding-top: 7px;
  box-sizing: border-box;
}

>>>.doubleList:nth-of-type(1) {
  width: 60%;
}

>>>.doubleList:nth-of-type(2) {
  width: 40%;
}

>>>.doubleList:nth-of-type(3) {
  width: 60%;
}

>>>.doubleList:nth-of-type(4) {
  width: 40%;
}

>>>.dev-label {
  white-space: nowrap;
}

>>>.select-tab-fixed-top {
  right: 0;
  width: 80%;
  z-index: 2;
  top: var(--window-top);
  white-space: nowrap;
}

>>>.popup-layer {
  position: fixed;
  top: var(--window-top);
  margin-top: 40px;
}

>>>.filter-content-detail {
  /* 	position: relative;
	height: 90px;
	overflow: scroll; */
}

.search_container {
  position: relative;
  padding-left: 30px;
  box-sizing: border-box;
  color: #fff;
  margin: auto;
  width: 80%;
  height: 26px;
  background-color: #409EFF;
  border-radius: 0;
  font-size: 14px;
  line-height: 26px;
}

.search_icon {
  position: absolute;
  left: 5px;
  top: 3px;
}

.fliter_content {
  position: absolute;
  right: 15px;
  left: 85px;
  height: 100%;
  z-index: 2;
}

.arrowright {
  position: absolute;
  right: 30upx;
  bottom: 30upx;
  font-size: 40upx !important;
}

>>>.dev-block__content {
  padding-right: 36upx;
}

>>>.dev-block__header-title-text {
  overflow: auto;
  white-space: pre-wrap !important;
}
</style>
