<template>
  <view class="incidentList">
    <view class="title">{{dataInfo.inspectionNodeName}}</view>
    <view class="head">
      <view class="tab" :class="{active: tab.id === dataInfo.tabActiveId}" v-for="tab in dataInfo.tabs" :key="tab.id" @click="clickTab(tab.id)">
        {{tab.name}}<text v-if="tab.num !== ''">({{tab.num}})</text>
      </view>
    </view>
    <view class="body" v-if="dataInfo.list.length">
      <view class="body_item" v-for="data in dataInfo.list" :key="data.id">
        <view class="body_item_head ellipsis-multiline">
          <text class="sign" v-if="data.status.value == 2" :class="{signRed: data.exception == 1}">{{data.exception == 1 ? '异常' : '正常'}}</text>{{ data.inspectionDTO?.inspectionFormDTO?.name }}-{{ data.inspectionNodeDTO?.name }}-{{ data.batchNo }}
        </view>

        <view class="body_item_content">
          <view class="body_item_content_p" v-if="data.inspectionDTO">
            <text class="name ellipsis">计划标题：{{data.inspectionDTO.name}}</text>
          </view>
          <view class="body_item_content_p" v-if="data.signType">
            <text class="name ellipsis">签到方式：{{data.signType.name}}</text>
          </view>
          <view class="body_item_content_p" v-if="data.userDTO || data.groupDTO">
            <text class="name ellipsis">执行人或组：{{ data.userDTO?.name || data.groupDTO?.groupName }}</text>
          </view>
          <view class="body_item_content_p" v-if="data.status || data.addTime">
            <text class="name ellipsis">状态：{{ data.status?.name}}</text>
            <text class="date">{{formatDate(data.addTime, 'yyyy-MM-dd HH:mm')}}</text>
          </view>
        </view>

        <view class="body_item_foot">
          <view class="btns pt0">
            <button v-if="data.status.value === '1' && dataInfo.tabActiveId === 0" @click.stop="toInspectionValue(data)" type="default" class="primaryButton btn">执行</button>
            <button v-if="data.status.value === '2' && data.exception == 1 && !data.incidentId && data.inspectionDTO.inspectionFormDTO.showOrder == 1" @click.stop="toBuildIncident(data)" type="default" class="primaryButton btn">生成维修单</button>
          </view>
        </view>
      </view>
    </view>
    <view class="zanwu" v-else>
      <text class="newicon newicon-zanwu"></text>
    </view>
  </view>
</template>

