<template>
  <view>
    <u-sticky>
      <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.safetyAuditStatus == 1 && isSafe">
          <u-badge :isDot="true" type="warning"></u-badge>
          <view class="text-normal" style="margin-left: 20rpx">待安检</view>
        </view>
        <view class="line" v-else-if="item.safetyAuditStatus == 2 && isSafe">
          <u-badge :isDot="true" type="error"></u-badge>
          <view class="text-normal" style="margin-left: 20rpx">驳回</view>
        </view>
        <view class="line" v-else-if="item.safetyAuditStatus == 3 && isSafe">
          <u-badge :isDot="true" type="success"></u-badge>
          <view class="text-normal" style="margin-left: 20rpx">已通过</view>
        </view>
        <view class="line" v-else-if="item.safetyAuditStatus == 4 && isSafe">
          <u-badge :isDot="true" type="info"></u-badge>
          <view class="text-normal" style="margin-left: 20rpx">待审批</view>
        </view>
        <view class="line">
          <view class="text-normal">合同编号: {{ item.contractNo }}</view>
        </view>
        <view class="line">
          <view class="text-normal">项目名称: {{ item.projectName }}</view>
        </view>
        <view class="line">
          <view class="text-small">客户名称: {{ item.customerName }}</view>
        </view>
        <view class="line">
          <view class="text-small">交车区域: {{ item.deliveryAreaName }}</view>
        </view>
        <view class="line">
          <view class="text-small">交车地点: {{ item.handoverAddress }}</view>
        </view>
        <view class="line" style="justify-content: space-between">
          <view class="text-small left"
            >交车时间: {{ formatDateTime(item.handoverDate) }}</view
          >
          <view class="text-small">车牌号: {{ item.plateNumber }}</view>
        </view>
        <view class="buttons">
          <!--deliveryPermit为1的时候准许交车  -->
          <button
            @tap="goto"
            v-if="item.deliveryPermit == 1 && currSafeRole === 0 && editButton"
            :data-url="`/pages/truckRent/detail?id=${item.id}`"
          >
            编辑
          </button>

          <button
            @tap="returnCar(item.id)"
            v-if="isBussinessRole && current === 0"
          >
            <!-- :disabled="![1, 2].includes(item.safetyAuditStatus)" -->
            还车
          </button>
          <button
            @tap="cancelReturnCar(item.id)"
            v-if="isBussinessRole && current === 1"
          >
            撤销还车
          </button>
          <button
            @tap="goto"
            v-if="currSafeRole === 1 && [1, 2].includes(item.safetyAuditStatus)"
            :data-url="`/pages/truckRent/detail?id=${item.id}${
              currSafeRole !== 0 ? '&isRead=1&isSafe=1' : ''
            }`"
          >
            <!-- :disabled="![1, 2].includes(item.safetyAuditStatus)" -->
            安全检查
          </button>
          <button
            @tap="goto"
            v-if="currSafeRole === 2 && item.safetyAuditStatus === 4"
            :data-url="`/pages/truckRent/detail?id=${item.id}${
              currSafeRole !== 0 ? '&isRead=1&isSafe=1' : ''
            }`"
          >
            <!-- :disabled="item.safetyAuditStatus !== 4" -->
            安全审批
          </button>
          <button
            @tap="goto"
            :data-url="`/pages/truckRent/detail?id=${item.id}&isRead=1`"
          >
            查看
          </button>
        </view>
      </view>

      <view class="no-more" v-if="noMoreData">没有更多数据了</view>
    </view>
    <view
      clas="line"
      style="margin-top: 150rpx"
      v-if="!dataList || dataList.length === 0"
    >
      <u-empty mode="search" text="暂无数据" width="400" textSize="16">
      </u-empty
    ></view>
    <u-loading-page
      bg-color="#ffffff"
      :loading="loading"
      color="#7ba746"
      font-size="24"
    ></u-loading-page>
    <custom-modal ref="customModal" @submit="returnCarFunc" />
  </view>
</template>

<script>
import CustomModal from "./modal.vue";
import stora from "@/utils/storage";
import { checkButtonPermission } from "@/utils/permission.js";
import { getUser } from "@/utils/auth.js";
export default {
  options: {
    styleIsolation: "shared", // 解除样式隔离
  },
  components: {
    CustomModal,
  },
  data() {
    return {
      current: 0,
      userInfo: {}, // 用户信息
      list: ["待交车", "全部"],
      queryPage: {
        pageNo: 1, // 页码
        pageSize: 10, //每页查询条数
        total: 0, //总页数
        pages: -1, //总页数
        // deliveryPermits: ["1"], // 交车许可 1表示 准许交车
      },
      costDepList: [], //费用部门
      dataList: [],
      pageNo: 1,
      noMoreData: false,
      loading: false,
      keyword: "", //搜索关键字
      pageCode: "applicationForDelivery",
      currId: "",
    };
  },
  computed: {
    editButton: function () {
      return checkButtonPermission("applicationForDeliveryEdit", this.pageCode);
    },
    currSafeRole() {
      const ids = this.userInfo?.roles?.map((item) => item.id) || [];
      if (ids.includes("1076403008717209600")) {
        return 2; //安全经理
      } else if (ids.includes("1012435145369616384")) {
        return 1; //安全员
      } else {
        return 0; //其他
      }
    },
    isBussinessRole() {
      console.log(this.userInfo);
      if (this.userInfo.depCode === "0501") {
        console.log("业务服务组-业务助理");
        return true; //业务服务组-业务助理
      } else {
        return false; //其他
      }
    },
    isSafe() {
      return [1, 2].includes(this.currSafeRole);
    },
  },
  methods: {
    // 新增的搜索方法
    searchList() {
      this.queryPage.plateNumber = this.keyword.trim(); // 设置车牌号条件
      this.queryPage.pageNo = 1; // 重置页码为1
      this.dataList = []; // 清空数据列表
      this.noMoreData = false; // 重置没有更多数据的标志
      this.loadmore(); // 重新加载数据
    },
    sectionChange(index) {
      this.current = index;
      this.queryPage.plateNumber = undefined; // 清空搜索关键字
      this.keyword = ""; // 清空搜索关键字
      if ([1, 2].includes(this.currSafeRole)) {
        if (index == 1) {
          // 已通过
          this.queryPage.safetyAuditStatus = ["3"];
        } else {
          // 未通过
          this.queryPage.safetyAuditStatus = ["1", "2", "4"];
        }
      } else if (this.isBussinessRole) {
        if (index == 1) {
          console.log("业务助理-待还车");
          // 业务助理，待还车
          this.queryPage.vehicleArrival = "0";
          this.queryPage.taskStatus = "";
        } else {
          // 全部
          this.queryPage.vehicleArrival = "2";
          this.queryPage.taskStatus = "1";
        }
      } else {
        if (index == 1) {
          // 全部 （准许交车 + 已交车）
          this.queryPage.deliveryPermits = ["1", "3"];
        } else {
          // 仅显示准许交车
          this.queryPage.deliveryPermits = ["1"];
        }
      }

      this.queryPage.pageNo = 1;
      this.dataList = [];
      this.loadmore();
    },
    submitEvent() {
      this.current = 1;
      //提交后删除缓存
      stora.remove("fault_fromData");
    },
    formatDateTime(obj) {
      if (obj == null) {
        return "";
      }
      let date = new Date(obj);
      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)
      );
    },
    loadmore() {
      this.loading = true;
      if (this.isBussinessRole && this.current == 1) {
        this.$api.returnCar
          .queryTakePageList(this.queryPage)
          .then((res) => {
            console.log(res);
            this.queryPage.pageNo = res.current;
            this.queryPage.pages = res.pages;
            this.queryPage.total = res.total;
            this.dataList.push(...(res.records || []));
            this.loading = false;
          })
          .catch((errors) => {
            this.loading = false;
          });
      } else {
        this.$api.truckRent
          .queryTakePageList(this.queryPage)
          .then((res) => {
            console.log(res);
            this.queryPage.pageNo = res.current;
            this.queryPage.pages = res.pages;
            this.queryPage.total = res.total;
            this.dataList.push(...(res.records || []));
            this.loading = false;
          })
          .catch((errors) => {
            this.loading = false;
          });
      }
    },
    goto(e) {
      uni.navigateTo({ url: e.target.dataset.url });
    },
    returnCar(id) {
      this.currId = id;
      this.$refs.customModal.openModal();
    },
    returnCarFunc(isHasOkPack) {
      const _this = this;
      this.$api.returnCar
        .startReturn({ id: this.currId, hasOkPack: isHasOkPack })
        .then((res) => {
          if (res) {
            uni.showToast({
              title: "还车成功",
              icon: "success",
              duration: 1500,
              success() {
                _this.sectionChange(_this.current);
              },
            });
          }
        });
      //     const _this = this;
      //   uni.showModal({
      //     title: "提示",
      //     cancelText: "无",
      //     confirmText: "有",
      //     content: "请确认退还车辆有无无忧包?",
      //     success: (res) => {
      //       if (res.confirm) {
      //         this.$api.returnCar
      //           .startReturn({ id, hasOkPack: isHasOkPack })
      //           .then((res) => {
      //             if (res) {
      //               uni.showToast({
      //                 title: "还车成功",
      //                 icon: "success",
      //                 duration: 1500,
      //                 success() {
      //                   _this.sectionChange(_this.current);
      //                 },
      //               });
      //             }
      //           });
      //       }
      //     },
      //   });
    },

    cancelReturnCar(id) {
      const _this = this;
      uni.showModal({
        title: "提示",
        content: "确认撤销本次还车？",
        success: (res) => {
          if (res.confirm) {
            this.$api.returnCar.cancelReturn({ id }).then((res) => {
              if (res) {
                uni.showToast({
                  title: "撤销成功",
                  icon: "success",
                  duration: 1500,
                  success() {
                    _this.sectionChange(_this.current);
                  },
                });
              }
            });
          }
        },
      });
    },
    // getCostDeps() {
    //   this.$api.returnCar.getCostDeps().then((res) => {
    //     this.costDepList = res;
    //   });
    // },
  },

  onLoad() {
    // this.getCostDeps();
    this.userInfo = getUser() || {};
    console.log(this.userInfo);
    if ([1, 2].includes(this.currSafeRole)) {
      this.list = ["未通过", "已通过"]; //安全模块
    } else if (this.isBussinessRole) {
      this.list = ["全部", "待还车"]; //交还车-费用核算
    }
  },
  onPullDownRefresh() {
    this.sectionChange(this.current);
    uni.stopPullDownRefresh(); //刷新数据之后停止刷新效果
  },
  destroyed() {
    //页面销毁删除掉数据缓存
    stora.remove("fault_fromData");
  },
  onReachBottom() {
    console.log("触底了");
    //当前页数小于总页数
    if (this.queryPage.pageNo < this.queryPage.pages) {
      this.queryPage.pageNo++;
      this.loadmore();
    } else {
      this.noMoreData = true;
      console.log("没有更多数据了");
    }
  },
  onShow() {
    this.sectionChange(this.current);
  },
};
</script>

<style lang="less" scoped>
/deep/ .u-badge--success {
  background-color: #5ac725 !important;
}
/deep/ .u-badge--info {
  background-color: #fcae63 !important;
}
/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; /* 下边距 */
// }
.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 {
        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>
