//列表页
<template>
  <view class="list">
    <TabBar></TabBar>
    <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="checkmark-circle" @click="pass('通过')"></text>
          <text class="close-circle" @click="pass('拒绝')"></text>
          <text class="share-square" @click="isExportShow = true"></text>
        </view>
      </view>
    </view>
    <view class="list-content">
      <view class="table" v-for="(item, index) in list" :key="index">
        <view class="table-checkbox">
          <u-checkbox-group >
            <u-checkbox
			 :checked="item.value"
              @change="checkboxChange(item)"
              shape="circle"
            ></u-checkbox>
          </u-checkbox-group>
        </view>
        <view class="table-item" @click="checkboxChange(item)">
          <view class="table-item-top">
            <view class="table-name"> {{ item.visitorName }} </view>
            <view class="table-number">{{ item.applyNo }} </view>
          </view>
          <view class="table-item-buttom">
            <view class="table-time"> {{ item.inTime }} </view>
          </view>
        </view>
        <view :class="item.color"> {{ item.status }} </view>
        <view class="table-icon">
          <view class="icon-info" @click="eyeLoock(item.applyNo)"></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">
          确认将{{ checkExport }}访客表单导出吗？
        </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="ispassShow"
      mode="bottom"
      :round="10"
      :closeOnClickOverlay="false"
      @close="close"
    >
      <view class="popup">
				<view class="title">提示</view>
        <view class="content"> 确定要将{{ text }}的{{ leixin }}? </view>
        <view class="footer">
					<button class="allow refuse" @click="ispassShow = false"> 取消</button>
					<button class="allow" @click="possQr"> 确认</button>
        </view>
      </view>
    </u-popup>
		
    <u-datetime-picker
      :show="startTimeShow"
      mode="datetime"
      title="请选择开始时间"
	  v-model="startTimeDefult"
      :formatter="formatter"
      @cancel="closeTime"
      @confirm="confirmTime"
    >
    </u-datetime-picker>
		
    <u-datetime-picker
      :show="endTimeShow"
      mode="datetime"
      title="请选择结束时间"
      :formatter="formatter"
	  v-model="endTimeDefult"
      @cancel="closeTime"
      @confirm="confirmEndTime"
    >
    </u-datetime-picker>
    <u-action-sheet
      :show="statusShow"
      :actions="statusList"
      title="请选择状态"
      description="只能单选"
      @close="statusShow = false"
      @select="statusSelect"
    >
    </u-action-sheet>

    <!-- 获取手机号popup组件 -->
    <GetPhonePopup :popShow="popShow" @closePop="closePop"/>
		<LoadingList :loading="loading" :nothingMore="nothingMore" />
		
		<!-- 返回顶部 -->
		<u-back-top 
			:scroll-top="scrollTop" 
			icon="arrow-up" 
			duration="200"
		></u-back-top>
  </view>
</template>

