<template>
  <view class="container py2">
    <!-- 标准信息：与 PC 端 Detail 保持一致 -->
    <view class="mx3 p3 bg-color-white" style="border-radius: 16rpx">
      <view class="f-size-30 main-color-text pb-2">标准信息</view>
      <equipment-line title="设备名称" :content="infoData.sbName" />
      <equipment-line title="设备编码" :content="infoData.sbNo" />
      <equipment-line title="标准编码" :content="modelStandard.no" />
      <equipment-line title="检查类型" :content="getMapText(typeMap, modelStandard.type)" />
      <equipment-line title="计划周期"
        :content="(modelStandard.period || '') + getMapText(periodTypeMap, modelStandard.periodType)" />
      <equipment-line title="维护等级" :content="getMapText(levelMap, modelStandard.level)" />
      <equipment-line title="标准工时" :content="modelStandard.standardHours" />
      <equipment-line title="动作类型" :content="getMapText(actionTypeMap, modelStandard.actionType)" />
      <equipment-line title="部位" :content="modelStandard.partName" />
      <equipment-line title="要求" :content="modelStandard.requirement" />
      <equipment-line title="备注" :content="modelStandard.remark" />
    </view>
    <view class="m3 p3 bg-color-white" style="border-radius: 16rpx">
      <view class="pb-3 border-bottom">
        <view class="f-size-30 main-color-text w200">检查项目</view>
        <view class="f-size-26 text-color-3 border-bottom py2" v-for="(item, index) in requirementList" :key="index">
          <view class="d-flex text-color-6">
            <view class="w180">保养周期：</view>
            <view class="text-color-3">{{ item.period }}</view>
          </view>
          <view class="d-flex text-color-6">
            <view class="w180">管理项目：</view>
            <view class="text-color-3">{{ item.manageItem }}</view>
          </view>
          <view class="d-flex text-color-6">
            <view class="w180">检查项目：</view>
            <view class="text-color-3">{{ item.checkItem }}</view>
          </view>
          <view class="d-flex text-color-6">
            <view class="w160">方法工具：</view>
            <view class="text-color-3">{{ item.method }}</view>
          </view>
          <view class="d-flex text-color-6">
            <view class="w160">保养级别：</view>
            <view class="text-color-3">{{ item.checkLevel }}</view>
          </view>
          <view class="d-flex text-color-6">
            <view class="w160">标准类型：</view>
            <view class="text-color-3">{{ item.sbTypeName }}</view>
          </view>
          <view class="d-flex text-color-6">
            <view class="w160">内容：</view>
            <view class="text-color-3">{{ item.remark }}</view>
          </view>
          <view class="d-flex text-color-6">
            <view class="w160">填报信息：</view>
            <view class="text-color-3 bold">{{ item.value }}</view>
          </view>
          <view class="d-flex text-color-6">
            <view class="w160">备注：</view>
            <view class="text-color-3">{{ item.text }}</view>
          </view>
        </view>
      </view>
    </view>
    <view class="m3 p3 bg-color-white" style="border-radius: 16rpx">
      <view class="d-flex py3 border-bottom">
        <view class="f-size-26 text-color-9 w200">标准图片</view>
        <view class="f-size-26 text-color-3 d-flex ">
          <block v-for="(item, index) in checkImgList" :key="index">
            <u-image width="100" class="mr-2" :src="item" @click="handlePre(index)" mode="widthFix"><u-loading
                slot="loading"></u-loading></u-image>
          </block>
          <view v-if="checkImgList.length === 0">暂无</view>
        </view>
      </view>
    </view>
    <!-- 标准文件：仅展示文件名 -->
    <view class="m3 p3 bg-color-white" style="border-radius: 16rpx"
      v-if="modelStandard.checkFileList && modelStandard.checkFileList.length > 0">
      <view class="f-size-30 main-color-text pb-2">标准文件</view>
      <view class="f-size-26 text-color-3 py2" v-for="item in modelStandard.checkFileList" :key="item.id">{{ item.name
      }}</view>
    </view>
    <!-- 任务信息：与 PC 端 Detail 保持一致 -->
    <view class="m3 p3 bg-color-white" style="border-radius: 16rpx">
      <view class="f-size-30 main-color-text pb-2">任务信息</view>
      <equipment-line title="执行人" :content="infoData.actualUser || infoData.checkUserName || '-'" />
      <equipment-line title="实际工时" :content="infoData.realHours" />
      <equipment-line title="预计执行日期" :content="infoData.startTime" />
      <equipment-line title="预计下次执行" :content="infoData.nextDate" />
      <equipment-line title="截至日期" :content="infoData.endTime" />
      <equipment-line title="实际开始时间" :content="infoData.actualStartTime" />
      <equipment-line title="实际结束时间" :content="infoData.actualEndTime" />
      <equipment-line title="任务状态" :content="statusMap[infoData.status]" />
      <equipment-line title="是否延期"
        :content="(infoData.receiveOvertime === null || infoData.receiveOvertime === 0 || !infoData.receiveOvertime) ? '否' : '是'" />
      <equipment-line title="检查结果" :content="infoData.feedback" />
    </view>
    <!-- 完成图片 -->
    <view class="m3 p3 bg-color-white" style="border-radius: 16rpx">
      <view class="d-flex py3 border-bottom">
        <view class="f-size-26 text-color-9 w200">完成图片</view>
        <view class="f-size-26 text-color-3 d-flex ">
          <block v-for="(item, index) in imgList" :key="index">
            <u-image width="100" class="mr-2" :src="item" @click="handleImgPre(index)" mode="widthFix"><u-loading
                slot="loading"></u-loading></u-image>
          </block>
          <view v-if="imgList.length === 0">暂无</view>
        </view>
      </view>
    </view>
    <!-- 完成文件：仅展示文件名 -->
    <view class="m3 p3 bg-color-white" style="border-radius: 16rpx" v-if="fileList.length > 0">
      <view class="f-size-30 main-color-text pb-2">完成文件</view>
      <view class="f-size-26 text-color-3 py2" v-for="item in fileList" :key="item.id">{{ item.name }}</view>
    </view>
    <view class="p-fixed d-flex j-around a-center footer">
      <view v-if="infoData.status ===
        1 ||
        infoData.status ===
        4" class="main-color-bg text-color-white common" @tap="handleExecute">接收</view>
      <view v-if="infoData.status === 2 && displayTime === 0" class="main-color-bg text-color-white common2"
        @tap="handleStart">
        <u-icon name="play-circle-fill"></u-icon> 开始计时
      </view>
      <view v-if="infoData.status === 2 && displayTime > 0" class="main-color-bg text-color-white common2"
        @tap="handlePause">
        <u-icon name="play-circle-fill" v-if="timerStatus === 2"></u-icon><u-icon name="pause-circle-fill"
          v-else></u-icon> {{ time }}
      </view>
      <view v-if="infoData.status === 2" class="main-color-bg text-color-white common" @tap="handleFinish">完成</view>
      <view v-if="infoData.status === 3" class="main-color-bg text-color-white common" @tap="handleRepair">发起报修</view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      infoData: {},
      detailId: '',
      statusMap: null,
      sbStatusMap: null,
      filter: 0,
      searchType: null,
      // 标准信息（来自保养标准接口，与 PC 端 Detail 一致）
      modelStandard: {},
      typeMap: null,
      periodTypeMap: null,
      levelMap: null,
      actionTypeMap: null,
      checkImgList: [],
      // 完成图片/文件（任务接口返回）
      imgList: [],
      fileList: [],
      requirementList: [],
      displayTime: 0,
      timer: null,
      timerStatus: 0,
      time: '00:00:00'
    }
  },
  onLoad(options) {
    this.detailId = options.detailId
    this.searchType = options.searchType
    this.filter = options.filter
    this.statusMap = this.$DictCache.getLabelByValueMapByType(this.$DictCache.TYPE.CHECK_JOB_STATUS)
    this.sbStatusMap = this.$DictCache.getLabelByValueMapByType(this.$DictCache.TYPE.SB_INFO_STATUS)
    this.typeMap = this.$DictCache.getLabelByValueMapByType(this.$DictCache.TYPE.CHECK_STANDARD_TYPE)
    this.periodTypeMap = this.$DictCache.getLabelByValueMapByType(this.$DictCache.TYPE.CHECK_PLAN_PERIOD_TYPE)
    // 维护等级/动作类型本地字典无取值，走后台字典接口（与 PC 端 levelMap/actionTypeMap 对应）
    this.$Http.getDictType({ type: 'CHECK_PLAN_LEVEL' }).then(res => {
      const map = {}
        ; (res.data || []).forEach(item => {
          map[item.value] = item.label
        })
      this.levelMap = map
    })
    this.$Http.getDictType({ type: 'CHECK_PLAN_ACTION_TYPE' }).then(res => {
      const map = {}
        ; (res.data || []).forEach(item => {
          map[item.value] = item.label
        })
      this.actionTypeMap = map
    })
  },
  onShow() {
    this.initData()
  },

  methods: {
    // 字典取值展示，防止 map 未加载时报错
    getMapText(map, value) {
      return map && map[value] != null ? map[value] : ''
    },
    handlePre(index) {
      uni.previewImage({
        urls: this.checkImgList,
        current: this.checkImgList[index],
        success() { }
      })
    },
    handleImgPre(index) {
      uni.previewImage({
        urls: this.imgList,
        current: this.imgList[index],
        success() { }
      })
    },
    handleExecute() {
      this.$Http.execute(this.infoData).then(res => {
        this.initData()
        uni.showToast({ title: '已接收，请及时完成任务' })
      })
    },
    handleFinish() {
      uni.navigateTo({
        url: `/pages/maintain/finish?id=${this.infoData.id}&standardId=${this.infoData.standardId}`
      })
    },
    handleRepair() {
      uni.navigateTo({
        url: '/pages/repair-add/repair-add?detailId=' + this.infoData.sbId
      })
    },
    initData() {
      const that = this
      this.$Http
        .fetchCheckJob({
          id: this.detailId
        })
        .then(res => {
          this.infoData = res.data
          // 完成图片/文件：与 PC 端 Detail 一致，取任务接口返回的 imgList/fileList
          this.imgList = (res.data.imgList || []).map(item => {
            return this.$BaseTool.UserUtil.getFileUrl(item.url)
          })
          this.fileList = res.data.fileList || []
          this.$Http.fetchCheckStandard({ id: res.data.standardId }).then(response => {
            this.modelStandard = response.data || {}
            if (res.data.conTask) {
              console.log(2)
              that.requirementList = JSON.parse(res.data.conTask)
            } else {
              that.requirementList = response.data.requirementList
            }
            // 标准图片：与 PC 端 Detail 一致，取自保养标准接口
            this.checkImgList = ((response.data && response.data.checkImgList) || []).map(item => {
              return this.$BaseTool.UserUtil.getFileUrl(item.url)
            })
          })
          this.$Http.timerStatus({ referenceId: this.infoData.id }).then(resp => {
            this.timerStatus = resp.data.timerStatus
            this.$Http.timerAccumulatedTime({ referenceId: this.infoData.id }).then(res => {
              this.displayTime = res.data
              this.updateDisplay()
              if (resp.data.timerStatus === 1) {
                that.startLocalTimer()
              }
            })
          })
        })
    },
    handleStart() {
      this.$Http.timerStart({ referenceId: this.infoData.id }).then(res => {
        uni.showToast({ title: '已开始计时' })
        this.startLocalTimer()
      })
    },
    handlePause() {
      if (this.timerStatus === 2) {
        this.$Http.timerResume({ referenceId: this.infoData.id }).then(res => {
          this.timerStatus = res.data.timerStatus
          this.startLocalTimer()
        })
        return
      }
      this.$Http.timerPause({ referenceId: this.infoData.id }).then(res => {
        this.timerStatus = res.data.timerStatus
        clearInterval(this.timer)
      })
    },
    // 本地计时器（用于实时显示）
    startLocalTimer() {
      this.timer = setInterval(() => {
        this.displayTime += 1000
        this.updateDisplay()
      }, 1000)
    },
    updateDisplay() {
      const minutes = Math.floor(this.displayTime / 60000)
      const seconds = Math.floor((this.displayTime % 60000) / 1000)
      this.time = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
    }
  }
}
</script>

<style lang="less">
page {
  background-color: #f4f4f4;
}

.container {
  padding-bottom: 100rpx;

  .footer {
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #fff;
    z-index: 10000;
  }

  .title {
    border-bottom: 1rpx solid #f4f4f4;
  }

  .img {
    width: 100rpx;
    height: 100rpx;
  }

  .p-fixed {
    border-top: 1rpx solid #f4f4f4;
    height: 100rpx;

    .common {
      padding: 15rpx 100rpx;
      border-radius: 30rpx;
      background-color: #0082ff;
      color: #fff;
    }

    .common2 {
      padding: 15rpx 50rpx;
      border-radius: 30rpx;
      background-color: #0082ff;
      color: #fff;
    }
  }
}
</style>
