<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">
          <text :style="priorityStyle(data.priority)">{{data.priority ? data.priority.name + ' ' : ''}}</text>{{data.description}}
        </view>
        
        <view class="body_item_content">
          <view class="body_item_content_p" v-if="data.department">
            <text class="name ellipsis">报修科室：{{data.department.dept}}</text>
            <view class="status" :style="stateStyle(data.state)">{{data.state ? data.state.name : ''}}</view>
          </view>
          <view class="body_item_content_p" v-if="data.place || data.houseNumber">
            <text class="name ellipsis">详细地址：{{data.place ? data.place.area.area : ''}}{{data.place ? data.place.place : ''}}{{data.houseNumber}}</text>
          </view>
          <view class="body_item_content_p" v-if="data.currentLog && data.currentLog.extra1DTO && data.currentLog.extra2 && data.currentLog.startTime">
            <text class="name ellipsis">延期处理：{{currentLogOverTime(data.currentLog)}}</text>
          </view>
          <view class="body_item_content_p">
            <text class="name"><template v-if="data.assigneeName">处理人：{{data.assigneeName}}</template></text>
            <text class="name"><template v-if="data.candidateGroupsName">处理组：{{data.candidateGroupsName}}</template></text>
            <view class="icon_all" @click="attachmentClick(data)">
              <uni-icons type="mic-filled" class="mic-filled" :size="22" color="#949494" v-if="data.callID"></uni-icons>
              <uni-icons type="image-filled" class="image-filled" :size="22" color="#949494" v-if="data.reqAttachment"></uni-icons>
            </view>
          </view>
        </view>
        
        <view class="body_item_foot">
          <view class="foot_info">
            <view class="name" @click="makePhoneCall(data.contactsInformation)">联系电话：{{data.contactsInformation}}<uni-icons type="phone-filled" class="phone-filled" :size="18" :color="primaryColor"></uni-icons></view>
            <text class="date">{{formatDate(data.startDate, 'MM-dd HH:mm')}}</text>
          </view>
          <view class="btns" v-if="data.state.value === 'pending' || data.state.value === 'handler'">
            <button @click="handler('changeUser')" type="default" class="primaryButton btn">换人处理</button>
            <button @click="handler('handler')" type="default" class="primaryButton btn" v-if="data.state.value === 'handler'">处理</button>
            <button @click="handler('receive')" type="default" class="primaryButton btn" v-if="data.state.value === 'pending'">接单</button>
          </view>
        </view>
      </view>
    </view>
    <view class="zanwu" v-else>
      <text class="newicon newicon-zanwu"></text>
    </view>
  </view>
  <incidentListFilter v-if="dataInfo.isFilter" @cancelEmit="cancelFilter" @confirmEmit="conformFilter" :evt="dataInfo.evtFilter"></incidentListFilter>
  <IncidentAttachment v-if="dataInfo.isAttachment" @knowEmit="knowAttachment" :incidentData="dataInfo.incidentData"></IncidentAttachment>
</template>

