<template>
  <view class="list">
    <view class="list-top">
     <!-- <u-input
        placeholder="关键字搜索"
        prefixIcon="search"
        border="none"
        v-model="queryList.keywords"
        @change="change"
        prefixIconStyle="font-size: 52rpx;color: #000"
      ></u-input> -->
      <view class="tab-th">
        <text class="dressingTime" @click="startTimeShow = true">{{
          time
        }}</text>
        <text class="dressingStatusInfo" @click="statusShow = true">{{
          statusInfo
        }}</text>
        <view class="icon">
          <text class="close-circle" @click="isBatchCancelShow = true"></text>
          <text class="share-square" @click="isExportShow = true"></text>
        </view>
      </view>
    </view>
    <view class="list-content">
		<view class="list-content-top">
			<view class="list-content-info"  v-for="(item,index) in coums" :key="index" :style="{width: item.width}">
				{{item.name}}
			</view>
		</view>
		<view class="list-content-center">
			<view class="list-content-center-info" v-for="(item, index) in list" :key="index">
				<view class="" style="width: 130rpx;font-size: 22rpx;text-align: center;" @click="eyeLoock(item, item.status === '1' ? '1' : '2')">
					<text>{{item.keywords}}</text>
					<text>({{item.devcode}})</text>
				</view>
				<view class="" style="width: 140rpx;font-size: 22rpx;text-align: center;" @click="eyeLoock(item, item.status === '1' ? '1' : '2')">
					{{item.alarmMessage}}
				</view>
				<view class="" style="width: 100rpx;font-size: 22rpx;text-align: center;" @click="eyeLoock(item, item.status === '1' ? '1' : '2')">
					{{item.alarmValue}}
				</view>
				<view class="" style="width: 150rpx;font-size: 22rpx;text-align: center;" @click="eyeLoock(item, item.status === '1' ? '1' : '2')">
					{{item.alarmTime}}
				</view>
				<!-- <view class="error-report error-report-red" v-if="!item.show" style="width: 110rpx;font-size: 22rpx;" @click="ispassShow = true">
					取消告警
				</view> -->
				<view class="error-report " :class="item.status === '1' ? 'error-report-red' : 'error-report-orange'" @click=" item.status === '1' ? getInfoId(item.id) : eyeLoock(item,'2')">
					{{item.status === '1' ? '取消报警' : '已消警'}}
				</view>
			</view>
		</view>
    </view>
    <u-popup
      :show="isExportShow"
      mode="bottom"
      :round="10"
      :closeOnClickOverlay="false"
      @close="close"
    >
      <view class="popup">
		<view class="title">提示</view>
        <view class="content">
          确认将所有的数据导出吗？
        </view>
        <view class="footer">
		<button class="allow refuse" @click="isExportShow = false">取消</button>
		<button class="allow" @click="exportQr"> 确认</button>
        </view>
      </view>
    </u-popup>
	<u-popup
	  :show="isBatchCancelShow"
	  mode="bottom"
	  :round="10"
	  :closeOnClickOverlay="false"
	  @close="isBatchCancelShow = false"
	>
	  <view class="popup">
		<view class="title">提示</view>
	    <view class="content">
	      确认将所有的数据消除警告吗？
	    </view>
	    <view class="footer">
		<button class="allow refuse" @click="isBatchCancelShow = false">取消</button>
		<button class="allow" @click="batchCancelQr"> 确认</button>
	    </view>
	  </view>
	</u-popup>
    <u-popup
      :show="ispassShow"
      mode="bottom"
      :round="10"
      :closeOnClickOverlay="false"
      @close="close"
    >
      <view class="popup">
		 <view class="title">取消告警</view>
        <u-form
			labelPosition="left"
			labelWidth="200rpx"
			:model="userInfo"
			:rules="rules"
			ref="form1"
        		>
			<u-form-item
			label="告警取消原因"
			prop="name"
			borderBottom
			@click="showSex = true;"
			ref="item1"
		  >
			<u-input
				v-model="userInfo.name"
				disabled
				placeholder="请选择告警取消原因"
				border="none"
				suffixIcon="arrow-right"
			></u-input>
		</u-form-item>
		<u-form-item
			label="备注"
			prop="handleMessage"
			borderBottom
			ref="item2"
	>
		<u-input
		v-model="userInfo.handleMessage"
		border="none"
		></u-input>
	</u-form-item>
        </u-form>
        <view class="footer">
		<button class="allow refuse" @click="ispassShow = false"> 取消</button>
		<button class="allow" @click="possQr"> 确认</button>
        </view>
      </view>
    </u-popup>
	<u-action-sheet
		:show="showSex"
		:actions="actions"
		title="请选择处理状态"
		@close="showSex = false"
		@select="sexSelect"
			>
	</u-action-sheet>
    <u-datetime-picker
      :show="startTimeShow"
      mode="datetime"
      title="请选择开始时间"
      :formatter="formatter"
	  v-model="startTimeDefult"
      @cancel="closeTime"
      @confirm="confirmTime"
    >
    </u-datetime-picker>
		
    <u-datetime-picker
      :show="endTimeShow"
      mode="datetime"
      title="请选择结束时间"
      :formatter="formatter"
	  v-model="endTimeDefult"
      @cancel="endTimeShow = false"
      @confirm="confirmEndTime"
    >
    </u-datetime-picker>
    <u-action-sheet
      :show="statusShow"
      :actions="statusList"
      title="请选择状态"
      description="只能单选"
      @close="statusShow = false"
      @select="statusSelect"
    >
    </u-action-sheet>
     <!-- 底部提示 -->
	<LoadingList :loading="loading" :nothingMore="nothingMore" />
  </view>
