<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" @click.stop="toIncidentDetail(data)">
        <view class="body_item_head ellipsis-multiline">
          {{data.description}}
        </view>

        <view class="body_item_content">
					<view class="body_item_content_p" v-if="data.place || data.houseNumber">
					  <text class="name ellipsis">详细地址：{{data.place ? data.place.building.buildingName : ''}}{{data.place ? data.place.floorName : ''}}<text v-if="data.place && data.place.floorName">层</text> {{data.houseNumber}}</text>
						<view class="status" :style="stateStyle(data.state)">{{data.state ? data.state.name : ''}}</view>
					</view>
          <view class="body_item_content_p" v-if="data.rsPrice">
            <text class="name ellipsis">维修总价：{{data.rsPrice}}</text>
          </view>
          <view class="body_item_content_p">
						 <view class="name ellipsis" @click.stop="makePhoneCall(data.contactsInformation)">维修人员电话：{{data.contactsInformation || '暂无'}}<uni-icons v-if="data.contactsInformation" type="phone-filled" class="phone-filled" :size="18" :color="primaryColor"></uni-icons></view>
          </view>
					<view class="body_item_content_p" v-if="data.currentLog && data.currentLog.logType.value=='overtime'">
					  <text class="name ellipsis">维修说明：{{data.overtimeRemark}}</text>
					</view>
        </view>

        <view class="body_item_foot">
          <view class="foot_info">
            <view class="name">维修人员：{{data.assigneeName || '暂无'}}</view>
            <text class="date">{{formatDate(data.startDate, 'yyyy-MM-dd HH:mm')}}</text>
          </view>
          <view class="btns">
            <button v-if="!data.wxdegree && (data.state.name=='待评价'|| data.state.name=='已关闭')" @click.stop="handler('changeUser', data)" type="default" class="primaryButton btn">评价</button>
          </view>
        </view>
				<div class="sign-style" v-if="deptRepair && publicRepair">
					<view class="img-box" v-if="data.repairIncidentType && data.repairIncidentType.name=='科室报修'">
						<view class="img-url1"></view>
						<view class="img-name">科</view>
					</view>
					<view class="img-box" v-if="data.repairIncidentType && data.repairIncidentType.name=='公共报修'">
						<view class="img-url2"></view>
						<view class="img-name">公</view>
					</view>
				</div>
      </view>
    </view>
    <view class="zanwu" v-else>
      <text class="newicon newicon-zanwu"></text>
    </view>
    <repairsFilter v-if="dataInfo.isFilter" @cancelEmit="cancelFilter" @confirmEmit="conformFilter" :evt="dataInfo.evtFilter"></repairsFilter>
    <IncidentAttachment v-if="dataInfo.isAttachment" @knowEmit="knowAttachment" :incidentData="dataInfo.incidentData"></IncidentAttachment>
		<uni-popup ref="popup" background-color="#fff" type="center" :before-close="true">
			<view class="popup-content">
				<view class="form_item column">
					<view class="title"><text class="required newicon newicon-bitian"></text>星级：</view>
					<uni-rate class="value" v-model="rate" />
				</view>
				<view class="form_item column">
					<view class="title"><text class="required newicon newicon-bitian"></text>内容：</view>
					<uni-easyinput class="value" type="textarea" v-model="wxdegreeremark" placeholder="请输入评价内容"/>
				</view>
			</view>
			<view class="foot_common_btns">
			  <button @click="closePop" type="default" class="cancelButton btn">取消</button>
			  <button @click="submit" type="default" class="primaryButton btn">提交</button>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
  import repairsFilter from '@/components/repairsFilter.vue';
  import IncidentAttachment from '@/components/IncidentAttachment.vue';
  import { startOfDay, endOfDay, format, add } from 'date-fns'
  import { ref, reactive, computed } from 'vue'
  import { onLoad, onShow, onHide, onPullDownRefresh, onReachBottom, onTabItemTap } from '@dcloudio/uni-app'
  import { api_getDictionary, api_incident, api_incident_count, api_incidentTask, api_taskresolve } 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 { useIncidentListSearchStore } from '@/stores/incidentListSearch'
	import { repositoryListSearchStore } from '@/stores/repositorySearch'
	
  useSetTitle();
	const repositorySearchStore = repositoryListSearchStore();
  const loginUserStore = useLoginUserStore();
  const incidentNumStore = useIncidentNumStore();
  const incidentListSearchStore = useIncidentListSearchStore();
  const { formatDate }  = filterFormatDate();
  const { priorityStyle }  = computedPriorityStyle();
  const { stateStyle }  = computedStateStyle();
  const { currentLogOverTime }  = computedCurrentLogOverTime();
  const { makePhoneCall }  = useMakePhoneCall();

  // 主题颜色
  const primaryColor = ref(defaultColor)
	const popup = ref(null);//弹框
  const assignFlag = ref(false);//指派权限
  const qiangdan = ref(false);//接单权限
	const deptRepair = ref({});//科内报修
	const publicRepair = ref({});//公共报修
	
	const degreeDictionary = ref(null); //星级字典
	const rowData = ref(null); //选择的数据
	const isSubmit = ref(false);
	const rate = ref(3);//星级
	const wxdegreeremark = ref(null);//评价内容
	
  // 判断是否显示接单按钮
  const computedReceive = computed(() => (data) => {
    let inUser = data.currentLog && data.currentLog.workerId == loginUserStore.loginUser.user.id;
    let inGroup = false;
    loginUserStore.loginUser.user.group.forEach(item => {
        if(data.currentLog){
            if (item.id == data.currentLog.groupId) {
                inGroup = true;
            }
        }
    })
    return data.state.value === 'pending' && (inUser || inGroup) && qiangdan.value;
  })

  // 转换协同人
  const computedSynergetic = computed(() => (synergetic) => {
    return (synergetic && synergetic.length) ? synergetic.map(v => v.name).join('，') : ''
  })
	
	const repairIncident = ref(null);
	
  // 数据
  const dataInfo = reactive({
    tabs: [{id: 0, name: '我的报修', value: 'all', num: ''},],
    tabActiveId: 0,//当前选择的tab
    list: [],//工单列表
    idx: 0,//页码
    hasMore: true,//是否有更多数据
    isFilter: false,//筛选框开关
    isAttachment: false,//图片和录音开关
    incidentId: undefined,
		stateValue:0,
    evtFilter: {
      hospital: {},
      selected: 'todoingAll',
      area: {id: 0, area: '全部'},
      category: {id: 0, category: '全部'},
      acceptDate: [],
    },//筛选框数据
  })

  // 工单详情
  function toIncidentDetail(data){
    uni.navigateTo({
      url: `/pages/repair/repairsDetail?incidentId=${data.id}`
    })
  }

  // 获取tab选项
  function getTabs(){
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
		let data = JSON.parse(uni.getStorageSync('sysData'))
		deptRepair.value = data.find(i=>i.keyconfig=='deptRepair')
		publicRepair.value = data.find(i=>i.keyconfig=='publicRepair')
		let postData = {
		  "key": 'repair_incident_type',
		  "type": "list",
		};
		if(deptRepair.value.valueconfig==1){
			api_getDictionary(postData).then(res => {
			  res = res || [];
			  repairIncident.value = res.find(i=>i.value=='dept')
				getList(0);
			})
			 dataInfo.tabs = [
				 {id: 0, name: '我的报修', value: 'all', num: ''},
				 {id: 1, name: '科内报修', value: '2', num: ''}
			 ]
		}else{
			getList(0);
			dataInfo.tabs = [
				{id: 0, name: '我的报修', value: 'all', num: ''},
			]
		}
  }

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

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

  // 确认筛选
  function conformFilter(evtFilter){
    dataInfo.stateValue = evtFilter.category;
    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, data){
		rowData.value = data
		popup.value.open()
		let postData = {
		  key: "incident_degree",
		  type: "list"
		};
		api_getDictionary(postData).then(res => {
		  res = res || [];
			degreeDictionary.value = res
		})
  }
	
	function closePop(){
		rate.value = 3
		wxdegreeremark.value = null
		popup.value.close()
	}
	
	function submit(){
		if(!rate.value){
			uni.showToast({
				icon: 'none',
			  title: '请选择星级'
			});
			return;
		}
		if(!wxdegreeremark.value){
			uni.showToast({
				icon: 'none',
			  title: '请输入评价内容'
			});
			return;
		}
		let rateData = null
		if(rate.value==0){
		   rateData=degreeDictionary.value[0].id
		}else if(rate.value==1){
		   rateData=degreeDictionary.value[4].id
		}else if(rate.value==2){
		   rateData=degreeDictionary.value[3].id
		}else if(rate.value==3){
		   rateData=degreeDictionary.value[2].id
		}else if(rate.value==4){
		   rateData=degreeDictionary.value[1].id
		}else if(rate.value==5){
		   rateData=degreeDictionary.value[0].id
		}
		let postData = {
			...rowData.value,
			wxdegree: rateData==0?degreeDictionary.value[0]:{id: rateData},
			wxdegreeremark: wxdegreeremark.value
		}
		api_taskresolve({incident:postData}).then(res => {
		  uni.hideLoading();
		  if(res.state == 200){
		    getList(0);
		    uni.showToast({
		    	icon: 'none',
		      title: '评价成功',
		    });
		  }else{
		    uni.showToast({
		      icon: 'none',
		      title: res.msg || '请求数据失败！'
		    });
		  }
		})
		closePop()
	}
	

  // 获取列表信息
  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": 20,
			incident: {
				requester: dataInfo.tabActiveId == 0 ? { id: loginUserStore.loginUser.user.id } : undefined,
				department: dataInfo.tabActiveId == 1 ? { id: loginUserStore.loginUser.user.dept.id } : undefined,
				statesValues: (dataInfo.stateValue === 'close0' || dataInfo.stateValue === 'close1') ? 'close' : (dataInfo.stateValue || undefined),
				hasWxdegree: dataInfo.stateValue === 'close0' ? 0 : (dataInfo.stateValue === 'close1' ? 1 : undefined),
				repairIncidentType:{
					id:''
				}
			}
    }
		if(dataInfo.tabActiveId == 1){
			postData.incident.repairIncidentType.id = repairIncident.value.id
		}
		if(JSON.stringify(postData.incident.statesValues) === '{}'){
			delete postData.incident.statesValues
		}
    api_incident(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.incident);
  }
	
  // 获取列表数量
  function getCount(incident = {}){
    let postData = {
      wxCount: 'true',
      incidentList: [],
    }
    dataInfo.tabs.forEach(v => {
        postData.incidentList.push({...incident, ...{statusId: v.id || undefined}});
    })

    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 || '请求数据失败！'
        });
      }
    })
  }

  // 初始化
  function onLoadFn(){
    getTabs();
  }

  onLoad((option) => {
		dataInfo.tabActiveId = Number(option.type)
		dataInfo.stateValue = option.value
		dataInfo.evtFilter.category = option.value
		repositorySearchStore.setRepositoryListSearchData(dataInfo.evtFilter)
    onLoadFn();
  })
	
	onShow((option) =>{
		
	})
	
	onHide(_=>{
		repositorySearchStore.clearRepositoryListSearchData()
	})
	
  onTabItemTap(e => {
    // onLoadFn();
  })

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

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