<script setup>
  import IncidentListFilter from '@/components/IncidentListFilter.vue';
  import IncidentAttachment from '@/components/IncidentAttachment.vue';
  import { ref, reactive } from 'vue'
  import { onLoad, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app'
  import { api_getDictionary, api_incident, api_incident_count } 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'
  
  useSetTitle();
  const loginUserStore = useLoginUserStore();
  const { formatDate }  = filterFormatDate();
  const { priorityStyle }  = computedPriorityStyle();
  const { stateStyle }  = computedStateStyle();
  const { currentLogOverTime }  = computedCurrentLogOverTime();
  const { makePhoneCall }  = useMakePhoneCall();
  
  // 主题颜色
  const primaryColor = ref(defaultColor)
  
  // 数据
  const dataInfo = reactive({
    tabs: [{id: 0, name: '全部', value: 'all', num: ''}],
    tabActiveId: 0,//当前选择的tab
    list: [],//事件列表
    idx: 0,//页码
    hasMore: true,//是否有更多数据
    isFilter: false,//筛选框开关
    isAttachment: false,//图片和录音开关
    incidentId: undefined,
    evtFilter: {
      hospital: {},
      selected: 'todoingAll',
      area: {id: 0, area: '全部'},
      category: {id: 0, category: '全部'},
    },//筛选框数据
  })
  
  // 获取tab选项
  function getTabs(){
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    api_getDictionary({
      "type": "list",
      "key": "incident_status"
    }).then(res => {
      uni.hideLoading();
      let incidentStatusList = res || [];
      let pending = incidentStatusList.find(v => v.value === 'pending');
      let handler = incidentStatusList.find(v => v.value === 'handler');
      dataInfo.tabs = [{id: 0, name: '全部', value: 'all', num: ''}];
      pending && dataInfo.tabs.push({...pending, ...{num: ''}});
      handler && dataInfo.tabs.push({...handler, ...{num: ''}});
      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 attachmentClick(incidentData){
    dataInfo.incidentData = incidentData;
    dataInfo.isAttachment = true;
  }
  
  // 知道了图片和录音
  function knowAttachment(){
    dataInfo.isAttachment = false;
  }
  
  // 处理按钮
  function handler(type){
    uni.navigateTo({
      url: `/pages/${type}/${type}`
    })
  }
  
  // 获取列表信息
  function getList(idx){
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    dataInfo.idx = idx === undefined ? dataInfo.idx : idx;
    if(dataInfo.idx === 0){
      dataInfo.list = [];
    }
    let postData = {
        "idx": dataInfo.idx,
        "sum": 10,
        "incident": {
            "queryTask": dataInfo.evtFilter.selected || undefined,
            "assignee": loginUserStore.loginUser.user.id,
            "statusId": dataInfo.tabActiveId || undefined,
        }
    }
    
    if(loginUserStore.loginUser.user.duty){
      // 当前的所属责任科室
      postData.incident.duty = loginUserStore.loginUser.user.duty;
    }else if(loginUserStore.loginUser.user.branch){
      // 当前的所属院区
      postData.incident.branch = loginUserStore.loginUser.user.branch.id;
    }
    
    if(dataInfo.evtFilter && dataInfo.evtFilter.category && dataInfo.evtFilter.category.id){
      postData.incident.levelCategory = dataInfo.evtFilter.category;
    }
    if(dataInfo.evtFilter && dataInfo.evtFilter.area && dataInfo.evtFilter.area.id){
      postData.incident.area = dataInfo.evtFilter.area;
    }
    
    api_incident(postData).then(res => {
      uni.hideLoading();
      uni.stopPullDownRefresh();
      if(res.status == 200){
        let list = res.list || [];
        list = list.map(v => ({...v, ...{reqAttachment: true, callID:123}}))//模拟
        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.incident);
  }
  
  // 获取列表数量
  function getCount(incident = {}){
    let postData = {
      wxCount: 'true',
      incidentList: [],
    }
    dataInfo.tabs.forEach(v => {
        postData.incidentList.push({...incident, ...{statusId: v.id || undefined}});
    })
    
    postData.incidentList.forEach(incident => {
        // 请求参数调整
        if(!incident){
            incident = {};
        }
        
        if(incident.queryTask === 'all' || incident.queryTask === 'callback'){
            if(loginUserStore.loginUser.user.duty){
                // 当前的所属责任科室
                incident.duty = loginUserStore.loginUser.user.duty;
            }else if(loginUserStore.loginUser.user.branch){
                // 当前的所属院区
                incident.branch = loginUserStore.loginUser.user.branch.id;
            }
        }else{
            delete incident.duty;
            delete incident.branch;
        }
        
        incident.assignee = loginUserStore.loginUser.user.id;
        
        if(incident.queryTask === 'todo' || incident.queryTask === 'owns'){
            incident.candidateGroups = loginUserStore.loginUser.user.group.map(v => v.id).toString();
        }else{
            delete incident.candidateGroups;
        }
        
        if(dataInfo.evtFilter && dataInfo.evtFilter.category && dataInfo.evtFilter.category.id){
          incident.levelCategory = dataInfo.evtFilter.category;
        }
        
        if(dataInfo.evtFilter && dataInfo.evtFilter.area && dataInfo.evtFilter.area.id){
          incident.place = {
            area: dataInfo.evtFilter.area
          }
        }
    })
    api_incident_count(postData).then(res => {
      if(res.state == 200){
        let myData = res.data || [];
        dataInfo.tabs.forEach((v, i) => {
            v.num = myData[i];
        })
      }else{
        uni.showToast({
          icon: 'none',
          title: res.msg || '请求数据失败！'
        });
      }
    })
  }
  
  onLoad((option) => {
    getTabs();
  })
  
  onPullDownRefresh(() => {
    getList(0)
  })
  
  onReachBottom(() => {
    dataInfo.idx += 1;
    if (dataInfo.hasMore) {
      getList(); // 当触底时加载更多数据
    }
  })
</script>

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