<template>
  <view>
    <u-sticky>
      <u-button text="新增" @click="addFailuer"></u-button>
      <!-- <u-search placeholder="请输入车牌号" v-model="keyword" :showAction="false" @search="searchList()"></u-search> -->
      <view style="background-color: #fff">
        <u-subsection
          mode="subsection"
          :list="list"
          :current="current"
          @change="sectionChange"
          activeColor="#7ba746"
          :fontSize="30"
        >
        </u-subsection>
      </view>

      <u-search
        placeholder="请输入"
        v-model="keyword"
        :showAction="false"
        @search="searchList()"
      ></u-search>
    </u-sticky>

    <view class="list">
      <view class="item" v-for="item in dataList" :key="item.id">
        <view
          class="line"
          v-if="item.approvalStatus == 10 && item.isSubmit != 0"
        >
          <u-badge :isDot="true" type="warning"></u-badge>
          <view class="text-normal">待审批</view>
        </view>
        <view class="line" v-else-if="item.approvalStatus === 0">
          <u-badge :isDot="true" type="warning"></u-badge>
          <view class="text-normal">待提交</view>
        </view>
        <view class="line" v-else-if="item.approvalStatus == 40">
          <u-badge :isDot="true" type="error"></u-badge>
          <view class="text-normal">驳回</view>
        </view>
        <view class="line" v-else-if="item.approvalStatus === 60">
          <u-badge :isDot="true" type="warning"></u-badge>
          <view class="text-normal">异动超时</view>
        </view>
        <view class="line" v-else-if="item.approvalStatus == 99">
          <u-badge :isDot="true" type="info"></u-badge>
          <view class="text-normal">已撤销</view>
        </view>
        <view class="line" v-else-if="item.approvalStatus == 30">
          <u-badge :isDot="true" type="error"></u-badge>
          <view class="text-normal">进行中</view>
        </view>
        <view class="line" v-else-if="item.approvalStatus == 50">
          <u-badge :isDot="true" type="success"></u-badge>
          <view class="text-normal">异动完成</view>
        </view>
        <!-- <view class="line" v-else-if="item.approvalStatus == 30">
          <u-badge
            :isDot="true"
            :type="item.transactionStatus === 2 ? 'success' : 'error'"
          ></u-badge>
          <view class="text-normal">{{
            item.transactionStatus === 2 ? "异动完成" : "进行中"
          }}</view>
        </view> -->
        <view class="line">
          <view class="text-small">车牌号: {{ item.plateNumber || "" }}</view>
        </view>
        <view class="line">
          <view class="text-small">申请人: {{ item.applyUserName || "" }}</view>
        </view>
        <view
          class="line"
          v-if="![0, 10].includes(item.approvalStatus) && item.approvalName"
        >
          <view class="text-small">审批人: {{ item.approvalName || "" }}</view>
        </view>
        <view class="line">
          <view class="text-small"
            >开始时间:
            {{ formatDateTime(item.transactionStartTime, "minute") }}</view
          >
        </view>
        <view class="line">
          <view class="text-small"
            >异动目的地: {{ item.transactionAddressName || "" }}</view
          >
        </view>
        <!-- <view class="line">
          <view class="text-small"
            >结束时间: {{ formatDateTime(item.approvalTime, "minute") }}</view
          >
        </view> -->
        <view class="buttons">
          <button
            @tap="goto"
            :data-url="`/pages/unusualActionApply/detail?id=${item.id}`"
            v-if="editButton && [0, 30, 40, 60].includes(item.approvalStatus)"
          >
            <!-- 25.2.24 注释&&
              ![2, 3].includes(item.transactionStatus) 
               2现为approvalStatus50 3为99
               去除异动状态，沿用审批状态字段当做异动状态显示 仅在前端显示为异动
              -->
            <!-- 
             item.applyUserId === userId 编辑按钮不跟申请人挂钩，跟外勤挂钩
            [30, 40].includes(item.approvalStatus) 30通过 40驳回  
          [2, 3].includes(item.transactionStatus) 2异动完成 3撤销 -->
            编辑
          </button>
          <button
            @tap="goto"
            :data-url="`/pages/unusualActionApply/detail?id=${item.id}&isAudit=1`"
            v-if="item.approvalStatus === 10 && auditButton"
          >
            审批
          </button>
          <button
            @tap="goto"
            :data-url="`/pages/unusualActionApply/detail?id=${item.id}&isRead=1`"
          >
            查看
          </button>
          <button
            @tap="cancelApply(item.id)"
            v-if="
              item.applyUserId == userId &&
              ![50, 99].includes(item.approvalStatus)
            "
          >
            撤销
          </button>
          <!-- 25.2.24 注释 ![2, 3].includes(item.transactionStatus) &&
                item.approvalStatus !== 99
               2现为approvalStatus50 3为99
               去除异动状态，沿用审批状态字段当做异动状态显示 仅在前端显示为异动
              -->
        </view>
      </view>
      <view class="no-more" v-if="noMoreData">没有更多数据了</view>
    </view>
    <u-loading-page
      bg-color="#ffffff"
      :loading="loading"
      color="#7ba746"
      font-size="24"
    ></u-loading-page>
  </view>
