<template>
  <view class="maintenance-container">
    <uni-nav-bar
      fixed="true"
      statusBar="true"
      left-icon="back"
      title="保养工单详情"
      @clickLeft="back"
      right-icon="scan"
      @clickRight="HandlScanCode"
    >
    </uni-nav-bar>
    <view class="maintenance-wrapper">
      <view class="maintenance-content">
        <KdTabs
          v-model="active"
          @change="handleTabChange"
          :list="['基本信息', '保养设备']"
        />
        <view class="kd-baseInfo" v-show="active === 0">
          <view class="kd-cell">
            <text class="kd-label">工单编号</text>
            <text class="kd-content">{{ worksheetInfo.workOrderCode }}</text>
          </view>
          <view class="kd-cell">
            <text class="kd-label">计划名称</text>
            <text class="kd-content">{{ worksheetInfo.planName }}</text>
          </view>
          <view class="kd-cell">
            <text class="kd-label">设备分类</text>
            <text class="kd-content">{{ worksheetInfo.equiTypeName }}</text>
          </view>
          <view class="kd-cell">
            <text class="kd-label">保养设备总数</text>
            <text class="kd-content text-warning"
              >{{
                worksheetInfo.equipCount - worksheetInfo.awaitInspectSum || 0
              }}/{{ worksheetInfo.equipCount }}</text
            >
          </view>
          <view class="kd-cell">
            <text class="kd-label">计划完成时长</text>
            <text class="kd-content">{{ worksheetInfo.duration }}分钟</text>
          </view>
          <view class="kd-cell">
            <text class="kd-label">实际完成时长</text>
            <text class="kd-content">{{
              finishTime(worksheetInfo.acceptTime, worksheetInfo.finishTime)
            }}</text>
          </view>
          <view class="kd-cell">
            <text class="kd-label">实际开始时间</text>
            <text class="kd-content">{{ worksheetInfo.acceptTime }}</text>
          </view>
          <view class="kd-cell">
            <text class="kd-label">实际完成时间</text>
            <text class="kd-content">{{ worksheetInfo.finishTime }}</text>
          </view>

          <!-- <u-button type="primary" size="large" text="开始执行"></u-button> -->
          <template v-if="worksheetInfo.status">
            <template v-if="worksheetInfo.status.code === 0">
              <button class="btn-execute" type="primary" @click="handleExecute">
                开始执行
              </button>
              <div class="apply-box">
                <!-- <button
                  class="btn-reassignment"
                  type="primary"
                  @click="sparepartApply"
                >
                  申请备品备件
                </button> -->
              </div>
            </template>
            <template v-else-if="worksheetInfo.status.code === 1">
              <button class="btn-execute" type="primary" @click="handleReport">
                报工
              </button>
            </template>
            <button
              v-else-if="worksheetInfo.status.code === 3"
              :disabled="true"
              class="btn-execute"
              type="primary"
            >
              已报工
            </button>
            <div class="apply-box">
              <button
                v-if="worksheetInfo.status.code !== 3"
                class="btn-reassignment"
                type="primary"
                @click="sparepartApply"
              >
                申请备品备件
              </button>
              <button
                v-if="worksheetInfo.status.code === 0"
                class="btn-reassignment"
                type="primary"
                @click="handleAssign"
              >
                转派
              </button>
            </div>
          </template>
        </view>
        <view class="kd-equipment" v-show="active === 1">
          <view class="kd-type-box">
            <text
              :class="{ 'type—active': typeActive === index }"
              v-for="(item, index) in equpStatus"
              :key="index"
              @click="typeChange(index)"
              >{{ item.name }}</text
            >
          </view>
          <view class="kd-list-container">
            <u-list @scrolltolower="scrolltolower">
              <u-list-item v-for="(item, index) in euqiList" :key="index">
                <view class="kd-card">
                  <view class="kd-card-wrapper">
                    <view class="kd-cell">
                      <text class="kd-label">设备编码</text>
                      <text class="kd-content">{{ item.equiCode }}</text>
                    </view>
                    <view class="kd-cell">
                      <text class="kd-label">设备名称</text>
                      <text class="kd-content">{{ item.equiName }}</text>
                    </view>
                    <view class="kd-cell">
                      <text class="kd-label">设备型号</text>
                      <text class="kd-content">{{ item.equiModel }}</text>
                    </view>
                    <view class="kd-cell">
                      <text class="kd-label">设备位置</text>
                      <text class="kd-content">{{ item.equiLocation }}</text>
                    </view>
                    <view class="kd-cell">
                      <text class="kd-label">执行结果</text>

                      <text class="kd-content">
                        <text
                          class="status-box text-warning"
                          v-if="item.resultStatus === 0"
                          >待保养</text
                        >
                        <text
                          class="status-box text-primary"
                          v-else-if="item.resultStatus === 1"
                          >完成保养</text
                        >
                        <text
                          class="status-box text-danger"
                          v-else-if="item.resultStatus === 2"
                          >缺陷</text
                        >
                        <text
                          class="status-box text-primary"
                          v-else-if="item.resultStatus === 3"
                          >已报修</text
                        >
                      </text>
                    </view>
                  </view>
                  <view class="card-footer">
                    <button
                      type="primary"
                      class="primary-btn"
                      @click="handleCheck(item)"
                      v-if="
                        worksheetInfo.status && worksheetInfo.status.code === 1
                      "
                    >
                      执行
                    </button>
                    <template
                      v-if="
                        worksheetInfo.status && worksheetInfo.status.code === 3
                      "
                    >
                      <button
                        type="default"
                        v-if="item.resultStatus === 2"
                        @click="handLbx(item)"
                      >
                        报修
                      </button>
                      <button
                        type="default"
                        v-else-if="item.resultStatus === 3"
                        @click="handLbxDetail(item)"
                      >
                        报修详情
                      </button>
                    </template>
                    <button
                      type="default"
                      v-if="
                        [0, 3].includes(
                          worksheetInfo.status && worksheetInfo.status.code
                        )
                      "
                      @click="checkDetail(item)"
                    >
                      保养详情
                    </button>
                  </view>
                </view>
              </u-list-item>
            </u-list>
          </view>
        </view>
      </view>
    </view>
    <uni-popup ref="inputDialog" type="dialog">
      <uni-popup-dialog
        ref="inputClose"
        mode="input"
        title="您当前已超出计划完成时间，请填写原因"
        placeholder="请输入内容"
        :before-close="true"
        @close="handleClose"
        @confirm="timeoutCauseConfirm"
      ></uni-popup-dialog>
    </uni-popup>
    <u-modal :show="modalShow" title="提示" @confirm="modalShow = false">
      <view
        >您还有
        <text class="text-warning">{{ worksheetInfo.awaitInspectSum }}</text>
        台设备待检，不可报工</view
      >
    </u-modal>
    <Assign ref="assignRef" @success="assignSuccess" />

    <!-- <ScanCode @scancodedate="scancodedate" :model="'uni'"></ScanCode> -->
  </view>