</template>

<script>
import { getAlarm, getCancelAlarm, getBatchCancel } from "@/api/check.js";
import { debounce } from "@/common/utils.js";
import { getLastMonth } from "@/common/formatTime.js";
import { solveStatus } from "@/api/message.js";
import { verifyPhone } from "@/api/index.js";
import { getLogin, getUserProfile } from "@/utils/auth.js";
import BASE_URL from "@/api/base.js";
import LoadingList from '@/components/base/LoadingList.vue';
export default {
  components: {
      LoadingList
  },
  data() {
    return {
      queryList: {
        keywords: '',
        alarmType: '',
        alarmContent: '',
        beginTime: '',
        endTime: '',
        status: '',
        offset: 1,
        limit: 20,
        sort: '',
        order: '',
      },
	  startTimeDefult:Number(new Date()),
	  endTimeDefult:Number(new Date()),
		userInfo: {
			handleMessage: '',
			name: '',
			jobStatus:''
		},
	  actions: [{
			name: '已处理',
			id: '3'
			},
			{
			name: '无需处理',
			id: '4'
			},
	  			],
      list: [],
	  type: '', // 是否是批量消警
	  coums:[
		  {name:'设备信息',width: '150rpx'}, 
		  {name:'告警原因',width: '150rpx'},
		  {name:'告警数值',width: '130rpx'},
		  {name:'告警时间',width: '145rpx'},
		  {name:'操作',width: '100rpx'}],
		  rules: {
			'handleMessage': {
				type: 'string',
				required: true,
				message: '请填写备注',
				trigger: ['blur', 'change']
			},
			'name': {
				type: 'string',
				required: true,
				message: '请选择如何处理',
				trigger: ['blur', 'change']
			},
		},
      isExportShow: false, // 导出提示框开关
      ispassShow: false,
	  isBatchCancelShow: false, // 批量消警按钮开关
	  statusShow: false, // 控制处理状态开关
	  showSex:false, // 选择具体处理情况开关
      startTimeShow: false,
      endTimeShow: false,
      TimeNextShow: false,
	  infoId:'', // 取消报警id
      statusList: [
        { name: "全部", id: "" },
        { name: "告警中", id: "1" },
        { name: "历史告警", id: "2" },
      ],
      time: "筛选时间",
      isTimeQ: "",
      isTimeZ: "",
      statusInfo: "筛选状态",
      popShow: false, //控制授权手机号弹出框
	  offset: 1,   //页数
	  limit: 10,   //一页几条数据
	  nothingMore: false, //上拉加载-没有数据了
	  loading: false, //是否显示上拉加载-加载中
    };
  },
  async onShow() {
	this.offset = 1;
    let pages = getCurrentPages();
    const curPage = pages[pages.length - 1];
    this.currentPagePath = curPage.route;
    uni.setStorageSync("currentPagePath", this.currentPagePath);
    this.getAlarmList()
  },
  //下拉刷新
  onPullDownRefresh() {
    this.queryList = {
      keywords: '',
      alarmType: '',
      alarmContent: '',
      beginTime: '',
      endTime: '',
      status: '',
      offset: 1,
      limit: 20,
      sort: '',
      order: '',
    };
    this.statusInfo = "筛选状态";
    this.time = "筛选时间";
	this.getAlarmList(false)
    this.getAlarmList(false).then(() => {
			uni.stopPullDownRefresh(); 
		});
  },
	//上滑加载
	onReachBottom() {
		this.getLoadingList();
	},
  methods: {
	  // 点击批量消警的确认按钮
	 async batchCancelQr() {
		 this.ispassShow = true
		 this.type = 'all'
		 this.queryList.offset = 1
		 this.isBatchCancelShow = false
	  },
	  // 获取id
	  getInfoId(id) {
		this.infoId = id
		this.type = ''
		this.ispassShow = true  
	  },
	  async getAlarmList(type) { // 获取到报警列表
	   const res = await getAlarm(this.queryList)
	    if(res.rows && res.rows.length) {
			const resData = res.rows.map(item=> {
				if( item.devcode === '412022060001' || item.devcode === '412022060002' || item.devcode === '412022060003'){
					item.keywords = '井盖状态监测仪'
				}else if (item.devcode === '312022040441'){
					item.keywords = '燃气智能监测终端'
				}else {
					item.keywords = '液位监测仪'
				}
				return item
			})
			this.nothingMore = false
			if(type){
				this.list = this.list.concat(resData);
			}else {
				this.list = resData
			}	
		}else {
			if(res.total === 0) {
				this.list = []
			}
			this.nothingMore = true
		}
	   },
	  sexSelect(e) {  // 选择状态
	    this.userInfo.name = e.name
		this.userInfo.jobStatus = e.id
		this.$refs.form1.validateField('name')
	 },
    //搜索框发生改变
   //  async change(e) {
   //    // this.getAlarmList()
   //  },
    //确定导出
    async exportClick() {
      const sessionId = uni.getStorageSync("token");
      let filePath = `${wx.env.USER_DATA_PATH}/${+new Date()}.xlsx`;
      uni.request({
        url: `https://smartwell.gd.smartlog.work/alarm/export`,
        responseType: "arraybuffer",
		params:this.queryList,
        header: {
          token: sessionId, //自定义请求头信息
        },
        success: ({ data }) => {
          let fm = wx.getFileSystemManager();
          fm.writeFile({
            filePath,
            data,
            success: (res) => {
              uni.openDocument({
                filePath,
                fileType: "xlsx",
                showMenu: true,
              });
            },
          });
        },
      });
    },
    //根据条件搜索
    async searchList(is) {
    },
    //选中状态
    statusSelect(e) {
	this.statusInfo = e.name	
	this.queryList.status = e.id
	this.queryList.offset = 1
	this.getAlarmList(false)
    },
	// 点击取消告警弹窗中的确认按钮
    async possQr() {
		let res = null
	  if(this.userInfo.jobStatus.trim() !== ''){
		  if(this.type === 'all') {
			  const params = {
				 keywords:this.queryList.keywords || '',
				 alarmType :this.queryList.alarmType || '',
				 alarmContent:this.queryList.alarmContent || '',
				 beginTime:this.queryList.beginTime || '',
				 endTime:this.queryList.endTime || '',
				 jobStatus:this.userInfo.jobStatus,
				 handleMessage:this.userInfo.handleMessage
			  }
			     res = await getBatchCancel(params)
		  }else {
			     res = await getCancelAlarm({...this.userInfo , id:this.infoId})
		  }
		 uni.showToast({
			title: `告警取消成功`,
			icon: 'none',
			duration: 2000,
		 }) 
		 this.ispassShow = false
		 this.list = []
		 this.getAlarmList(false)
	  }else {
		  uni.showToast({
		  	title: `告警取消原因必选`,
		  	icon: 'none',
		  	duration: 2000,
		  })
	  }
	  
    },
	// 确认导出
    exportQr() {
      this.exportClick();
      this.isExportShow = false;
    },
    eyeLoock(row,messageId) {
	 uni.setStorageSync("rowInfo",row);
      wx.navigateTo({
        url: `/pages/reportInfo/reportInfo?messageId=${messageId}`,
      });
    },
    //取消选择时间
    closeTime() {
	this.queryList = {
	  keywords: '',
	  alarmType: '',
	  alarmContent: '',
	  beginTime: '',
	  endTime: '',
	  status: '',
	  offset: 1,
	  limit: 20,
	  sort: '',
	  order: '',
	};
	this.statusInfo = "筛选状态";
	this.time = "筛选时间";
	this.startTimeShow = false;
    },
    //确定选择结束时间
    async confirmEndTime(e) {
	  this.queryList.offset = 1;
      this.queryList.endTime = await this.shijianc(e.value);
      this.isTimeZ = await this.yueFen(e.value);
      this.time = `${this.isTimeQ}${this.isTimeZ}`;
      this.endTimeShow = false;
      this.getAlarmList(false);
    },
    //确定选择开始时间
    async confirmTime(e) {
      this.queryList.beginTime = await this.shijianc(e.value);
      this.isTimeQ = await this.yueFen(e.value);
      this.startTimeShow = false;
      this.endTimeShow = true;
    },
    shijianc(time) {
      let date = new Date(time);
      let Y = date.getFullYear() + "-";
      let M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      let D =
        (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
      let h =
        (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      let m =
        (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
        ":";
      let s =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return Y + M + D + h + m + s;
    },
    yueFen(time) {
      let date = new Date(time);
      let M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      let D =
        (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
      return M + D;
    },
    //格式化时间
    formatter(type, value) {
      if (type === "year") {
        return `${value}年`;
      }
      if (type === "month") {
        return `${value}月`;
      }
      if (type === "day") {
        return `${value}日`;
      }
      return value;
    },

    async checkphone() {
      //有电话就去验证
      if (this.phone) {
        const res = await verifyPhone(this.phone);
        if (res === "用户未注册") {
          wx.reLaunch({
            url: "/pages/register/register",
          });
        } else {
          uni.setStorageSync("registerPhone", this.phone);
          getUserProfile();
        }
      } else {
        //没有电话就弹出授权
         this.popShow = true;
      }
    },
		closePop() {
			this.popShow = false;
		},
		//上拉加载
		async getLoadingList() {
		  if (this.nothingMore) return;
		  this.queryList.offset += 1;
		  this.loading = true;
		  await this.getAlarmList(true);
		  this.loading = false;
		}
  },
};
</script>

<style scoped lang="scss">
.list {
  box-sizing: border-box;
	padding: 20rpx;
  padding-bottom: 180rpx;
	.popup {
		.title {
			font-size: 36rpx;
			color: #000;
			font-weight: 600;
			margin-bottom: 32rpx;
			text-align: center;
		}
		.content {
			font-size: 32rpx;
			color: #000;
			margin-bottom: 42rpx;
			text-align: center;
		}
		.footer {
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			align-items: flex-end;
			.allow {
				color: rgba(197, 0, 10, 1);
				height: 68rpx;
				padding: 16px 19px;
				line-height: 0;
				border: 1rpx solid rgba(197, 0, 10, 1);
				margin: 0 40rpx;
			}
			.refuse {
				color: rgba(142, 142, 142, 1.0);
				border: 1rpx solid rgba(142, 142, 142, 1.0);
				background-color: transparent;
			}
		}
	}
  .list-top {
    border-radius: 20rpx;
    padding: 20rpx 20rpx 5rpx;
    background-color: #fff;
  }
  .list-content {
    border-radius: 20rpx;
    margin-top: 20rpx;
    padding: 20rpx;
    background-color: #fff;
  }
  .tab-th {
    margin-top: 16rpx;
    margin-bottom: 10rpx;
    display: flex;
    .dressingTime {
      width: 260rpx;
      height: 72rpx;
      background-color: #f0f0f0;
      text-align: center;
      line-height: 72rpx;
      color: #837d7d;
      border-radius: 72rpx;
    }
    .dressingStatusInfo {
      margin-left: 30rpx;
      width: 260rpx;
      height: 72rpx;
      background-color: #f0f0f0;
      text-align: center;
      line-height: 72rpx;
      color: #837d7d;
      border-radius: 72rpx;
    }
    .icon {
      margin-left: 30rpx;
      width: 160rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .close-circle {
        width: 55rpx;
        height: 55rpx;
        background: url(@/static/checkIcon/cancel-all.png) no-repeat;
        background-size: contain;
      }
      .share-square {
        width: 55rpx;
        height: 55rpx;
        background: url(@/static/listIcon/export.png) no-repeat;
        background-size: contain;
      }
    }
  }
}
/deep/.u-input__content {
  background-color: #f0f0f0;
  border-radius: 10rpx;
  height: 80rpx;
}
.list-content-top {
	height: 80rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	.list-content-info {
		font-weight: 500;
	}
}
.list-content-center-info {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 80rpx;
		margin-bottom: 20rpx;
	}
	.error-report {
		width: 150rpx;
		height: 50rpx;
		color: #fff;
		line-height: 50rpx;
		text-align: center;
		border-radius: 20rpx;
		font-size: 22rpx;
	}
	.error-report-red {
		background-color: red;
		width: 110rpx;
	}
	.error-report-orange {
		width: 100rpx;
		border-radius: 10rpx !important;
		background-color: orange;
	}
</style>

<style lang="scss">
.list {
	.u-popup__content {
	  padding: 30rpx 40rpx;
	}
}
</style>
