<template>
  <view class="incidentDetail">
    <view class="head">
      <view class="tab" :class="{active: tab.value === dataInfo.tabActiveValue}" v-for="tab in dataInfo.tabs" :key="tab.id" @click="clickTab(tab.value)">
        {{tab.name}}<text v-if="tab.num !== ''">({{tab.num}})</text>
      </view>
    </view>
    <scroll-view scroll-y class="body">
      <!-- 基础信息 -->
      <template v-if="dataInfo.tabActiveValue === '1'">
        <view class="detail_head">
          <text class="title">计划批次信息</text>
          <view class="other">
            <view class="status" :style="{ color: dataInfo.inspectionTaskData.status == 1 ? 'red' : '' }">{{dataInfo.inspectionTaskData.status ? dataInfo.inspectionTaskData.status.name : ''}}</view>
          </view>
        </view>
        <view class="detail_item_wrap">
          <view class="deital_item">
            <text class="name">单号：</text>
            <text class="value">{{dataInfo.inspectionTaskData.code}}</text>
          </view>
          <view class="deital_item">
            <text class="name">计划主题：</text>
            <text class="value">{{dataInfo.inspectionTaskData.inspectionDTO?.name}}</text>
          </view>
          <view class="deital_item">
            <text class="name">巡检点：</text>
            <text class="value">{{dataInfo.inspectionTaskData.inspectionNodeDTO?.name }}</text>
          </view>
          <view class="deital_item">
            <text class="name">巡检单：</text>
            <text class="value">{{dataInfo.inspectionTaskData.inspectionDTO?.inspectionFormDTO?.name}}</text>
          </view>
          <view class="deital_item">
            <text class="name">签到方式：</text>
            <text class="value">{{dataInfo.inspectionTaskData.signType?.name}}</text>
          </view>
        </view>

        <view class="detail_head">
          <text class="title">执行信息</text>
          <view class="other">
            <view class="status" :style="{ color: dataInfo.inspectionTaskData.exception === 1 ? 'red' : '#49B856' }">{{dataInfo.inspectionTaskData.exception === 1 ? '异常' : '正常'}}</view>
          </view>
        </view>
        <view class="detail_item_wrap">
          <view class="deital_item">
            <text class="name">创建时间：</text>
            <text class="value">{{formatDate(dataInfo.inspectionTaskData.addTime, 'yyyy-MM-dd HH:mm')}}</text>
          </view>
          <view class="deital_item">
            <text class="name">截止时间：</text>
            <text class="value">{{formatDate(dataInfo.inspectionTaskData.overtime, 'yyyy-MM-dd HH:mm')}}</text>
          </view>
          <view class="deital_item">
            <text class="name">完成时间：</text>
            <text class="value">{{formatDate(dataInfo.inspectionTaskData.completeTime, 'yyyy-MM-dd HH:mm')}}</text>
            <text class="value text_right">执行人：{{ dataInfo.inspectionTaskData.userDTO?.name || dataInfo.inspectionTaskData.groupDTO?.groupName }}</text>
          </view>
          <template v-if="dataInfo.inspectionTaskData.incidentDTO">
            <view class="deital_item">
              <text class="name">故障单号：</text>
              <text class="value">{{dataInfo.inspectionTaskData.incidentDTO?.incidentsign}}</text>
              <text class="value text_right">{{dataInfo.inspectionTaskData.incidentDTO?.state?.name}}</text>
            </view>
            <view class="deital_item">
              <text class="name">处理人/组：</text>
              <text class="value">{{dataInfo.inspectionTaskData.incidentDTO?.groupORHandlerUser}}</text>
            </view>
          </template>
        </view>
      </template>

      <!-- 巡检信息 -->
      <template v-if="dataInfo.tabActiveValue === '2'">
        <view class="info">
          <view v-for="item in dataInfo.valueList" :key="item.id">
            <view v-for="(value, i) in item" :key="i" class="infoItem">
              <text class="name">{{value.name}}</text>
              <template v-if="value.inspectionFormItemDTO">
                <text v-if="value.inspectionFormItemDTO.type.value != 7" class="value" :class="{ red: value.exception === 1 }">{{getValuex(value)}}</text>
                <view class="deital_item" v-if="value.inspectionFormItemDTO.type.value == 7">
                  <view class="value img">
                    <image class="resourceItem" :src="img.thumbFilePath" mode="aspectFill" v-for="(img, i) in value.valuex" :key="i" @click="previewImg(i, 'inspectionTaskImgs', value.valuex)"></image>
                  </view>
                </view>
              </template>
            </view>
          </view>
        </view>
      </template>

      <!-- 流程图 -->
      <template v-if="dataInfo.tabActiveValue === '3'">
        <view class="process_item_wrap">
          <view class="process_item" v-for="item in dataInfo.logList" :key="item.id">
            <view class="process_item_top">
              <view class="name">{{item.operationType?.name }}</view>
              <view class="value" v-if="item.remarks">（{{item.remarks}}）</view>
            </view>
            <view class="process_item_bottom">
              <text class="name">{{formatDate(item.operationTime, 'yyyy-MM-dd HH:mm:ss')}}</text>
              <text class="value" v-if="item.username">{{item.username}}</text>
            </view>
          </view>
        </view>
      </template>

    </scroll-view>
    <view class="foot_common_btns">
      <button @click="viewInspectionExecute()" type="default" class="primaryButton btn">返回巡检列表</button>
      <button v-if="dataInfo.inspectionTaskData.incidentId" @click="viewIncidentDetail(dataInfo.inspectionTaskData.incidentId)" type="default" class="primaryButton btn">查看故障单</button>
    </view>
  </view>