<script setup>
  import { startOfDay, endOfDay, format, add } from 'date-fns'
  import { ref, reactive, computed } from 'vue'
  import { onLoad, onPullDownRefresh, onReachBottom, onTabItemTap } from '@dcloudio/uni-app'
  import { SM } from "@/http/http.js"
  import { api_getDictionary, api_inspectionTask, api_listCount, api_scanCode, api_inspectionNode, api_listAttachment } from "@/http/api.js"
  import { filterFormatDate } from '@/filters/filterFormatDate.js'
  import { computedPriorityStyle } from '@/filters/computedPriorityStyle.js'
  import { computedStateStyle } from '@/filters/computedStateStyle.js'
  import { computedCurrentLogOverTime } from '@/filters/computedCurrentLogOverTime.js'
  import { defaultColor } from '@/static/js/theme.js'
  import { useSetTitle } from '@/share/useSetTitle.js'
  import { useMakePhoneCall } from '@/share/useMakePhoneCall.js'
  import { useLoginUserStore } from '@/stores/loginUser'
  import { useIncidentNumStore } from '@/stores/incidentNum'
  import { useInspectionListSearchStore } from '@/stores/inspectionListSearch'
  import { useInspectionValueStore } from '@/stores/inspectionValue'
  import { useSetTabbar } from '@/share/useSetTabbar.js'
  import { useIncidentBuildStore } from '@/stores/incidentBuild'

  useSetTitle();
  const loginUserStore = useLoginUserStore();
  const incidentNumStore = useIncidentNumStore();
  const inspectionListSearchStore = useInspectionListSearchStore();
  const inspectionValueStore = useInspectionValueStore();
  const { formatDate }  = filterFormatDate();
  const { priorityStyle }  = computedPriorityStyle();
  const { stateStyle }  = computedStateStyle();
  const { currentLogOverTime }  = computedCurrentLogOverTime();
  const { makePhoneCall }  = useMakePhoneCall();
  const { setTabbar }  = useSetTabbar();
  const incidentBuildStore = useIncidentBuildStore();

  // 主题颜色
  const primaryColor = ref(defaultColor)
  
  // 故障来源列表
  const defaultSourceValue = ref();
  
  // 数据
  const dataInfo = reactive({
    tabs: [{id: 0, name: '巡检工单', value: 'todo', num: ''}, {id: 1, name: '历史工单', value: '', num: ''}],
    tabActiveId: 0,//当前选择的tab
    list: [],//工单列表
    idx: 0,//页码
    hasMore: true,//是否有更多数据
    inspectionNodeDTO: {},
    inspectionNodeNewCode: '',//巡检点二维码
    inspectionNodeCode: '',//巡检点原始二维码
    inspectionNodeName: '',
  })
  
  // 获取故障来源列表
  function getSources(){
    let postData = {
      "key": 'incident_source',
      "type": "list",
    };
    api_getDictionary(postData).then(res => {
      res = res || [];
      let discover = res.find(v => v.value === 'inspection');
      if(discover){
        defaultSourceValue.value = discover.id;
      }
    })
  }
  
  // 新建事件
  async function toBuildIncident(res){
  	incidentBuildStore.clearIncidentBuildData();
   let imgObj = res.inspectionFormValuesList.find(v => v.inspectionFormItemDTO.type.value == 7);
   let repairImgList = [];
   if(imgObj){
     let result = await api_listAttachment('inspection', res.id);
     result.data = result.data || [];
     result.data = result.data.filter(v => v.recordId == imgObj.itemId);
     result.data = result.data.map(v => ({
       url: location.origin + "/file" + v.relativeFilePath,
       path: location.origin + "/file" + v.relativeFilePath,
       size: v.size,
       name: v.name,
       extname: v.suffix,
     }))
     repairImgList = result.data;
   }
   
   console.log(repairImgList, 'repairImgList')
   
   let incidentData = {
     place: res.inspectionNodeDTO.floorDTO,
     houseNumber: res.inspectionNodeDTO.address,
     source: defaultSourceValue.value,
     description: res.inspectionFormValuesList.filter(v => v.exception == 1).map(v => `${v.name}填写值为${v.valuex ? v.valuex : (v.formItemConfigList ? v.formItemConfigList.map(vv => v.name).join('，') : '')}`).join('；'),
     requester: loginUserStore.loginUser.user,
     branch: loginUserStore.loginUser.user.currentHospital.parent ? loginUserStore.loginUser.user.currentHospital.parent.id : loginUserStore.loginUser.user.currentHospital.id,
     contacts: loginUserStore.loginUser.user.name,
     contactsInformation: loginUserStore.loginUser.user.phone,
     category: res.inspectionDTO.inspectionFormDTO.categoryDTO,
     department: res.inspectionDTO.inspectionFormDTO.repairDeptDTO,
     priority: res.inspectionDTO.inspectionFormDTO.priorityDTO,
     repairImgList,
     inspectionTaskId: res.id,
   }
   console.log(incidentData, 'incidentData')
   incidentBuildStore.setIncidentBuildData(incidentData, 'buildIncident');
   uni.navigateTo({
     url: `/pages/buildIncident/buildIncident?type=inspection`
   })
  }
  
  // 巡检项
  function toInspectionValue(data){
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    let postData = {
      code: dataInfo.inspectionNodeNewCode,
      taskId: data.id,
      account: loginUserStore.loginUser.user.account,
    };
    // 'inspection|$|1bd0c704-0962-4ed4-b5a6-b5bda3d78231'
    // 'inspection|$|bc9f61af-99c8-4c86-88f9-f29dd3fc43c0'
		// 'inspection|$|92e7bb9a-5f58-42f6-991a-fcd67247e295'
    api_scanCode(postData).then((res) => {
      uni.hideLoading();
      if (res.status == 200) {
        inspectionValueStore.setInspectionValueData(res.data);
        uni.navigateTo({
          url: `/pages/inspection/inspectionValue/inspectionValue?inspectionExecuteId=${data.id}`
        })
      } else {
        uni.showToast({
          icon: 'none',
          title: res.msg || '请求数据失败！'
        });
      }
    });
  }

  // 点击tab
  function clickTab(tabId){
    dataInfo.tabActiveId = tabId;
    getList(0);
  }

  // 获取列表信息
  function getList(idx){
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    dataInfo.idx = idx === undefined ? dataInfo.idx : idx;
    if(dataInfo.idx === 0){
      dataInfo.list = [];
    }
    let tabActiveObj = dataInfo.tabs.find(v => v.id == dataInfo.tabActiveId);
    let tabActiveObjIndex = dataInfo.tabs.findIndex(v => v.id == dataInfo.tabActiveId);
    let postData = {
        "idx": dataInfo.idx,
        "sum": 10,
        "inspectionTask": {
          "queryTask": tabActiveObj.value || undefined,
          "status": tabActiveObj.value ? undefined : { "value": 2 },
          "assignAccount": tabActiveObj.id == 0 ? loginUserStore.loginUser.user.account : undefined,
          "inspectionNodeDTO":{
            code: dataInfo.inspectionNodeCode,
          }
        }
    }

    api_inspectionTask(postData).then(res => {
      uni.hideLoading();
      uni.stopPullDownRefresh();
      if(res.status == 200){
        let list = res.list || [];
        dataInfo.tabs[tabActiveObjIndex].num = res.totalNum;
        if(list.length){
          dataInfo.hasMore = true;
          dataInfo.list = dataInfo.idx === 0 ? list : dataInfo.list.concat(list);
          dataInfo.inspectionNodeDTO = list[0].inspectionNodeDTO;
        }else{
          dataInfo.hasMore = false;
          dataInfo.inspectionNodeDTO = {};
        }
      }else{
        uni.showToast({
          icon: 'none',
          title: res.msg || '请求数据失败！'
        });
      }
    })

    getCount(tabActiveObj.id);
  }

  // 获取列表数量
  function getCount(id){
    dataInfo.tabs.forEach(v => {
      if(v.id != id){
        let tabActiveObj = v;
        let postData = {
            "idx": 0,
            "sum": 1,
            "inspectionTask": {
              "queryTask": tabActiveObj.value || undefined,
              "status": tabActiveObj.value ? undefined : { "value": 2 },
              "assignAccount": tabActiveObj.id == 0 ? loginUserStore.loginUser.user.account : undefined,
              "inspectionNodeDTO":{
                code: dataInfo.inspectionNodeCode,
              }
            }
        }
        api_inspectionTask(postData).then(res => {
          if(res.status == 200){
            v.num = res.totalNum;
          }else{
            uni.showToast({
              icon: 'none',
              title: res.msg || '请求数据失败！'
            });
          }
        })
      }
    })
  }
  
  onLoad((option) => {
    getSources();
    dataInfo.inspectionNodeCode = option.inspectionNodeCode;
    dataInfo.inspectionNodeNewCode = option.inspectionNodeNewCode;
    dataInfo.inspectionNodeName = option.inspectionNodeName;
    getList(0);
  })

  onPullDownRefresh(() => {
    getList(0)
  })

  onReachBottom(() => {
    dataInfo.idx += 1;
    if (dataInfo.hasMore) {
      getList(); // 当触底时加载更多数据
    }
  })