</template>

<script>
import { getUser } from "@/utils/auth.js";
import { checkButtonPermission } from "@/utils/permission.js";
export default {
  options: {
    styleIsolation: "shared", // 解除样式隔离
  },
  data() {
    return {
      keyword: "",
      userId: null,
      current: 0,
      list: ["审批通过", "待审批"],
      queryPage: {
        pageNo: 1, // 页码
        pageSize: 10, // 每页查询条数
        total: 0, // 总页数
        pages: -1, // 总页数
        approvalStatusList: [30, 50, 60], // 审批状态集合
        wxOrder: 2,
      },
      dataList: [],
      pageNo: 1,
      noMoreData: false,
      loading: false,
      pageCode: "transactionManagement",
    };
  },
  computed: {
    auditButton: function () {
      console.log(checkButtonPermission("transactionAudit", this.pageCode));
      return checkButtonPermission("transactionAudit", this.pageCode);
    },
    editButton: function () {
      return checkButtonPermission("transactionEdit", this.pageCode);
    },
  },
  methods: {
    // 新增的搜索方法
    searchList() {
      this.queryPage.plateNumber = this.keyword.trim(); // 设置车牌号条件
      this.queryPage.pageNo = 1; // 重置页码为1
      this.dataList = []; // 清空数据列表
      this.noMoreData = false; // 重置没有更多数据的标志
      this.loadmore(); // 重新加载数据
    },
    sectionChange(index) {
      console.log(index);
      this.current = index;
      this.queryPage.plateNumber = undefined; // 清空搜索关键字
      this.keyword = ""; // 清空搜索关键字
      if (index == 1) {
        this.queryPage.approvalStatusList = [0, 10, 40, 99]; // 待提交，待审批，审批不通过，已撤销
        this.queryPage.wxOrder = 1;
      } else {
        this.queryPage.approvalStatusList = [30, 50, 60]; //审批通过  60过期
        this.queryPage.wxOrder = 2;
      }

      this.queryPage.pageNo = 1;
      this.dataList = [];
      this.loadmore();
    },
    formatDateTime(obj, type = "data") {
      if (obj == null) {
        return "";
      }

      const date = new Date(obj);
      if (type === "date") {
        let y = 1900 + date.getYear();
        let m = "0" + (date.getMonth() + 1);
        let d = "0" + date.getDate();
        return (
          y +
          "-" +
          m.substring(m.length - 2, m.length) +
          "-" +
          d.substring(d.length - 2, d.length)
        );
      } else if (type === "minute") {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始
        const day = String(date.getDate()).padStart(2, "0");
        const hour = String(date.getHours()).padStart(2, "0");
        const minute = String(date.getMinutes()).padStart(2, "0");
        return `${year}-${month}-${day} ${hour}:${minute}`;
      }
    },
    loadmore() {
      this.loading = true;
      this.$api.unusualActionApply
        .queryPageList(this.queryPage)
        .then((res) => {
          console.log(res);
          this.queryPage.pageNo = res.data?.current;
          this.queryPage.pages = res.data?.pages;
          this.queryPage.total = res.data?.total;
          this.dataList.push(...(res.data?.records || []));
          this.loading = false;
        })
        .catch((errors) => {
          this.loading = false;
        });
    },
    onPullDownRefresh() {
      this.sectionChange(this.current);
      uni.stopPullDownRefresh(); //刷新数据之后停止刷新效果
    },
    // formatPlateNumber(plateNumbers) {
    //   if (!plateNumbers) return ""; // 如果为空，返回空字符串
    //   const plates = plateNumbers.split(","); // 将字符串按逗号分隔成数组
    //   if (plates.length > 1) {
    //     return `${plates[0]}...`; // 如果有多个车牌号，返回第一个加上“...”
    //   }
    //   return plates[0]; // 如果只有一个车牌号，直接返回
    // },
    goto(e) {
      uni.navigateTo({ url: e.target.dataset.url });
    },
    cancelApply(id) {
      uni.showModal({
        title: "提示",
        content: "是否撤销本次异动申请?",
        success: (res) => {
          if (res.confirm) {
            this.cancelApplyApi(id);
          }
        },
      });
    },
    //撤销异动申请
    cancelApplyApi(id) {
      if (id) {
        this.$api.unusualActionApply.revokeTransaction({ id }).then((res) => {
          if (res) {
            uni.showToast({
              title: "撤销成功",
              icon: "success",
              duration: 1500,
              success: () => {
                this.sectionChange(this.current);
              },
            });
          }
        });
      }
    },
    addFailuer() {
      uni.navigateTo({ url: `/pages/unusualActionApply/detail` });
    },
  },
  onLoad() {
    this.userInfo = getUser() || {};
    this.userId = this.userInfo.id;
    console.log("userId type:", typeof this.userId);
  },
  onPullDownRefresh() {
    this.queryPage.pageNo = 1;
    this.dataList = [];
    this.loadmore();
    uni.stopPullDownRefresh(); //刷新数据之后停止刷新效果
  },
  onReachBottom() {
    console.log("触底了");
    //当前页数小于总页数
    if (this.queryPage.pageNo < this.queryPage.pages) {
      this.queryPage.pageNo++;
      this.loadmore();
    } else {
      this.noMoreData = true;
      console.log("没有更多数据了");
    }
  },
  onShow() {
    this.queryPage.pageNo = 1;
    this.dataList = [];
    this.loadmore();
  },
};
</script>

