<template>
  <view>
    <view class="reader-box" v-if="isScaning">
      <view class="reader" id="reader-sbxx"></view>
    </view>
    <view class="page" v-else>
      <view class="uni-flex uni-row">
        <view class="text" style="-webkit-flex: 12; flex: 12">
          <sl-filter :ref="'slFilter'" :topFixed="fixed" :menuList.sync="menuList"
            @result="getEquipAccount"></sl-filter>
        </view>
        <view class="otherFixed" style="width: 40%">
          <!-- <view class="text" @click="showSinglePicker">{{
            deptResult.name
          }}</view> -->
          <view class="text" @click="filterDate">{{
            timeData.begin == ""
              ? "检验日期"
              : timeData.begin + "~" + timeData.end
          }}</view>
        </view>
      </view>
      <view class="example-body" v-if="listCards.length > 0">
        <view v-for="(item, index) in listCards" :key="index" class="example-box" @click="clickDetail(item)">
          <dev-block :title="item.title" :note="item.note" :contentList="item.contentList" :extra="'删除'"
            :approveState="0" @remove="remove(item)"></dev-block>
        </view>
        <view @click="getList" v-if="loadingType != 2" style="text-align: center; color: #333">点击加载更多</view>
        <!-- <uni-load-more
          :loadingType="loadingType"
          :contentText="contentText"
        ></uni-load-more> -->
      </view>
      <view class="example-body" v-else>
        <no-record></no-record>
      </view>
      <uni-calendar ref="calendar" :lunar="false" :range="true" @confirm="confirmDate" />
      <lb-picker ref="picker" mode="multiSelector" :level="level" :pickerValueDefault="[0, 0]" @confirm="pickerConfirm"
        :props="myProps" :list="deptArray"></lb-picker>
      <view class="goHome" @click="goMain()">
        <img src="../../static/img/gohome.png" />
      </view>
    </view>
  </view>
</template>

