<template>
  <view>
    <view class="reader-box" v-if="isScaning">
      <view class="reader" id="reader"></view>
    </view>
    <view 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
        :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"
          @click="clickDetail"
        ></dev-block>
        <uni-icons
          type="arrowright"
          size="20"
          color="#666"
          class="arrowright"
        ></uni-icons>
      </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 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: "56",
      level: "",
      deviceCode: "",
      pagenumber: 1, //当前第几页
      pagesize: 5, //每页加载数据条数
      menuList: [
        {
          title: "故障等级",
          isMutiple: false,
          key: "level",
          detailList: [],
          defaultSelectedIndex: [],
        },
        {
          title: "任务状态",
          isMutiple: false,
          isSort: true,
          key: "status",
          detailList: [
            {
              title: "待处理",
              value: "56",
            },
            {
              title: "待验收",
              value: "57",
            },
            {
              title: "所有的",
              value: "",
            },
          ],
          defaultSelectedIndex: [0],
        },
        // {
        // 	'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() {
    this.getDateList();

    //任务等级初始化
    var _this = this;
    this.$http
      .request({
        url: "/apis/dict/getDictsByType",
        params: {
          type: "task_level",
        },
      })
      .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) => {});

    //责任人初始化
    // var _this = this;
    // var userInfo  = uni.getStorageSync('userInfo');
    // this.$http.request({
    //   url: '/apis/common/getUsers',
    //    params:{
    // 		deptId:userInfo.deptId
    //   }
    // }).then(res=>{
    // 	if(res.statusCode == '200'){
    // 		_this.menuList[2].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[2].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();
  },
  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: {
    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;
    },
    getQrCodeInfo(serialNo) {
      this.deviceCode = serialNo;
      this.getDateList();
    },
    //获取列表数据
    getDateList() {
      this.loading_status = "loading";
      var filterRes = {};

      filterRes.pageno = this.pagenumber;
      filterRes.pagesize = this.pagesize;
      filterRes.engineerId = this.engineerId;
      filterRes.singleStatus = this.status;
      filterRes.level = this.level;
      filterRes.deviceCode = this.deviceCode ? this.deviceCode : "";
      this.$http
        .request({
          url: "/apis/repairEvent/eventList",
          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.level = filterRes.level;
      this.listCards = [];
      this.pagenumber = 1;
      this.loading_status = "more";
      this.getDateList();
    },
    formaterData(data) {
      var resData = [];
      data.forEach((vals, index) => {
        var combineJSON = {
          id: vals.reventId,
          title: vals.deviceSerialno + "/" + vals.deviceName,
          // title: vals.workOrderNo+"-"+vals.reventStatusName,
          titleNumber: vals.workOrderNo + "-" + vals.reventLevelName,
          // titleNumber: vals.deviceSerialno?"[" + vals.deviceSerialno + "]" + vals.deviceName:' ',
          contentList: [
            {
              id: 1,
              isDouble: true,
              labelName: "报修人",
              labelContent: vals.createUserName,
            },
            {
              id: 2,
              isDouble: true,
              labelName: "维修责任人",
              labelContent: vals.engineerUserName,
            },
            {
              id: 3,
              isDouble: false,
              labelName: "报修时间",
              labelContent: vals.createTime,
            },
            {
              id: 4,
              isDouble: false,
              labelName: "要求完成时间",
              labelContent: vals.planTime,
            },
            // {
            // 	id: 3,
            // 	isDouble: true,
            // 	labelName: '维修部门',
            // 	labelContent: vals.engineerDeptName
            // },
          ],
          extra: vals.reventStatusName,
          tagType: this.setTag(vals.reventStatusId),
          // reventStatusName:vals.reventStatusName
        };
        resData.push(combineJSON);
      });
      return resData;
    },
    //查看详情
    toDetail(index, item) {
      if (item.reventStatusName == "暂存") {
        uni.removeStorageSync("repairInfo");
        //需要跳转到设备编辑
        uni.navigateTo({
          url: "addRepair?id=" + item.id,
        });
      } else {
        uni.removeStorageSync("repairDealInfo");
        uni.navigateTo({
          url: "repairDetail?id=" + item.id,
        });
      }
    },
    //搜索
    toSearch() {
      uni.navigateTo({
        url: "repairSearch",
      });
    },
    //跳转到维修记录界面。
    torepairRecord() {
      uni.navigateTo({
        url: "repairRecord",
      });
    },
    //跳转到新增界面
    toAddRepair() {
      uni.navigateTo({
        url: "addRepair",
      });
    },
  },
  onNavigationBarButtonTap(obj) {
    if (obj.id == "add") {
      uni.removeStorageSync("repairInfo");
      //去故障维修，新增。
      this.toAddRepair();
    } else if (obj.id == "scan") {
      //去维修记录
      this.openQrcode();
    } else {
      //去维修记录
      this.torepairRecord();
    }
  },
  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%);
}
>>> .select-tab-fixed-top {
  right: 0;
  width: 80%;
}

.arrowright {
  position: absolute;
  right: 30upx;
  bottom: 30upx;
  font-size: 40upx !important;
}
>>> .dev-block__content {
  padding-right: 36upx;
}
>>> .select-tab .select-tab-item,
>>> .select-tab-fixed-top .select-tab-item {
  display: -webkit-box;
  display: -webkit-flex;
  display: flex;
  -webkit-box-pack: center;
  -webkit-justify-content: center;
  justify-content: center;
  -webkit-box-align: center;
  -webkit-align-items: center;
  align-items: center;
  margin: 5px 3%;
  /* background: #F6F6F6; */
  border-radius: 40px;
  width: 50% ！important;
  width: 30% !important;
}
</style>