<style lang="less" scoped>
/deep/ .u-search {
  background: #d7d7d7 !important;
  padding: 20rpx 10rpx !important;
}
// /deep/ .u-search__content__input {
//   height: 50rpx !important;
//   padding-top: 20rpx !important; /* 上边距 */
//   padding-bottom: 20rpx !important; /* 下边距 */
// }
/deep/ .u-icon__icon {
  font-size: 26rpx !important;
}

/deep/ .u-badge--error {
  background-color: red !important;
}
/deep/ .u-badge--success {
  background-color: #4cd964 !important;
}

/deep/ .u-badge--dot {
  height: 20rpx !important;
  width: 20rpx !important;
}

.list {
  background: #d7d7d7;
  padding: 0 20px 20rpx;

  .item {
    background: white;
    width: calc(100% - 40rpx);
    padding: 20rpx;
    margin-bottom: 20rpx;
    position: relative;
    border-radius: 15rpx;

    .line {
      display: flex;
      align-items: center;
      margin-bottom: 15rpx;

      .left {
        margin-right: 50rpx;
        width: 300rpx;
      }

      .text-small {
        font-size: x-small;
      }

      .text-normal {
        margin-left: 20rpx;
        font-size: small;
      }
    }

    .buttons {
      position: absolute;
      top: 20rpx;
      right: 20rpx;

      button {
        width: 130rpx;
        height: 50rpx;
        padding: 12rpx 0;
        font-size: 26rpx;
        line-height: 26rpx;
        margin-bottom: 10rpx;
      }
    }
  }

  .no-more {
    width: 100%;
    text-align: center;
    font-size: xx-small;
    color: white;
  }
}
</style>
