<template>
  <view>
    <!-- 顶部标签操作栏 -->
    <cu-custom bgColor="bg-gradual-blueness" :isBack="true" :isRingt="true">
      <block slot="backText">返回</block>
      <block slot="content">点检清单</block>
    </cu-custom>

    <!-- 检索固定栏 -->
    <view class="top-fixed">
      <scroll-view scroll-x class="bg-white nav" scroll-with-animation :scroll-left="scrollLeft">
        <view class="flex text-center">
          <view class="cu-item flex-sub" :class="index === tabCurrent ? 'text-blue cur' : ''"
            v-for="(item, index) in tabNav" :key="index" @tap="tabSelect" :data-id="index">
            {{ item }}
          </view>
        </view>
      </scroll-view>
      <view class="line"></view>
      <view>
        <view class="cu-bar search bg-white">
          <input class="search-form radius" v-model="searchQuery" placeholder="请输入点检人或清单名" />
          <view class="action">
            <button class="cu-btn bg-green shadow-blur radius" @click="search()">
              搜索
            </button>
            <button class="cu-btn bg-blue shadow-blur radius" @click="handleReset()" style="margin-left: 10px">
              重置
            </button>
          </view>
        </view>
        <view class="line"></view>
      </view>
    </view>

    <block v-if="tabCurrent === 0">
      <scroll-view class="dy-scroll-nobg" @scrolltolower="fnScrolltolower" scroll-y
        :style="'top:' + sTop + 'px;height:calc(100vh - ' + totalHeight + 'px)'">
        <view v-if="checkPointList.length > 0">
          <view class="dy-card" v-for="item in checkPointList" :key="item.LISTMANAGER_ID"
            @click="checkDateBeforeNavigate(item)">
            <view class="dy-card-title">
              <text>
                <text v-if="item.USER_ID === loginUserId" style="margin-right: 10upx; color: #07bb07">★</text>
                {{ item.INSPECTION_NAME }}
              </text>
              <text class="cuIcon-right f30 text-gray"></text>
            </view>
            <view class="dy-card-content">
              <view class="dy-sub-stitle">
                <text class="text-grey">企业内部编码：{{ item.DEVICE_ID }}</text>
              </view>
              <view class="dy-sub-stitle">
                <text class="text-grey">设备类型：{{ item.DEVICE_TYPE_NAME }}</text>
                <text class="text-grey">点检时间：{{ item.CHECK_DATE }}</text>
              </view>
              <view class="dy-sub-stitle">
                <text class="text-grey">下次点检时间：{{ item.NEXTCHECK_DATE }}</text>
                <text class="text-grey">点检人：{{ item.CHECKER }}</text>
              </view>
            </view>
          </view>
        </view>
        <view v-else-if="dataFlag == 'noData'" class="dy-null">
          <view class="dy-null-img">
            <image :src="background[dataFlag].url" mode=""></image>
          </view>
          <view class="dy-null-title">
            {{ background[dataFlag].msg }}
          </view>
        </view>
      </scroll-view>
    </block>

    <block v-if="tabCurrent === 1">
      <scroll-view class="dy-scroll-nobg" @scrolltolower="fnScrolltolower" scroll-y
        :style="'top:' + sTop + 'px;height:calc(100vh - ' + totalHeight + 'px)'">
        <view v-if="checkHistoryList.length > 0">
          <view class="dy-card" v-for="item in checkHistoryList" :key="item.ID"
            @click="navigateToRecordView(item.CHECK_ID)">
            <view class="dy-card-title">
              <text>设备类型：{{ item.DEVICE_ID }}</text>
            </view>
            <view class="dy-card-content">
              <!--              <view class="dy-sub-stitle">-->
              <!--                <text class="text-grey">设备名称：{{item.EQUIP_NAME}}</text>-->
              <!--              </view>-->
              <view class="dy-sub-stitle">
                <text class="text-grey">点检时间：{{ item.CHECKERTIME }}</text>
              </view>
              <view class="dy-sub-stitle">
                <text class="text-grey">检查部门：{{ formatDepartments(item.OTHER) }}</text>
              </view>
              <view class="dy-sub-stitle">
                <text class="text-grey">检查人：{{ formatCheckers(item.OTHER) }}</text>
              </view>
              <view class="dy-sub-stitle">
                <text class="text-grey">备注：{{ item.REMARK }}</text>
              </view>
              <view class="dy-sub-stitle">
                <text class="text-grey">
                  点检结论：{{ item.FINISHED == '1' ? '完成' : '未完成' }}
                </text>
              </view>
              <view class="dy-sub-stitle">
                <text class="text-grey">签字图片：</text>
                <image :src="baseImgPath + item.FILEPATH" mode="aspectFit" style="width: 100px; height: 100px" />
              </view>
            </view>
          </view>
        </view>
        <view v-else-if="dataFlag == 'noData'" class="dy-null">
          <view class="dy-null-img">
            <image :src="background[dataFlag].url" />
          </view>
          <view class="dy-null-title">
            {{ background[dataFlag].msg }}
          </view>
        </view>
        <view class="cu-tabbar-height"></view>
      </scroll-view>
    </block>

    <yk-authpup ref="authpup" type="top" @changeAuth="$noMultipleClicks(scan)" :permissionID="permissionID" />
  </view>
