<template>
  <view class="incidentList">
    <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 class="filter" @click="filterClick">
        <text class="newicon newicon-shaixuan"></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">
          {{ 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'" @click.stop="toInspectionValue(data)" type="default" class="primaryButton btn">执行</button>
          </view>
        </view>
      </view>
    </view>
    <view class="zanwu" v-else>
      <text class="newicon newicon-zanwu"></text>
    </view>
    <InspectionListFilter v-if="dataInfo.isFilter" @cancelEmit="cancelFilter" @confirmEmit="conformFilter" :evt="dataInfo.evtFilter"></InspectionListFilter>
  </view>
</template>

<script setup>
  import InspectionListFilter from '@/components/InspectionListFilter.vue';
  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 } 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'

  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 primaryColor = ref(defaultColor)

  const assignFlag = ref(false);//指派权限
  const qiangdan = ref(false);//接单权限

  // 转换协同人
  const computedSynergetic = computed(() => (synergetic) => {
    return (synergetic && synergetic.length) ? synergetic.map(v => v.name).join('，') : ''
  })

  // 数据
  const dataInfo = reactive({
    tabs: [{id: 0, name: '全部', value: 'all', num: ''}],
    tabActiveId: 0,//当前选择的tab
    list: [],//工单列表
    idx: 0,//页码
    hasMore: true,//是否有更多数据
    isFilter: false,//筛选框开关
    evtFilter: {
      area: {id: 0, area: '全部'},
      inspectionForm: {id: 0, name: '全部'},
      acceptDate: [],
    },//筛选框数据
  })

  // 巡检项
  function toInspectionValue(data){
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    // 'inspection|$|1bd0c704-0962-4ed4-b5a6-b5bda3d78231'
    // 'inspection|$|bc9f61af-99c8-4c86-88f9-f29dd3fc43c0'
		// 'inspection|$|92e7bb9a-5f58-42f6-991a-fcd67247e295'
    SM().then((ress1) => {
      let postData = {
        code: ress1,
        taskId: data.id,
        account: loginUserStore.loginUser.user.account,
      };
      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 || '请求数据失败！'
          });
        }
      });
    }).catch(err=>{
      uni.hideLoading();
    });
  }

  // 获取tab选项
  function getTabs(){
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    api_getDictionary({
      "type": "list",
      "key": "inspection_task_status"
    }).then(res => {
      uni.hideLoading();
      let list = res || [];
      let todo = list.find(v => v.value === '1');
      let close = list.find(v => v.value === '2');
      dataInfo.tabs = [{id: 0, name: '全部', value: 'all', num: ''}];
      todo && dataInfo.tabs.push({...todo, ...{num: '', value: 'todo'}});
      close && dataInfo.tabs.push({...close, ...{num: '', value: 'close'}});
      getList(0);
    })
  }

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

  // 点击筛选
  function filterClick(){
    dataInfo.isFilter = true;
  }

  // 确认筛选
  function conformFilter(evtFilter){
    dataInfo.evtFilter = evtFilter;
    dataInfo.isFilter = false;
    getList(0);
  }

  // 关闭筛选
  function cancelFilter(){
    dataInfo.isFilter = false;
  }

  // 获取列表信息
  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 postData = {
        "idx": dataInfo.idx,
        "sum": 10,
        "account": loginUserStore.loginUser.user.account,
        "inspectionTask": {
          "queryTask": tabActiveObj ? tabActiveObj.value : undefined,
          "assignAccount": loginUserStore.loginUser.user.account,
        }
    }

    if(dataInfo.evtFilter && dataInfo.evtFilter.inspectionForm && dataInfo.evtFilter.inspectionForm.id){
      postData.inspectionTask.formId = dataInfo.evtFilter.inspectionForm.id;
    }

    if(dataInfo.evtFilter && Array.isArray(dataInfo.evtFilter.acceptDate) && dataInfo.evtFilter.acceptDate.length){
      postData.inspectionTask.addTimeStart = format(startOfDay(new Date(dataInfo.evtFilter.acceptDate[0])), 'yyyy-MM-dd HH:mm:ss');
      postData.inspectionTask.addTimeEnd = format(endOfDay(dataInfo.evtFilter.acceptDate[1]), 'yyyy-MM-dd HH:mm:ss');
    }

    if(dataInfo.evtFilter && dataInfo.evtFilter.area && dataInfo.evtFilter.area.id){
      postData.inspectionTask.buildId = dataInfo.evtFilter.area.id;
    }

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

    getCount(postData.inspectionTask);
  }

  // 获取列表数量
  function getCount(inspectionTask = {}){
    let postData = {
      account: loginUserStore.loginUser.user.account,
      taskList: [],
    }
    dataInfo.tabs.forEach(v => {
        postData.taskList.push({...inspectionTask, ...{ queryTask: v.value }});
    })

    api_listCount(postData).then(res => {
      if(res.state == 200){
        let myData = res.data || [];
        dataInfo.tabs.forEach((v) => {
            v.num = myData[v.value];
        })
      }else{
        uni.showToast({
          icon: 'none',
          title: res.msg || '请求数据失败！'
        });
      }
    })
  }

  // 初始化
  function onLoadFn(){
    // 我的-数量跳转
    if(inspectionListSearchStore.inspectionListSearch.data){
      // 缓存的搜索条件
      Object.assign(dataInfo, inspectionListSearchStore.inspectionListSearch.data);
    }
    getTabs();
  }

  onLoad((option) => {
    for(let i = 0; i<5; i++){
    	setTabbar(i)
    }
    onLoadFn();
  })

  onTabItemTap(e => {
    onLoadFn();
  })

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

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

<style lang="scss" scoped>
page{
  height: calc(100vh - var(--window-bottom));
}
.incidentList{
  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;
      &.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-bottom: var(--window-bottom);
    margin-top: 88rpx;
    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;
      }
      .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-bottom: var(--window-bottom);
    margin-top: 88rpx;
    border-top: 6rpx solid #EBEBEB;
    height: calc(100vh - var(--window-bottom) - 88rpx);
    display: flex;
    justify-content: center;
    background-color: #F7F7F7;
    .newicon-zanwu{
      font-size: 256rpx;
      color: #D6D6D6;
      margin-top: 140rpx;
    }
  }
}
</style>