<script>
import LbPicker from "@/components/lb-picker";
import slFilter from "@/components/xinsoft-sl-filter/xinsoft-sl-filter.vue";
import devBlock from "@/components/xinsoft-dev-block/xinsoft-dev-block.vue";
import uniLoadMore from "@/components/uni-load-more/uni-load-more.vue";
import noRecord from "@/components/xinsoft-no-record/xinsoft-no-record";
import uniCalendar from "@/components/uni-calendar/uni-calendar.vue";
import jweixin from "@/jweixin-module/index.js";
import { Html5Qrcode } from "html5-qrcode";
// import '../../reqrcode/wxCode.js'
export default {
  components: {
    slFilter,
    devBlock,
    uniLoadMore,
    noRecord,
    uniCalendar,
    LbPicker,
  },
  data() {
    return {
      xcjcd:'',
      html5Qrcode: null,
      isScaning: false,
      deptArray: [],
      level: 4,
      myProps: {
        label: "text",
        value: "id",
        children: "children",
      },
      pickerValueDefault: [0, 0],
      deepLength: 2,
      fixed: true,
      filter: {},
      deviceCode: "",
      filterResult: "",
      menuList: [
        {
          title: "任务状态",
          isMutiple: false,
          key: "type",
          detailList: [
            {
              title: "所有的",
              value: 0,
            },
            {
              title: "我发起的",
              value: 1,
            },
            {
              title: "待处理",
              value: 2,
            },
            {
              title: "待审批",
              value: 3,
            },
          ],
          defaultSelectedIndex: [],
        },
      ],
      listCards: [],
      //上拉刷新，下拉加载
      loadingText: "加载中...",
      loadingType: 0, //定义加载方式 0---contentdown  1---contentrefresh 2---contentnomore
      contentText: {
        contentdown: "上拉显示更多",
        contentrefresh: "正在加载...",
        contentnomore: "没有更多数据了",
      },
      pageSize: 5,
      page: 1,
      //日历变量。
      timeData: {
        begin: "",
        end: "",
      },
      deptResult: {
        value: "",
        name: "使用部门",
      },
    };
  },
  onLoad() {
    //使用状态初始化。
    var _this = this;
    // this.$http
    //   .request({
    //     url: "/apis/dict/getDictsByType",
    //     params: {
    //       type: "device_status",
    //     },
    //   })
    //   .then((res) => {
    //     if (res.statusCode == "200") {
    //       _this.menuList[0].detailList = [
    //         {
    //           title: "不限",
    //           value: "",
    //         },
    //       ];
    //       var useType = res.data.datas;
    //       for (let i = 0; i < useType.length; i++) {
    //         var myVal = {
    //           title: useType[i].name,
    //           value: useType[i].id,
    //         };
    //         _this.menuList[0].detailList.push(myVal);
    //       }
    //     }
    // })
    // .catch((err) => {
    //   console.log(err);
    // });

    //生产设备初始化
    this.$http
      .request({
        url: "/apis/dict/getDictsByType",
        params: {
          type: "device_type",
        },
      })
      .then((res) => {
        if (res.statusCode == "200") {
          _this.menuList[1].detailList = [
            {
              title: "不限",
              value: "",
            },
          ];
          var useType = res.data.datas;
          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) => {
        console.log(err);
      });

    //使用部门
    this.$http
      .request({
        url: "/apis/dept/tree",
        method: "GET",
      })
      .then((res) => {
        if (res.statusCode == "200") {
          this.deptArray = res.data.data.children;
        }
      })
      .catch((err) => {
        console.log(err);
      });

    //初始化当前列表。
    _this.searchList({});
    // this.initiateWX();
  },
  onPullDownRefresh: function () {
    //下拉刷新的时候请求一次数据
    this.getEquipAccount(JSON.parse(this.filterResult));
  },
  // onReachBottom: function () {
  //   //触底的时候请求数据，即为上拉加载更多
  //   this.getEquipAccountMore(JSON.parse(this.filterResult));
  // },
  mounted() {
    // this.initiateWX();
  },
  methods: {
    remove(val) {
      let _this = this;
      uni.showModal({
        title: "",
        content: "确定删除吗?",
        success: function (el) {
          if (el.confirm) {
            let ids = [];
            ids.push(val.id);
            _this.$http
              .request({
                url: "/apis/hl/ahgl/xcjc/del",
                data: ids,
              })
              .then((res) => {
                if (res.data.code == 0) {
                  uni.showToast({
                    title: "删除成功",
                    duration: 2000,
                    icon: "none",
                  });
                  _this.page = 1;
                  _this.searchList({});
                } else {
                  uni.showToast({
                    title: res.data.msg,
                    duration: 1000,
                    icon: "none",
                  });
                }
              });
          }
        },
      });
    },
      //搜索框文本变化
    onNavigationBarSearchInputChanged(n) {
      this.page = 1;
      this.xcjcd = n.text;
      this.searchList(JSON.parse(this.filterResult));
    },
    searchList(filterRes) {
      if (this.loadingType !== 0) {
        //loadingType!=0;直接返回
        return false;
      }
      this.loadingType = 1;
      uni.showNavigationBarLoading(); //显示加载动画
      this.filterResult = JSON.stringify(filterRes, null, 2);
      filterRes.pageno = this.page;
      filterRes.pagesize = this.pageSize;
      filterRes.startTime = this.timeData.begin;
      filterRes.endTime = this.timeData.end;
      filterRes.xcjcd = this.xcjcd;
      filterRes.ggxh = this.ggxh;
      // filterRes.deptId = this.deptResult.value;
      this.$http
        .request({
          url: "/apis/hl/ahgl/xcjc/pageList",
          data: filterRes,
        })
        .then((res) => {
          if (!res.data.data.records || res.data.data.records.length == 0) {
            uni.showToast({
              title: "没有更多数据了",
              duration: 2000,
              icon: "none",
            });
            //没有数据
            this.loadingType = 2;
            uni.hideNavigationBarLoading(); //关闭加载动画
            this.listCards = [];
            // return;
          }
          if (res.data.code == 0) {
            this.page++; //每触底一次 page +1
            this.loadingType = 0; //将loadingType归0重置
            uni.hideNavigationBarLoading(); //关闭加载动画
            let resultData = this.formaterData(res.data.data.records);
            this.listCards = resultData;
          }
        })
        .catch((err) => {});
    },
    getList() {
      this.page = 1;
      // this.searchList(JSON.parse(this.filterResult))
      this.getEquipAccountMore(JSON.parse(this.filterResult));
    },
    openQrcode() {
      this.isScaning = true;
      Html5Qrcode.getCameras().then((devices) => {
        if (devices && devices.length) {
          this.html5Qrcode = new Html5Qrcode("reader-sbxx");
          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: "https://www.newbest1.cn/gyhl-app//",
            //  url: window.location.href.split("#")[0],
          },
        })
        .then((res) => {
          if (res.data.code == 0) {
            // console.log(window.location.href.split("#")[0],"测试前————————————————");
            let s = res.data;
            let wxData = JSON.parse(JSON.stringify(res.data));
            wx.config({
              debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
              appId: wxData.appId, // 必填，公众号的唯一标识
              timestamp: wxData.timestamp, // 必填，生成签名的时间戳
              nonceStr: wxData.nonceStr, // 必填，生成签名的随机串
              signature: wxData.signature, // 必填，签名
              jsApiList: ["scanQRCode"], // 必填，需要使用的JS接口列表
            });
            wx.ready(function () {
              console.log("成功");
            });
            wx.error(function (res) {
              console.log(res, "错误");
              // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
            });
            // 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) => {
          console.log(err);
          // uni.showToast({
          //   title: err,
          //   icon: "none",
          //   duration: 2000,
          // });
        });
    },
    onNavigationBarButtonTap() {
      console.log("点击了");
      uni.navigateTo({
        url: "/pages/xcjc/add",
      });
      // this.openQrcode();
    },

    onNavigationBarButtonTap1() {
      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 {
              // let par = eval('('+resultStr+')');
              let par = JSON.parse(resultStr);
              if (par.serialNo) {
                _this.getQrCodeInfo(par.serialNo);
              } else {
                uni.showToast({
                  title: "二维码错误，请扫描正确的二维码",
                  icon: "none",
                  duration: 2000,
                });
              }
            } catch (e) {
              alert(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.deviceCode = serialNo;
      this.getEquipAccount({});
    },

    getEquipAccount(filterRes) {
      this.page = 1;
      this.loadingType = 0;
      this.filterResult = JSON.stringify(filterRes, null, 2);
      filterRes.pageno = this.page;
      filterRes.pagesize = this.pageSize;
      filterRes.startTime = this.timeData.begin;
      filterRes.endTime = this.timeData.end;
      filterRes.deptId = this.deptResult.value;
      filterRes.xcjcd = this.xcjcd;
      this.$http
        .request({
          url: "/apis/hl/ahgl/xcjc/pageList",
          data: filterRes,
        })
        .then((res) => {
          if (!res.data.data.records || res.data.data.records.length == 0) {
            //没有数据
            this.listCards = [];
            uni.hideNavigationBarLoading(); //关闭加载动画
            return;
          }
          if (res.data.code == 0) {
            this.page++; //得到数据之后page+1
            uni.hideNavigationBarLoading();
            uni.stopPullDownRefresh(); //得到数据后停止下拉刷新
            if (res.data.data.records.length > 0) {
              this.listCards = [];
              this.listCards = this.formaterData(res.data.data.records);
            }
          }
        })
        .catch((err) => {});
    },
    getEquipAccountMore(filterRes) {
      if (this.loadingType !== 0) {
        //loadingType!=0;直接返回
        return false;
      }
      this.loadingType = 1;
      uni.showNavigationBarLoading(); //显示加载动画
      this.filterResult = JSON.stringify(filterRes, null, 2);
      filterRes.pageno = this.page;
      filterRes.pagesize = this.pageSize;
      filterRes.startTime = this.timeData.begin;
      filterRes.endTime = this.timeData.end;
      filterRes.xcjcd = this.xcjcd;
      this.$http
        .request({
          url: "/apis/hl/ahgl/xcjc/pageList",
          data: filterRes,
        })
        .then((res) => {
          if (!res.data.data.records || res.data.data.records.length == 0) {
            uni.showToast({
              title: "没有更多数据了",
              duration: 2000,
              icon: "none",
            });
            //没有数据
            this.loadingType = 2;
            uni.hideNavigationBarLoading(); //关闭加载动画
            return;
          }
          if (res.data.code == 0) {
            this.page++; //每触底一次 page +1
            this.loadingType = 0; //将loadingType归0重置
            uni.hideNavigationBarLoading(); //关闭加载动画
            var resultData = this.formaterData(res.data.data.records);
            this.listCards = [...this.listCards, ...resultData];
          }
        })
        .catch((err) => {});
    },
    clickDetail(val) {
      const rwzt = val.rwzt;
      const state = [
        { zt: "待处理", url: "/pages/xcjc/detail" },
        { zt: "待审批", url: "/pages/xcjc/audit" },
      ];
      let url = state.filter((item) => item.zt == rwzt);
      if (url && url.length == 1) {
        uni.navigateTo({
          url: url[0]["url"] + "?id=" + val.id,
        });
      } else {
        uni.navigateTo({
          url: "/pages/xcjc/detail" + "?id=" + val.id,
        });
      }
    },
    showSinglePicker() {
      this.$refs.picker.show();
    },
    // pickerConfirm(e){
    // 	var value = e.value;

    // 	this.deptResult.value = value[1]?value[1]:value[0];
    // 	var name = e.label;
    // 	if(!value[1]){
    // 		name = name.substring(0,name.length-1);
    // 	}
    // 	this.deptResult.name = name;
    // 	this.getEquipAccount(JSON.parse(this.filterResult));
    // },
    pickerConfirm(e) {
      var value = e.value;
      console.log(value);
      var name = "";
      this.filter.deptId = "";
      if (value[1] == "-") {
        name = e.item[0].text;
        this.deptResult.value = value[0];
      } else {
        this.deptResult.value = value[2] ? value[2] : value[1];
        if (value[2]) {
          // name = name.substring(0,name.length-2);
          name = e.item[0].text + "/" + e.item[1].text + "/" + e.item[2].text;
        } else {
          name = e.item[0].text + "/" + e.item[1].text;
        }
      }
      console.log(this.deptResult.value);
      this.deptResult.name = name;
      this.listCards = [];
      this.page = 1;
      this.loading_status = "more";
      this.getEquipAccount(JSON.parse(this.filterResult));
    },
    formaterData(data) {
      var resData = [];
      data.forEach((vals, index) => {
        var combineJSON = {
          rwzt: vals.rwzt,
          id: vals.id,
          title: vals.xcjcd + "一" + vals.rwzt,
          //   titleNumber:'['+vals.serialno+']',
          contentList: [
            {
              id: 1,
              isDouble: true,
              labelName: "检查日期",
              labelContent: vals.jcrq,
            },
            {
              id: 2,
              isDouble: true,
              labelName: "检察人员",
              labelContent: vals.jcry,
            },
            {
              id: 3,
              isDouble: true,
              labelName: "车间",
              labelContent: vals.cj,
            },
            {
              id: 4,
              isDouble: true,
              labelName: "负责人",
              labelContent: vals.zrr,
            },
            {
              id: 5,
              isDouble: false,
              labelName: "完成时间",
              labelContent: vals.yqwcrq,
            },
          ],
          //   note: "设备关联信息",
          extra: vals.status_name,
          tagType: vals.using_status + "",
        };
        resData.push(combineJSON);
      });
      return resData;
    },
    /**
     * @param {Object} e
     * 跳转到筛选界面
     */
    showFilter() {
      uni.navigateTo({
        url: "eqFilter",
      });
    },
    /*
     * 日历相关方法。
     */
    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.page =1
        this.searchList(JSON.parse(this.filterResult));
      }
    },
  },
  /**
   * 当 searchInput 配置 disabled 为 true 时触发
   */
  onNavigationBarSearchInputClicked(e) {
    uni.navigateTo({
      url: "eqSearch",
    });
  },
  /**
   *  点击导航栏 buttons 时触发 扫一扫
   */
  onNavigationBarButtonTap() {
    uni.scanCode({
      onlyFromCamera: true,
      success: function (res) {
        console.log("条码类型：" + res.scanType);
        console.log("条码内容：" + res.result);
      },
    });
  },
  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%);
}

>>>.picker-item .lb-picker-column .lb-picker-column-label {
  -webkit-transition: all 0.3s;
  transition: all 0.3s;
  line-height: 55px !important;
}

>>>.select-tab-fixed-top {
  left: 0;
  width: 80%;
  z-index: 2;
  white-space: nowrap;
}

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