</template>

<script setup>
  import chunk from 'lodash-es/chunk'
  import { ref, reactive } from 'vue'
  import { onLoad } from '@dcloudio/uni-app'
  import { api_listAttachment, api_inspectionTaskDetail, api_inspectionFormValues } from "@/http/api.js"
  import { defaultColor } from '@/static/js/theme.js'
  import { useSetTitle } from '@/share/useSetTitle.js'
  import { filterFormatDate } from '@/filters/filterFormatDate.js'

  useSetTitle();
  const { formatDate }  = filterFormatDate();

  // 主题颜色
  const primaryColor = ref(defaultColor)
	
  // 数据
  const dataInfo = reactive({
    tabs: [
      {id: 1, name: '基础信息', value: '1', num: ''},
      // {id: 2, name: '巡检信息', value: '2', num: ''},
      {id: 3, name: '流程图', value: '3', num: ''},
    ],
    tabActiveValue: 0,//当前选择的tab
    inspectionTaskId: undefined,//巡检执行ID
    inspectionTaskData: {},//巡检执行对象
    inspectionTaskImgs: [],//巡检图片
    valueList: [],//巡检信息
    logList: [],//流程图
  })
  
  function getValuex(value){
    return value.formItemConfigList ? value.formItemConfigList.map(v => v.valuex).toString() : value.valuex;
  }

  // 获取巡检信息
  function getValue(){
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    let postData = {
        "idx": 0,
        "sum": 9999,
        "inspectionFormValues": {
          taskId: dataInfo.inspectionTaskId,
        }
    };
    api_inspectionFormValues(postData).then(res => {
      uni.hideLoading();
      if(res.status == 200){
        let valueList = res.list || [];
        let imgFlag = valueList.some(v => v.inspectionFormItemDTO.type.value == 7);

        if(imgFlag){
          valueList.forEach(v => {
            if(v.inspectionFormItemDTO.type.value == 7){
              v.valuex = [];
            }
          })
        }

        dataInfo.valueList = chunk(valueList, 3);

        if(imgFlag){
          getInspectionImgs();
        }
      }else{
        uni.showToast({
          icon: 'none',
          title: res.msg || '请求数据失败！'
        });
      }
    })
  }

  // 预览图片
  function previewImg(index, type, imgList){
    uni.previewImage({
      current: index,
      urls: imgList.map(v => v.previewUrl),
      longPressActions: {
        itemList: ['发送给朋友', '保存图片', '收藏'],
        success: function(data) {
          console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
        },
        fail: function(err) {
          console.log(err.errMsg);
        }
      }
    });
  }

  // 初始化表单
  function initForm(){
    if(dataInfo.tabActiveValue === '1'){
      
    }else if(dataInfo.tabActiveValue === '2'){
      getValue();
    }else if(dataInfo.tabActiveValue === '3'){
      
    }
  }

  // 点击tab
  function clickTab(tabValue){
    if(dataInfo.tabActiveValue == tabValue){
      return;
    }
    dataInfo.tabActiveValue = tabValue;
    initForm()
  }

  // 获取巡检执行详情
  function getInspectionTaskDetail(){
    uni.showLoading({
      title: "加载中",
      mask: true,
    });

    api_inspectionTaskDetail(dataInfo.inspectionTaskId).then(res => {
      uni.hideLoading();
      if(res.status == 200){
        dataInfo.inspectionTaskData = res.data || {};
        dataInfo.logList = dataInfo.inspectionTaskData.logList || [];
        
        // 巡检信息
        if(dataInfo.inspectionTaskData.status.value === '2'){
          let flag = dataInfo.tabs.some(v => v.value === '2');
          !flag && dataInfo.tabs.splice(1, 0, {id: 2, name: '巡检信息', value: '2', num: ''});
        }
        
        dataInfo.tabActiveValue = dataInfo.tabs[0].value;
        initForm()
      }else{
        uni.showToast({
          icon: 'none',
          title: res.msg || '请求数据失败！'
        });
      }
    })
  }
	
  // 获取巡检图片
  function getInspectionImgs(){
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    api_listAttachment('inspection', dataInfo.inspectionTaskId).then(res => {
      uni.hideLoading();
      res.data = res.data || [];
      res.data.forEach(v => {
        v.previewUrl = location.origin + "/file" + v.relativeFilePath;
        v.thumbFilePath = location.origin + "/file" + v.thumbFilePath;
      })
      
      let imgList = res.data || [];
      dataInfo.valueList.forEach(v => {
        v.forEach(vv => {
          imgList.forEach(item => {
            if(vv.itemId == item.recordId){
              if(vv.valuex && vv.valuex.length){
                vv.valuex.push(item)
              }else{
                vv.valuex = [item];
              }
            }
          })
        })
      })
    })
  }

  // 返回巡检列表
  function viewInspectionExecute(){
    uni.reLaunch({
      url: `/pages/inspection/inspectionExecute/inspectionExecute`
    })
  }
  
  // 查看故障单
  function viewIncidentDetail(incidentId){
    uni.navigateTo({
      url: `/pages/incidentDetail/incidentDetail?incidentId=${incidentId}`
    })
  }

  onLoad((option) => {
    dataInfo.inspectionTaskId = option.inspectionTaskId;
		getInspectionTaskDetail();
  })