<script>
import TabBar from "@/components/tabBar/tabBar.vue";
import { getList } from "@/api/list.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 GetPhonePopup from "@/components/base/getphonePopup.vue"
import BASE_URL from "@/api/base.js";
import LoadingList from '@/components/base/LoadingList.vue';
export default {
  components: {
    TabBar, GetPhonePopup, LoadingList
  },
  data() {
    return {
			scrollTop: 0,
      queryList: {
        keywords: "",
        startTime: "",
        endTime: "",
        status: "",
		offset: this.offset,
		limit: this.limit
      },
	  startTimeDefult:Number(new Date()),
	  endTimeDefult:Number(new Date()),
      list: [],
      isExportShow: false,
      ispassShow: false,
      leixin: "",
      text: "已通过",
      checkboxList: [],
      checkExport: "所有",
      startTimeShow: false,
      endTimeShow: false,
      TimeNextShow: false,
      statusShow: false,
      statusList: [
        { name: "申请已提交", id: "1" },
        { name: "申请已通过", id: "2" },
        { name: "申请已失败", id: "3" },
      ],
      time: "筛选时间",
      isTimeQ: "",
      isTimeZ: "",
      statusInfo: "筛选状态",
      popShow: false, //控制授权手机号弹出框
			offset: 1,   //页数
			limit: 10,   //一页几条数据
			nothingMore: false, //上拉加载-没有数据了
			loading: false, //是否显示上拉加载-加载中
    };
  },
  mounted() {
  	uni.showShareMenu({
  		withShareTicket: true,
  		menus: ["shareAppMessage"]
  	});
  },
  //分享好友
  onShareAppMessage() {
  	return {
  		title: '环市东院区安防小程序',
  		imageUrl: '../../static/share.jpg',
  	};
  },
	// 监听滚动条位置
	onPageScroll(e) {
		this.scrollTop = e.scrollTop;
	},
	async onShow() {
		this.offset = 1;
    let pages = getCurrentPages();
    const curPage = pages[pages.length - 1];
    this.currentPagePath = curPage.route;
    uni.setStorageSync("currentPagePath", this.currentPagePath);

    //验证手机号
    this.phone = uni.getStorageSync("registerPhone");
    this.checkphone();
		
		
    this.queryList = {
      keywords: "",
      startTime: "",
      endTime: "",
      status: "",
			offset: this.offset,
			limit: this.limit
    };
		const param = {
			offset: 1,
			limit: this.limit
		}
		this.nothingMore = false;
    const res = await getList(param);
    this.list = res.records.map((item) => {
		item.value = false
      if (item.visitorApplyStatus == "1") {
        item.status = "申请已提交";
        item.color = "blue";
      } else if (item.visitorApplyStatus == "2") {
        item.status = "申请已通过";
        item.color = "green";
      } else {
        item.status = "申请未通过";
        item.color = "red";
      }
      return item;
    });
  },
  //下拉刷新
  onPullDownRefresh() {
		this.offset = 1;
    this.queryList = {
      keywords: "",
      startTime: "",
      endTime: "",
      status: "",
	  offset: this.offset,
	  limit: this.limit
    };
    this.statusInfo = "筛选状态";
    this.time = "筛选时间";
    this.searchList(false).then(() => {
			uni.stopPullDownRefresh(); 
		});
    this.checkboxList = [];
    this.checkExport = "所有";
  },
	//上滑加载
	onReachBottom() {
		this.getLoadingList();
	},
  methods: {
    //选中的数据
    checkboxChange(item) {
		item.value = !item.value
      if (this.checkboxList.indexOf(item) == -1) {
        this.checkboxList.push(item);
      } else {
        this.checkboxList.splice(this.checkboxList.indexOf(item), 1);
      }
      this.checkExport = this.checkboxList.length > 0 ? "选中的" : "所有";
    },
    //搜索框发生改变
    async change(e) {
			this.offset = 1;
      if (e.trim() === "") {
				const param = {
					offset: this.offset,
					limit: this.limit
				}
        const res = await getList(param);
        return (this.list = res.records.map((item) => {
          if (item.visitorApplyStatus == "1") {
            item.status = "申请已提交";
            item.color = "blue";
          } else if (item.visitorApplyStatus == "2") {
            item.status = "申请已通过";
            item.color = "green";
          } else {
            item.status = "申请未通过";
            item.color = "red";
          }
          return item;
        }));
      }
      debounce(this.searchList(false), 10000);
    },
    //确定导出
    async exportClick() {
      const sessionId = uni.getStorageSync("sessionId");
      let filePath = `${wx.env.USER_DATA_PATH}/${+new Date()}.xlsx`;
      let ids = "";
      ids =
        this.checkboxList.length === 0
          ? this.list.map((item) => item.id).join()
          : this.checkboxList.map((item) => item.id).join();
      uni.request({
        url: `https://visitor.gd.smartlog.work/visitor/exportMessage?ids=${ids}`,
        responseType: "arraybuffer",
        header: {
          token: sessionId, //自定义请求头信息
        },
        success: ({ data }) => {
          let fm = wx.getFileSystemManager();
          fm.writeFile({
            filePath,
            data,
            success: (res) => {
              uni.openDocument({
                filePath,
                fileType: "xlsx",
                showMenu: true,
              });
            },
          });
        },
      });
      this.checkboxList = [];
    },
    //根据条件搜索
    async searchList(is) {
			if(!this.loading) {
				this.list = [];
			}
			if(!is) {
				this.offset = 1
			}
			this.queryList.offset = this.offset;
      const res = await getList(this.queryList);
			if(res.records && res.records.length) {
				this.nothingMore = false;
				const resData = res.records.map((item) => {
				  if (item.visitorApplyStatus == "1") {
				    item.status = "申请已提交";
				    item.color = "blue";
				  } else if (item.visitorApplyStatus == "2") {
				    item.status = "申请已通过";
				    item.color = "green";
				  } else {
				    item.status = "申请未通过";
				    item.color = "red";
				  }
				  return item;
				});
				this.list = this.list.concat(resData);
			} else {
				this.nothingMore = true;
			}
    },
    //选中状态
    statusSelect(e) {
			this.offset = 1;
      this.statusInfo = e.name;
      this.queryList.status = e.id;
      this.searchList(false);
    },
    //打开导出提示框
    pass(leixin) {
      this.leixin = leixin;
      this.text = this.checkboxList.length !== 0 ? "选中的" : "所有";
      this.ispassShow = true;
    },
    async possQr() {
	  const statusList = this.checkboxList.length === 0 ? this.list.filter((item) => item.visitorApplyStatus === '1') : this.checkboxList.filter((item) => item.visitorApplyStatus === '1')
	  let ids = statusList.map((item) => item.id).join();
	  if( ids === '') {
		  this.checkboxList = [];
		  this.ispassShow = false;
		  this.searchList(false);
		  return uni.showToast({
				title: `暂无需要改动状态人员`,
				icon: 'none',
				duration: 2000,
			})
	  }
      let res = await solveStatus(this.leixin == "通过" ? "2" : "3", ids);
      this.searchList(false);
      this.ispassShow = false;
      this.checkboxList = [];
    },
    exportQr() {
      this.exportClick();
      this.isExportShow = false;
    },
    eyeLoock(messageId) {
      wx.navigateTo({
        url: `/pages/info/info?messageId=${messageId}`,
      });
    },
    //取消选择时间
    closeTime() {
	  this.offset = 1;
      this.startTimeShow = false;
      this.time = "筛选时间";
      this.queryList = {
        keywords: "",
        startTime: "",
        endTime: "",
        status: "",
		offset: this.offset,
		limit: this.limit
      };
	  this.startTimeShow = false;
	  this.endTimeShow = false;
    },
    //确定选择结束时间
    async confirmEndTime(e) {
			this.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.searchList(false);
    },
    //确定选择开始时间
    async confirmTime(e) {
			this.offset = 1;
      this.queryList.startTime = 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.offset = this.offset + 1;
		  this.loading = true;
		  await this.searchList(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: 0 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: 210rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .close-circle {
        width: 55rpx;
        height: 55rpx;
        background: url(@/static/listIcon/noNext.png) no-repeat;
        background-size: contain;
      }
      .checkmark-circle {
        width: 55rpx;
        height: 55rpx;
        background: url(@/static/listIcon/next.png) no-repeat;
        background-size: contain;
      }
      .share-square {
        width: 55rpx;
        height: 55rpx;
        background: url(@/static/listIcon/export.png) no-repeat;
        background-size: contain;
      }
    }
  }
  .table {
    font-size: 24rpx;
    display: flex;
    align-items: center;
    font-size: 28rpx;
    .table-checkbox {
      width: 30rpx;
      height: 100rpx;
      padding: 50rpx 5rpx 3rpx 3rpx;
    }
    .table-item {
      width: 360rpx;
      margin-left: 20rpx;
      margin-right: 40rpx;
      .table-item-top {
        display: flex;
        justify-content: space-between;
        .table-name {
          font-size: 34rpx;
          font-weight: 500;
        }
        .table-number {
          font-size: 26rpx;
          color: #ccc;
        }
      }

      .table-time {
        margin-top: 10rpx;
        font-size: 26rpx;
        color: #ccc;
      }
    }

    .table-icon {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-left: 25rpx;
      padding-right: 10rpx;
      height: 150rpx;
      width: 50rpx;
      .icon-info {
        width: 55rpx;
        height: 55rpx;
        background: url(@/static/listIcon/overInfo.png) no-repeat;
        background-size: 55rpx 55rpx;
      }
    }
  }
}
/deep/.u-input__content {
  background-color: #f0f0f0;
  border-radius: 10rpx;
  height: 80rpx;
}
// .popup {
//   width: 700rpx;
//   height: 450rpx;
//   .popup-title {
//     text-align: center;
//     font-size: 36rpx;
//     margin: 35rpx;
//     margin-top: 96rpx;
//   }
//   .popup-buttom {
//     padding: 70rpx;
//     margin-top: 150rpx;
//     display: flex;
//     justify-content: space-between;
//   }
//   .popup-jujue-fanhui {
//     border: none;
//     border-radius: 8rpx;
//     background-color: gray;
//     color: #fff;
//   }
//   .popup-jujue-queren {
//     border: none;
//     border-radius: 8rpx;
//     background-color: skyblue;
//     color: #fff;
//   }
//   .popup-buttom view {
//     width: 180rpx;
//     height: 56rpx;
//     text-align: center;
//     line-height: 56rpx;
//     border-radius: 6rpx;
//     border: 1px #000 solid;
//   }
// }
.green {
  width: 240rpx;
  height: 48rpx;
  background-color: #00aa88;
  text-align: center;
  line-height: 48rpx;
  border-radius: 48rpx;
  color: #fff;
}
.blue {
  width: 240rpx;
  height: 48rpx;
  background-color: #85c2ff;
  text-align: center;
  line-height: 48rpx;
  border-radius: 48rpx;
  color: #fff;
}
.red {
  width: 240rpx;
  height: 48rpx;
  background-color: #fa5a5a;
  text-align: center;
  line-height: 48rpx;
  border-radius: 48rpx;
  color: #fff;
}
</style>

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