</template>

<script>
import {
  basePath,
  loginUser,
  loginSession,
  baseImgPath
} from '@/common/tool.js'
import tkiTree from '@/components/select-tree/select-tree.vue'
import ykAuthpup from '@/components/yk-authpup/yk-authpup'

export default {
  components: { tkiTree, ykAuthpup },

  data() {
    return {
      /** 公共图片路径,由外部引入并使用 */
      baseImgPath,
      /** 权限ID */
      permissionID: '',
      /** tab 切换状态 */
      tabCurrent: 0,
      sTop: 0,
      /** 总页数高度 */
      totalHeight: 0,
      /** 滚动左侧距离 */
      scrollLeft: 0,
      /** 每页展示的页数 */
      showCount: 10,
      /** 点检清单信息的总页数 */
      checkPointTotalPage: 0,
      /** 点检历史记录的总页数 */
      checkHistoryTotalPage: 0,
      /** 点检清单信息的当前页数 */
      checkPointCurrentPage: 0,
      /** 点检历史记录的当前页数 */
      checkHistoryCurrentPage: 0,
      /** tab切换栏标题 */
      tabNav: ['点检清单信息', '点检历史记录'],
      /** 存储点检清单信息列表 */
      checkPointList: [],
      /** 存储点检历史记录列表 */
      checkHistoryList: [],
      totalCheckPointList: [],
      totalCheckHistoryList: [],
      /** 传递搜索关键词 */
      searchQuery: '',
      /** 当前登录的用户ID */
      loginUserId: '',
      /** 是否已结束请求的标识 */
      isEnd: true,
      initflag: false,
      /** 标识点检清单信息的列表是否全部加载完成 */
      allDataLoadedPoint: false,
      /** 标识点检历史记录的列表是否全部加载完成 */
      allDataLoadedHistory: false,
      /** 空数据标识 */
      dataFlag: 'noData',
    }
  },

  onLoad() {
    loginSession();
    this.handleReset();
    this.loginUserId = loginUser.USER_ID; // 存储用户唯一ID
    this.background = require('@/common/background.json'); // 存储背景主题色
  },

  onReady() {
    let that = this;
    let CustomBar = this.CustomBar;
    uni.getSystemInfo({
      // 调用uni-app接口获取屏幕高度
      success(res) {
        // 成功回调函数
        let titleH = uni.createSelectorQuery().select('.top-fixed'); // 想要获取高度的元素名（class/id）
        titleH
          .boundingClientRect(data => {
            that._data.sTop = data.height // 计算高度：元素高度=窗口高度-元素距离顶部的距离（data.top）
            that.totalHeight = data.height + CustomBar
          })
          .exec();
      }
    });
  },

  onShow() {
    var _this = this;
    if (_this.initflag) {
      _this.initflag = false;  // 重置标志位
      _this.handleReset(); // 重置
      _this.$forceUpdate();   // 强制刷新组件
    }
  },

  methods: {
    /**
     * 处理清空重置
     */
    handleReset() {
      this.searchQuery = ''; // 重置搜索框内容
      if (this.tabCurrent === 0) {
        this.checkPointList = []; // 清空检点清单信息列表的数据
        this.checkPointCurrentPage = 0;
        // 请求检点清单信息列表
        this.getData();
      } else {
        this.checkHistoryList = []; // 清空点击历史记录列表的数据
        this.checkHistoryCurrentPage = 0;
        // 请求历史记录列表
        this.getHistoryData();
      }
    },
    /**
     * tab 栏切换选择动作处理
     */
    tabSelect(e) {
      this.tabCurrent = e.currentTarget.dataset.id; // 设置当前选中的 tab 项
      this.scrollLeft = (e.currentTarget.dataset.id - 1) * 60;
      if (e.currentTarget.dataset.id === 0) {
        if (this.checkPointTotalPage <= this.checkPointCurrentPage) return;
        // 请求检点清单信息列表
        this.getData();
      }
      if (e.currentTarget.dataset.id === 1) {
        if (this.checkHistoryTotalPage === 0 && this.checkHistoryCurrentPage === 0) {
          this.getHistoryData();
          return;
        };
        if (this.checkHistoryTotalPage <= this.checkHistoryCurrentPage) return;
        // 请求历史记录列表
        this.getHistoryData();
      }
    },
    /**
     * 搜索按钮逻辑处理
     */
    search() {
      if (this.tabCurrent === 0) {
        this.checkPointList = [];
        this.checkPointCurrentPage = 0;
        this.getData();
      } else {
        this.checkHistoryList = [];
        this.checkHistoryCurrentPage = 0;
        this.getHistoryData();
      }
    },
    /**
     * 请求检点清单信息列表
     */
    async getData() {
      let _this = this;
      uni.showLoading({
        title: '加载中'
      });
      uni.request({
        url: basePath + '/app/recordItems/recordList',
        method: 'POST',
        dataType: 'json',
        header: {
          'Content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          USER_ID:loginUser.USER_ID,
          USER_NAME: loginUser.NAME,
          CORPINFO_ID: loginUser.CORPINFO_ID,
          showCount: _this.showCount,
          currentPage: _this.checkPointCurrentPage,
          KEYWORDS: _this.searchQuery,
        },
        success: function (res) {
          if (res.data.result === 'success') {
            var content = res.data.varList
            _this.totalPage = res.data.page.totalPage
            // 点检清单信息
            _this.checkPointList = _this.checkPointList.concat(content);
            _this.checkPointTotalPage = res.data.page.totalPage;
            _this.checkPointCurrentPage = res.data.page.currentPage;
            if (res.data.page.totalPage === res.data.page.currentPage) {
              _this.allDataLoadedPoint = true;
            }
            uni.hideLoading()
          } else {
            uni.showToast({
              icon: 'none',
              title: '系统异常',
              duration: 2000
            })
          }
        },
        fail: function (error) {
          uni.showToast({
            icon: 'none',
            title: '系统异常',
            duration: 2000
          });
          uni.hideLoading();
        },
        complete: function () {
          uni.hideLoading();
        }
      });
    },
    /**
     * 获取点检历史记录列表
     */
    getHistoryData() {
      let _this = this;
      uni.showLoading({
        title: '加载中'
      });
      uni.request({
        url: basePath + '/app/recordslog/list',
        method: 'POST',
        dataType: 'json',
        header: {
          'Content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          USER_NAME: loginUser.NAME,
          CORPINFO_ID: loginUser.CORPINFO_ID,
          showCount: _this.showCount,
          currentPage: _this.checkHistoryCurrentPage,
          KEYWORDS: _this.searchQuery, // 传递搜索关键词
        },
        success: function (res) {
          if (res.data.result === 'success') {
            var content = res.data.varList;
            _this.checkHistoryTotalPage = res.data.page.totalPage;
            _this.checkHistoryCurrentPage = res.data.page.currentPage;
            _this.checkHistoryList = _this.checkHistoryList.concat(content);
            if (res.data.page.totalPage === res.data.page.currentPage) {
              _this.allDataLoadedHistory = true;
            }
            uni.hideLoading();
          } else {
            uni.showToast({
              icon: 'none',
              title: '系统异常',
              duration: 2000
            });
          }
        }
      });
    },
    /**
     * 列表滚动到底部触发处理
     */
    fnScrolltolower() {
      if (this.tabCurrent === 0) {
        if (this.allDataLoadedPoint) return;
        this.checkPointCurrentPage = this.checkPointCurrentPage + 1;
        if (this.checkPointTotalPage >= this.checkPointCurrentPage) {
          // 请求检点清单信息列表
          this.getData();
        }
      } else {
        if (this.allDataLoadedHistory) return;
        this.checkHistoryCurrentPage = this.checkHistoryCurrentPage + 1;
        if (this.checkHistoryTotalPage >= this.checkHistoryCurrentPage) {
          // 请求历史记录列表
          this.getHistoryData();
        }
      }
    },
    /**
     * 点击跳转事件
     */
    checkDateBeforeNavigate(item) {
      const currentDate = new Date().toISOString().split('T')[0];
      const checkDate = item.CHECK_DATE;
      if (currentDate < checkDate) {
        uni.showToast({
          icon: 'none',
          title: '当前时间未到点检日期',
          duration: 2000
        });
      } else {
        this.goToList({ equipType: item.DEVICE_TYPE, ID: item.ID });
      }
    },
    /**
     * 检查部门格式化显示
     */
    formatDepartments(other) {
      if (!other) {
        return ''
      }
      try {
        const otherArray = JSON.parse(other)
        return otherArray.map(o => o.DEPARTMENT_NAME).join(', ')
      } catch (e) {
        return ''
      }
    },
    /**
     * 检查人格式化显示
     */
    formatCheckers(other) {
      if (!other) {
        return ''
      }
      try {
        const otherArray = JSON.parse(other)
        return otherArray.map(o => o.USER_NAME).join(', ')
      } catch (e) {
        return ''
      }
    },
    /**
     * 去到列表项的详情页面
     */
    goToList(params) {
      const { equipType, ID } = params;
      uni.navigateTo({
        url: `/pages/application/recordItems/info?equipType=${equipType}&CHECK_ID=${ID}`
      })
    },
    /**
     * 导航至记录预览页面
     */
    navigateToRecordView(CHECK_ID) {
      uni.navigateTo({
        url: `/pages/application/recordItems/view?CHECK_ID=${CHECK_ID}`
      })
    },
    /**
     * 打开权限组件
     */
    openAuth(permissionID) {
      this.permissionID = permissionID;
      setTimeout(() => {
        this.$refs['authpup'].open();
      }, 200);
    },
    /**
     *  二维码处理
     */
    scan() {
      uni.scanCode({
        success: function (response) {
          let flag = false
          let listId = response.result
          for (
            let i = 0, lens = this.totalCheckPointList.length;
            i < lens;
            i++
          ) {
            if (this.totalCheckPointList[i].LISTMANAGER_ID === listId) {
              flag = true
              this.goToList({
                listId: this.totalCheckPointList[i].LISTMANAGER_ID,
                listName: this.totalCheckPointList[i].NAME,
                userid: this.totalCheckPointList[i].USER_ID,
                BAO_BAO_TYPE: this.totalCheckPointList[i].BAO_BAO_TYPE,
                HIDDEN_RISKSTANDARD: '1'
              })
              break
            }
          }
          for (
            let i = 0, lens = this.totalCheckHistoryList.length;
            i < lens;
            i++
          ) {
            if (this.totalCheckHistoryList[i].CUSTOM_ID == listId) {
              flag = true
              this.goToList({
                listId: this.totalCheckPointList[i].CUSTOM_ID,
                listName: this.totalCheckPointList[i].NAME,
                userid: this.totalCheckPointList[i].USER_ID,
                BAO_BAO_TYPE: this.totalCheckPointList[i].BAO_BAO_TYPE,
                HIDDEN_RISKSTANDARD: '2'
              })
              break
            }
          }
          if (!flag) {
            uni.showToast({
              title: '无法检查该清单',
              duration: 2000
            })
          }
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.dy-list {
  background: #fff;
  margin-top: 2upx;
}

.dy-card {
  background-color: #fff;
  border-radius: 10upx;
  margin: 30upx;
}

.dy-stitle {
  margin: 16upx 0;
}

.dy-sub-stitle {
  margin: 16upx 0;
  display: flex;
  justify-content: space-between;
}

.dy-card-title {
  display: flex;
  justify-content: space-between;
  border-bottom: 1px solid #eee;
  min-height: 80upx;
  line-height: 80upx;
  padding: 0 30upx;
}

.dy-card-content {
  padding: 0upx 30upx 30upx;
}
</style>
