<template>
  <view>
    <view class="reader-box" v-if="isScaning">
      <view class="reader" id="reader"></view>
    </view>
  <view class="page" v-else>
    <view class="uni-flex uni-row">
      <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>
      <view class="text">
        <xinsoft-sl-filter
          :menuList.sync="menuList"
          @result="getFilter"
        ></xinsoft-sl-filter>
      </view>
      <view class="otherFixed98">
        <view class="text" @click="selectOperater">{{ user.name }}</view>
      </view>
      <!-- <view class="otherFixed" style="width: 30%; right: 5px">
        <view class="text" style="width: 100%" @click="filterDate">{{
          timeData.begin == ""
            ? "计划时间"
            : timeData.begin + "~" + timeData.end
        }}</view>
      </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>
    <uni-load-more :status="loading_status"></uni-load-more>
    <uni-calendar
      ref="calendar"
      :lunar="false"
      :range="true"
      @confirm="confirmDate"
    />
    <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 uniCalendar from "@/components/uni-calendar/uni-calendar.vue";
import chooseUserSingle from "@/components/xinsoft-search-list/chooseUserSingle.vue";
import { Html5Qrcode } from 'html5-qrcode';

// import jweixin from "@/jweixin-module/index.js";

export default {
  components: {
    xinsoftSlFilter,
    devBlock,
    uniIcons,
    uniLoadMore,
    uniCalendar,
    chooseUserSingle
  },
  data() {
    return {
      html5Qrcode: null,
      isScaning: false,
      show_search_user: false,
      listCards: [],
      filterResult: {
        // singleStatus: 56,
        status:'',
      },
      status:'',
      pagenumber: 1, //当前第几页
      pagesize: 5, //每页加载数据条数
      menuList: [
        {
          title: "状态",
          isMutiple: false,
          isSort: true,
          key: "status",
          detailList: [
            {
              title: "全部",
              value: '',
            },
            {
              title: "待处理",
              value: 56,
            },
            {
              title: "关闭",
              value: 167,
            },
            {
              title: "超期未处理",
              value: 999,
            },
            {
              title: "已完成",
              value: 131,
            }
          ],
          defaultSelectedIndex: [0],
          // },
          // {
          // 	'title': '责任人',
          // 	'isMutiple': false,
          // 	'key': 'engineer_id',
          // 	'detailList': [],
          // 	'defaultSelectedIndex': []
        },
      ],
      user: {
        value: "",
        name: "保养责任人",
      },
      loading_status: "more", //more（loading前）、loading（loading中）、noMore（没有更多了）
      timeData: {
        begin: "",
        end: "",
      },
    };
  },
  created() {
    this.getDateList();
    var userInfo = uni.getStorageSync("userInfo");
    // //责任人人初始化
    // var _this = this;
    // this.$http.request({
    //   url: '/apis/common/getUsers',
    //   params:{
    //   	 deptId:userInfo.deptId
    //   }
    // }).then(res=>{
    // 	if(res.statusCode == '200'){
    // 		_this.menuList[1].detailList = [
    // 			{
    // 				'title': '不限',
    // 				'value': ''
    // 			}
    // 		];
    // 		var useType = res.data.datas;
    // 		console.log(useType)
    // 		for (let i = 0; i < useType.length; i++) {
    // 		    var myVal=
    // 		    	{
    // 		    		'title': useType[i].name,
    // 		    		'value': useType[i].id
    // 		    	}
    // 		    _this.menuList[1].detailList.push(myVal);
    // 		}
    // 	}
    // }).catch(err=>{
    // });
  },
  //滚动到底部加载下一页
  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();
  },
  methods: {
     // 选择责任人
     selectOperater() {
      this.show_search_user = true;
    },
    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();
      }
    },
    //获取微信相关
    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;
            jweixin.config({
              beta: true,
              debug: false, // 开启调试模式,调用的所有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",
              ],
            });
          } 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("你点击了按钮"); // 允许从相机和相册扫码
      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.filterResult.deviceCode = serialNo;
      this.getDateList(1);
    },

    //获取列表数据
    getDateList(n) {
      if (n == 1) {
        this.pagenumber = 1;
        this.listCards = [];
      }
      this.loading_status = "loading";
      var filterRes = this.filterResult;
      filterRes.pageno = this.pagenumber;
      filterRes.pagesize = this.pagesize;
      filterRes.start_time = this.timeData.begin;
      filterRes.end_time = this.timeData.end;
      filterRes.status = this.status;
      this.$http
        .request({
          url: "/apis/upkeepPlan/addValidRecords",
          params: filterRes,
        })
        .then((res) => {
          uni.stopPullDownRefresh();
          if (!res.data.data || res.data.data.length == 0) {
            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";
        });
    },

    getFilter(filterRes) {
      this.listCards = [];
      this.pagenumber = 1;
      this.loading_status = "more";
      this.filterResult = filterRes;
      this.status = filterRes.status;
      this.getDateList();
    },
    //列表数据格式化
    formaterData(data) {
      var resData = [];
      data.forEach((vals, index) => {
        var combineJSON = {
          id: vals.id,
          noticeId: vals.noticeId,
          patrolPlanId: vals.patrolPlanId,
          title:vals.device_serialno + "/" + vals.deviceName,
          // title: vals.work_orderNo
          //   ? vals.work_orderNo + "-" + vals.result_name
          //   : vals.result_name,
            titleNumber: vals.work_orderNo
            ? vals.work_orderNo:'--',
          // titleNumber: "[" + vals.device_serialno + "]" + vals.deviceName,
          contentList: [
            {
              id: 1,
              isDouble: true,
              labelName: "保养名称",
              labelContent: vals.planName || "",
            },
            {
              id: 2,
              isDouble: true,
              labelName: "保养责任人",
              labelContent: vals.username,
            },
            // {
            //   id: 3,
            //   isDouble: true,
            //   labelName: "保养工时",
            //   labelContent: vals.man_hour ? vals.man_hour + "小时" : "-",
            // },
            // {
            //   id: 4,
            //   isDouble: true,
            //   labelName: "保养工时费",
            //   labelContent: vals.manhourCost ? vals.manhourCost + "元" : "-",
            // },
            // {
            //   id: 5,
            //   isDouble: true,
            //   labelName: "保养材料费",
            //   labelContent: vals.cost ? vals.cost + "元" : "-",
            // },
            {
              id: 6,
              isDouble: false,
              labelName: "计划开始时间",
              labelContent: vals.start_time,
            },
            {
              id: 7,
              isDouble: false,
              labelName: "计划结束时间",
              labelContent: vals.end_time || "-",
            },
          ],
          extra: vals.result_name,
					tagType: this.setTag(vals.result)
        };
        resData.push(combineJSON);
      });
      return resData;
    },
    //设置状态颜色
		setTag(val) {
				if (val == 50) {
					return "106";
				} else if (val == 999) {
					return "108";
				} else {
					return "106";
				}
			},
    //查看详情
    toDetail(index, item) {
      uni.navigateTo({
        url: "upkeepDetail?id=" + item.id,
      });
    },
    //搜索巡检
    toSearch() {
      uni.navigateTo({
        url: "keepSearch",
      });
    },
    filterDate() {
      this.$refs.calendar.open();
    },
    confirmDate(e) {
      if (e.range.begin && e.range.end) {
        this.timeData = {
          begin: e.range.begin + " 00:00:00",
          end: e.range.end + " 00:00:00",
        };
        this.listCards = [];
        this.pagenumber = 1;
        this.loading_status = "more";
        this.getDateList();
      }
    },
  },
  onNavigationBarButtonTap(obj) {
    uni.navigateTo({
      url: "keepStep1",
    });
  },
  onBackPress(options) {
    //取消默认的返回事件.
    uni.switchTab({
      url: "../main/main",
    });
    return true;
  },
};
</script>

<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%);
	}
>>> .dev-label {
  white-space: nowrap;
}
>>> .select-tab-fixed-top {
  left: 20%;
  right: 0%;
  width: 80%;
}
.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>