<style scoped>
	>>> .uni-popup__wrapper{
		width: 80%;
		padding: 40rpx;
	}
</style>
<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;
			position: relative;
			.sign-style{
				position: absolute;
				right: 0;
				top: -25rpx;
				.img-box{
					position: relative;
					.img-url1{
						width: 70rpx;
						height: 70rpx;
						background-image: url('../../static/img/jiaobiao1.png');
					}
					.img-url2{
						width: 70rpx;
						height: 70rpx;
						background-image: url('../../static/img/jiaobiao2.png');
					}
					.img-name{
						position: absolute;
						right: 8rpx;
						top: 0;
						color: #fff;
						font-size: 24rpx;
					}
				}
			}
      .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;
    }
  }
	.popup-content{
		.form_item{
		  display: flex;
		  align-items: center;
		  padding-top: 24rpx;
		  min-height: 86rpx;
			position: relative;
			.chunk{
				width: 100%;
				height: 70rpx;
				line-height: 70rpx;
				text-align: center;
				background: #F7F8FA;
				box-shadow: 0px 3px 6px 1px rgba(0,0,0,0.16);
				border-radius: 10rpx;
			}
		  &.column{
		    height: auto;
		    flex-direction: column;
		    align-items: flex-start;
				.import-rep{
					padding: 5rpx 10rpx;
					border-radius: 50rpx;
					background: #d1fcd5;
					color: #49b856;
					font-size: 24rpx;
				}
		    .title{
		      margin-right: 0;
		    }
				.title-width{
					width: 100%;
				}
				.title-fl-sb{
					display: flex;
					justify-content: space-between;
					width: 100%;
				}
		    .value{
		      margin-top: 10rpx;
		      // padding-left: 20rpx;
		      box-sizing: border-box;
		    }
		    .tips{
		      padding: 24rpx;
		      text-align: center;
		      font-size: 22rpx;
		      color: #909399;
		      width: 100%;
		      box-sizing: border-box;
		    }
		  }
		  .title{
		    font-size: 26rpx;
		    display: flex;
		    align-items: center;
		    margin-right: 12rpx;
		    flex-shrink: 0;
		    &.select{
		      width: calc(5em + 20rpx);
		    }
		  }
		  .value{
		    width: 100%;
		    &.category{
		      width: 100%;
		      display: flex;
		      justify-content: space-between;
		      align-items: center;
		      .categoryName{
		        font-size: 26rpx;
		        color: #555;
		        flex: 1;
		      }
		      .newicon-weibiaoti2010104{
		        color: $uni-primary;
		        margin-left: 24rpx;
		      }
		    }
		    .imgTips{
		      color: #909399;
		      font-size: 22rpx;
					margin-top: 10rpx;
		    }
		  }
			.item-input{
				border: 1px solid #DBDBDB;
				height: 70rpx;
				line-height: 70rpx;
				padding: 0 10rpx;
				border-radius: 4rpx;
				width: 100%;
				font-size: 14px;
			}
			.icon{
				position: absolute;
				right: 20rpx;
				color: #49b856;
			}
		}
	}
	
}
</style>