</script>

<style lang="scss" scoped>
.popup-content{
	padding: 40rpx;
}
.incidentDetail{
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .head{
    height: 88rpx;
    display: flex;
    position: fixed;
    z-index: 99;
    width: 100%;
    background-color: #fff;
    font-size: 30rpx;
    .tab{
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
      border-bottom: 4rpx solid transparent;
      position: relative;
      &:last-of-type{
        &:after{
          display: none;
        }
      }
      &:after{
        content: '';
        position: absolute;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 1rpx;
        height: 44rpx;
        background-color: #515151;
      }
      &.active{
        color: $uni-primary;
        border-color: $uni-primary;
      }
    }
  }
  .body{
    margin-top: 88rpx;
    box-sizing: border-box;
    flex: 1;
    min-height: 0;
    border-top: 7rpx solid #EBEBEB;
    .phone-filled{
      margin-left: 5rpx;
    }
    .mic-filled{
      margin-right: 100rpx;
    }
    .detail_item_wrap{
      padding-bottom: 24rpx;
    }
    .detail_head{
      padding: 24rpx;
      border-top: 1rpx solid #D2D2D2;
      border-bottom: 1rpx solid #D2D2D2;
      display: flex;
      justify-content: space-between;
      align-items: center;
      &:first-of-type{
        border-top: none;
      }
      .title{
        font-size: 26rpx;
        color: $uni-primary;
        padding-left: 18rpx;
        position: relative;
        &:before{
          content: '';
          width: 8rpx;
          height: 25rpx;
          background-color: $uni-primary;
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
        }
      }
      .other{
        display: flex;
        align-items: center;
        .priority{
          font-size: 26rpx;
          margin-right: 15rpx;
        }
        .status{
          font-size: 26rpx;
        }
      }
    }

    .deital_item{
      font-size: 26rpx;
      color: #555;
      padding: 24rpx 24rpx 0;
      display: flex;
      align-items: center;
      .name{
        width: 8em;
        margin-right: 24rpx;
      }
      .value{
        flex: 1;
        word-break: break-all;
        &.img{
          display: flex;
          .imgItem{
            width: 82rpx;
            height: 82rpx;
            margin-right: 24rpx;
            &:last-of-type{
              margin-right: 0;
            }
          }
					.resourceItem{
						width: 100rpx;
						height: 100rpx;
						margin-right: 24rpx;
						&:last-of-type{
						  margin-right: 0;
						}
					}
					.resourceItem-audio{
						width: 300rpx;
						height: 60rpx;
					}
        }
      }
    }

    .summaryItem_bodyItem{
      padding: 24rpx 24rpx 0;
      font-size: 26rpx;
      .summaryItem_bodyItem_top{
        display: flex;
        justify-content: space-between;
        align-items: center;
        .value{
          padding-left: 48rpx;
          flex-shrink: 0;
        }
      }
      .summaryItem_bodyItem_bottom{
        margin-top: 24rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .name{
          text-align: right;
          flex: 1;
        }
        .value{
          width: 220rpx;
          text-align: right;
          flex-shrink: 0;
        }
      }
    }

    .summaryItem_bodyItem_total{
      text-align: right;
      padding: 24rpx;
      font-size: 26rpx;
    }

    .summaryItem_total{
      text-align: center;
      padding-top: 24rpx;
      font-size: 32rpx;
      font-weight: bold;
      color: $uni-primary;
      border-top: 1rpx solid #D2D2D2;
    }
    
    .info{
      padding: 0 24rpx 32rpx;
      .infoItem{
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-top: 32rpx;
        .name{
          word-break: break-all;
          width: 33.33%;
          flex-shrink: 0;
        }
        .value{
          word-break: break-all;
          margin-left: 24rpx;
        }
      }
    }

    .process_item_wrap{
      padding: 38rpx;
      .process_item{
        &:last-of-type{
          .process_item_bottom{
            border-left: none;
          }
        }
        .process_item_top{
          padding-left: 30rpx;
          display: flex;
          align-items: center;
          position: relative;
          &:before{
            content: '';
            position: absolute;
            left: -13rpx;
            top: 50%;
            width: 26rpx;
            height: 26rpx;
            border-radius: 50%;
            background-color: $uni-primary;
            transform: translateY(-50%);
          }
          .name{
            font-size: 30rpx;
          }
          .value{
            margin-left: 20rpx;
            font-size: 22rpx;
            color: #A1A1A1;
						flex: 1;
          }
        }
        .process_item_bottom{
          min-height: 82rpx;
          border-left: 1rpx solid #B7BDC6;
          margin-top: 5rpx;
          padding-left: 30rpx;
          display: flex;
          font-size: 24rpx;
          color: #A1A1A1;
          .value{
            margin-left: 20rpx;
          }
        }
      }
    }

    .appraise_detail{
      padding: 24rpx 24rpx 24rpx 40rpx;
      .appraise_detail_top{
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 26rpx;
        .name{
          color: #A1A1A1;
        }
        .value{}
      }
      .appraise_detail_bottom{
        font-size: 30rpx;
        margin-top: 24rpx;
        word-break: break-all;
      }
    }
  }
}
</style>