</script>

<style lang="scss" scoped>
.toolbar {
  position: fixed;
  left: 0;
  bottom: var(--window-bottom);
  z-index: 99;
  width: 100%;
  height: 88rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
  border-radius: 4rpx;
  background-color: #E5E8ED;

  .toolbar-icon {
    font-size: 52rpx;
    margin-right: 16rpx;
    color: #49B856;
  }

  .toolbar-sao {
    font-size: 36rpx;
    color: #333;
  }
}
.incidentList{
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .title{
    width: 100%;
    height: 88rpx;
    position: fixed;
    z-index: 99;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #EBEBEB;
    font-weight: bold;
    font-size: 32rpx;
  }
  .head{
    height: 88rpx;
    display: flex;
    top: 88rpx;
    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;
      &.active{
        color: $uni-primary;
        border-color: $uni-primary;
      }
    }
    .filter{
      width: 84rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      .newicon-shaixuan{
        font-size: 36rpx;
        color: #2C2C2C;
      }
    }
  }
  .body{
    margin-top: 176rpx;
    border-top: 6rpx solid #EBEBEB;
    .body_item{
      border-bottom: 8rpx solid #EBEBEB;
      .body_item_head{
        word-break: break-all;
        text-align: justify;
        text-align: left;
        margin: 24rpx;
        font-size: 30rpx;
        .sign{
          margin-right: 16rpx;
          font-weight: bold;
          color: #49B856;
          &.signRed{
            color: #FF0000;
          }
        }
      }
      .body_item_content{
        border-top: 1rpx solid #D8D8D8;
        padding: 24rpx 24rpx 24rpx 48rpx;
        .body_item_content_p{
          color: #6A6A6A;
          font-size: 26rpx;
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 24rpx;
          &:last-of-type{
            margin-bottom: 0;
          }
          .name{
            flex: 1;
          }
          .status{
            padding: 4rpx 10rpx;
            border-radius: 20rpx;
            background-color: #DBE8FE;
            font-size: 22rpx;
            color: #006CF9;
          }
          .icon_all{
            .mic-filled,
            .image-filled
            {
              margin-left: 16rpx;
            }
          }
        }
      }
      .body_item_foot{
        border-top: 1rpx solid #D8D8D8;
        font-size: 26rpx;
        padding: 24rpx;
        .foot_info{
          display: flex;
          justify-content: space-between;
          align-items: center;
          .phone-filled{
            margin-left: 5rpx;
          }
        }
      }
    }
  }
  .zanwu{
    box-sizing: border-box;
    margin-top: 176rpx;
    border-top: 6rpx solid #EBEBEB;
    height: calc(100vh - 88rpx);
    display: flex;
    justify-content: center;
    background-color: #F7F7F7;
    .newicon-zanwu{
      font-size: 256rpx;
      color: #D6D6D6;
      margin-top: 140rpx;
    }
  }
}
</style>