</template>

<script>
import { get, post, postJ } from '@/utils/api.js'
import Assign from '@/components/Assign.vue'
import CellInfo from '@/components/CellInfo.vue'
import KdTabs from '@/components/KdTabs.vue'
import dayjs from 'dayjs'
import ScanCode from '@/components/ScanCode.vue'
export default {
  components: {
    CellInfo,
    KdTabs,
    Assign,
    ScanCode
  },
  data () {
    return {
      modalShow: false,
      active: 0,
      typeActive: 0,
      statusList: {
        0: '待接收',
        1: '执行中',
        3: '已完成'
      },
      pageId: '',
      workOrderCode: '',
      worksheetInfo: {
        equiList: [],
        workOrder: {}
      },
      equpStatus: [
        // {
        //   name: '全部',
        //   value: []
        // },
        {
          name: '待执行',
          value: [0]
        },
        {
          name: '已执行',
          value: [1, 2, 3]
        },
        {
          name: '缺陷',
          value: [2]
        },
        {
          name: '全部',
          value: []
        }
      ],
      euqiList: [],
      equipPage: 1,
      isEnd: false,
      barType: 0,
      qrContent: null
    }
  },
  async onLoad (options) {
    this.workOrderCode = options.workOrderCode
    this.pageId = options.id
    // 设备台账跳转详情
    if (options.qrContent) {
      this.qrContent = options.qrContent
      await this.getInfo()
      this.cbScancodedate({ code: this.qrContent })
    }
  },
  onShow () {
    this.getInfo()
    this.typeChange(0)
    let _this = this
    uni.$off('scancodedate') // 每次进来先 移除全局自定义事件监听器
    uni.$on('scancodedate', function (data) {
      _this.cbScancodedate(data)
    })
  },
  onHide () {
    uni.$off('scancodedate')
  },
  onUnload () {
    uni.$off('scancodedate')
  },
  methods: {
    // 扫码枪扫码
    cbScancodedate (data) {
      this.Scancodedate(data.code)
    },
    // 相机扫码
    HandlScanCode () {
      let _this = this
      uni.scanCode({
        onlyFromCamera: true,
        success: function (res) {
          _this.Scancodedate(res.result)
        }
      })
    },
    Scancodedate (code) {
      let _this = this
      if (this.worksheetInfo.status.code === 0) {
        uni.showModal({
          title: '提示',
          content: '工单未开启执行，不可进行保养操作，请先点击“开始执行”！',
          confirmText: '开始执行', //这块是确定按钮的文字
          cancelText: '取消', //这块是取消的文字
          success: function (res) {
            if (res.confirm) {
              _this.handleExecute() // 执行确认后的操作
            } else {
              // 执行取消后的操作
            }
          }
        })
        return
      }
      this.qrContent = code.trim()
      this.barType = this.setBarType(this.qrContent)
      _this.getData()
    },
    // 设置barType
    setBarType (val) {
      let index = val.indexOf('@_@')
      let result = 0
      if (index !== -1) {
        let item = val.substr(index + 3, 1)
        if (item) {
          result = Number(item)
        }
      }
      return result
    },
    // 根据条码请求设备数据
    getData () {
      let par = {
        barType: this.barType,
        qrContent: this.qrContent
      }
      uni.showLoading({
        title: '加载中',
        mask: true
      })
      postJ(this.apiUrl + '/scan/getAssetInfo', par)
        .then(res => {
          console.log('扫码接口返回', res)
          let data = res.data
          this.matchEquipment(data)
        })
        .finally(() => {
          uni.hideLoading()
        })
    },

    matchEquipment (data) {
      let par = {
        assetCode: data.assetCode,
        workOrderId: this.worksheetInfo.id
      }
      console.log('par', par)
      post(this.apiUrl + '/workOrder/scanMatching', par).then(res => {
        let data = res.data
        if (!data) {
          uni.showModal({
            title: '提示',
            content: '本工单中，无此设备！',
            confirmText: '好的', //这块是确定按钮的文字
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                // 执行确认后的操作
              } else {
                // 执行取消后的操作
              }
            }
          })
        } else {
          // 未报工
          if (this.worksheetInfo.status.code === 1) {
            this.handleCheck(data)
          }
          // 已报工
          if (this.worksheetInfo.status.code === 3) {
            this.checkDetail(data)
          }
        }
      })
    },

    back () {
      uni.navigateBack({
        delta: 1
      })
    },
    handleAssign () {
      this.$refs.assignRef.open(this.pageId)
    },
    assignSuccess () {
      this.back()
    },
    finishTime (start, end) {
      if (!end) return ''
      let dur = new Date(end).getTime() - new Date(start).getTime()
      return Math.ceil(dur / 1000 / 60) + '分钟'
    },
    // 申请备品备件
    sparepartApply () {
      uni.navigateTo({
        url: `/pages/maintenance/sparepart/sparepart?planCode=${this.worksheetInfo.planCode}&sourceId=${this.worksheetInfo.id}&sourceCode=${this.worksheetInfo.workOrderCode}`
      })
    },
    // 申请备品备件详情
    sparepartDetail () {
      uni.navigateTo({
        url: `/pages/maintenance/sparepart/sparepartDetail?applyOrder=${this.worksheetInfo.applyOrder}`
      })
    },
    // 报工
    handleReport () {
      // if (
      //   new Date(this.worksheetInfo.planFinishTime).getTime() <
      //   new Date().getTime()
      // ) {
      //   this.$refs.inputDialog.open()
      //   return
      // }
      this._report()
    },
    handleClose () {
      this.$refs.inputDialog.close()
    },
    timeoutCauseConfirm (value) {
      if (!value) {
        uni.showToast({
          title: '请输入超时原因',
          icon: 'none'
        })
        return
      }
      this.$refs.inputDialog.close()
      this._report(value)
    },
    _report (timeoutCause = '') {
      post(
        this.apiUrl + '/workOrder/reportWork',
        {
          workOrderId: this.pageId,
          timeoutCause
        },
        true,
        false
      )
        .then(res => {
          let _this = this
          if (res?.success) {
            let data = res.data
            if (data.length) {
              uni.showModal({
                title: '提示',
                content: `有${data.length}台设备被标记为缺陷，是否要报修？`,
                cancelText: '取消', // 取消按钮的文字
                confirmText: '报修', // 确认按钮的文字
                showCancel: true, // 是否显示取消按钮，默认为 true
                success: res => {
                  if (res.confirm) {
                    if (data.length > 1) {
                      uni.navigateTo({
                        url: `/pages/maintenance/detail/detail?workOrderCode=${this.workOrderCode}&id=${this.pageId}&chooseTab=true`
                      })
                    } else {
                      uni.navigateTo({
                        url: `/pages/repair/repair/index?source=5&workOrderCode=${this.workOrderCode}&equiCode=${data[0].equiCode}&equiId=${data[0].equiId}&workOrderId=${this.pageId}&equiName=${data[0].equiName}&equiModel=${data[0].equiModel}&equiLocation=${data[0].equiLocation}`
                      })
                    }
                  } else {
                    _this.getInfo()
                  }
                }
              })
            } else {
              uni.showToast({
                icon: 'success',
                title: '操作成功！',
                duration: 2000
              })
              this.getInfo()
            }
          }
        })
        .catch(res => {
          if (res.code === '4444') {
            this.$refs.inputDialog.open()
          } else if (res.code === '5555') {
            this.modalShow = true
            // uni.showModal({
            //   title: '提示',
            //   content: `您还有 ${this.worksheetInfo.awaitInspectSum} 台设备待检，不可报工`,
            //   success: function (res) {},
            //   showCancel: false
            // })
          }
        })
    },
    // 执行工单
    handleExecute () {
      post(this.apiUrl + '/workOrder/execute', {
        workOrderCode: this.workOrderCode
      }).then(res => {
        if (res?.success && res.data) {
          uni.showToast({
            icon: 'success',
            title: '操作成功！',
            duration: 2000
          })
		  this.active = 1
          this.getInfo()
        }
      })
    },
    //巡点检设备加载更多
    scrolltolower () {
      if (this.isEnd) return
      this.equipPage++
      this.getEquipList()
    },
    // 巡点检设备列表
    getEquipList () {
      const params = {
        workOrderId: this.pageId,
        resultStatus: this.equpStatus[this.typeActive].value
      }

      post(
        this.apiUrl +
          `/workOrder/getEquipmentListApp?page=${this.equipPage}&size=10`,
        params,
        true
      ).then(res => {
        if (res?.success) {
          if (this.equipPage === 1) {
            this.euqiList = res.data.records
          } else {
            this.euqiList.push(...res.data.records)
          }

          this.isEnd = this.euqiList.length >= res.data.total
        }
      })
    },

    handleTabChange (value) {
      if (value === 1) {
        this.typeChange(0)
      }
    },
    // 设备状态切换
    typeChange (type) {
      this.typeActive = type
      this.equipPage = 1
      this.getEquipList()
    },
    handleCheck ({ id, equiName, equiCode, sparePartsJson }) {
      this.$store.commit('maintenance/SET_SPAREPARTSJSON', sparePartsJson)
      uni.navigateTo({
        url: `/pages/maintenance/check/index?workOrderId=${this.pageId}&id=${id}&equiName=${equiName}&equiCode=${equiCode}&applyOrder=${this.worksheetInfo.applyOrder}&workOrderCode=${this.worksheetInfo.workOrderCode}`
      })
    },
    checkDetail ({ id, equiName, equiCode, sparePartsJson }) {
      this.$store.commit('maintenance/SET_SPAREPARTSJSON', sparePartsJson)
      uni.navigateTo({
        url: `/pages/maintenance/check/detail?workOrderId=${this.pageId}&id=${id}&equiName=${equiName}&equiCode=${equiCode}&applyOrder=${this.worksheetInfo.applyOrder}&workOrderCode=${this.worksheetInfo.workOrderCode}`
      })
    },
    getInfo () {
      post(this.apiUrl + '/workOrder/getDetailsApp', {
        workOrderCode: this.workOrderCode
      }).then(res => {
        if (res?.success) {
          this.worksheetInfo = res.data
        }
      })
    },
    // 报修
    handLbx (item) {
      uni.navigateTo({
        url: `/pages/repair/repair/index?source=4&workOrderCode=${this.workOrderCode}&equiCode=${item.equiCode}&equiId=${item.equiId}&workOrderId=${this.pageId}&equiName=${item.equiName}&equiModel=${item.equiModel}&equiLocation=${item.equiLocation}`
      })
    },
    // 报修详情
    handLbxDetail (item) {
      uni.navigateTo({
        url: `/pages/repair/detail/detail?id=${item.repairId}`
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/components/submitted.scss';

.list-cell {
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: $uni-text-color-grey;
  padding: 5rpx 20rpx;
}

.font-sm {
  font-size: $uni-font-size-sm;
}

.font-text {
  color: $uni-text-color;
}

.btn-execute {
  background-color: $j-primary-border-green;
  width: 450rpx;
  margin-top: 10vh;
}

.btn-reassignment {
  color: $uni-color-primary;
  background-color: transparent;
  border: none;
  box-shadow: none;

  &::after {
    display: none;
  }
}

.maintenance-container {
  position: fixed;
  top: 0;
  bottom: 0;
  width: 100vw;
  display: flex;
  flex-direction: column;
  /deep/.u-popup {
    flex: none !important;
  }
}
.maintenance-wrapper {
  position: relative;
  flex: 1;
}
.maintenance-content {
  padding-top: 40rpx;
  box-sizing: border-box;
  // height: calc(100vh - 88rpx);
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  flex-direction: column;
}

.kd-cell {
  line-height: 90rpx;
  border-bottom: 1px dashed #dadada;
  display: flex;
  justify-content: space-between;
  .kd-label {
    display: inline-block;
    width: 7em;
    font-weight: bold;
  }
  .kd-content {
    flex: 1;
    text-align: left;
    word-break: break-all;
  }
}
.kd-baseInfo {
  padding: 0 32rpx;
  font-size: 28rpx;
}
.kd-equipment {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  .kd-type-box {
    text-align: center;
    padding: 26rpx 0;
    text {
      display: inline-block;
      width: 120rpx;
      padding: 4rpx 0;
      color: #333;
      margin: 0 8rpx;
      &.type—active {
        background-color: rgba(215, 215, 215, 1);
      }
    }
  }
  .kd-list-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    padding: 12rpx 18rpx;
    background-color: $page-bg;

    .u-list {
      flex: 1;
      height: 100% !important;
    }
  }
}

.kd-card {
  background-color: #fff;
  margin-bottom: 20rpx;
  padding: 8rpx 0;
  font-size: 28rpx;
  word-break: break-all;
  .kd-card-wrapper {
    padding: 0 30rpx;
    border-bottom: 1px solid #dadada;
  }
  .kd-cell {
    line-height: 60rpx;
  }
  .kd-cell:last-of-type {
    border-bottom: none;
  }
  .status-box {
    margin-right: 16rpx;
  }
  .card-footer {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding: 8rpx 0 20rpx;
    button {
      width: 180rpx;
      height: 56rpx;
      line-height: 56rpx;
      font-size: 28rpx;
      margin: 0 8rpx;
    }
    .primary-btn {
      background-color: $j-primary-border-green;
    }
  }
}
.apply-box {
  width: 70%;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: space-around;
}
</style>
