<template>
  <view>
    <u-sticky>
      <view style="background-color: #fff">
        <u-subsection
          v-if="!isEnergyRole"
          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">
          <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.handoverAddressName }}</view
          >
        </view>
        <view class="line">
          <view class="text-small"
            >还车地点: {{ item.returnLocationName }}</view
          >
        </view>
        <view class="line" style="justify-content: space-between">
          <view class="text-small left"
            >还车时间: {{ formatDateTime(item.returnDate) }}</view
          >
          <view class="text-small">车牌号: {{ item.plateNumber }}</view>
        </view>
        <view class="buttons">
          <!--deliveryPermit为1的时候准许交车  -->
          <button
            @tap="goto"
            v-if="
              item.taskStatus == 0 &&
              editButton &&
              current == 0 &&
              [null, 1].includes(item.vehicleArrival)
            "
            :data-url="`/pages/returnCar/detail?id=${item.id}`"
          >
            编辑
            <!-- item.taskStatus == 0 && //未提交编辑
              isServiceDep && //是运维
              current === 0 && //菜单是待还车
              item.vehicleArrival === 1 //已到达 -->
          </button>
          <button
            v-if="
              current === 0 && isOutServiceRole && item.vehicleArrival === 0
            "
            @tap="reachCar(item.id)"
          >
            <!-- :disabled="![1, 2].includes(item.safetyAuditStatus)" -->

            车辆到达
          </button>
          <button
            v-if="
              isOutServiceRole &&
              item.returnLocationType === 2 &&
              item.taskStatus === 1
            "
            @tap="parkingFunc(item.id)"
          >
            <!-- :disabled="![1, 2].includes(item.safetyAuditStatus)" -->

            停车场
          </button>
          <!-- <button
            @tap="goto"
            v-if="
              !(
                (isBussinessDep && current === 1) ||
                (isServiceDep && current === 0) ||
                (isFinanceDep && current === 1)
              )
            "
            :data-url="`/pages/returnCar/cost?id=${item.id}`"
          >
            费用核算
          </button>
          <button
            v-if="
              current === 1 &&
              isFinanceDep &&
              item.returnCostApprovalStatus != 30
            "
            @tap="goto"
            :data-url="`/pages/returnCar/cost?id=${item.id}`"
          >
            费用结算
          </button> -->
          <!-- :data-url="
              isCostUser || (isServiceDep && current == 1)
                ? `/pages/returnCar/cost?id=${item.id}&isRead=1`
                : `/pages/returnCar/detail?id=${item.id}&isRead=1`
            " -->
          <button
            @tap="goto"
            :data-url="`/pages/returnCar/detail?id=${item.id}&isRead=1`"
          >
            查看
          </button>
        </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>
    <u-modal
      :show="showParkingModal"
      @confirm="confirmModal"
      @cancel="cancelModal"
      :showCancelButton="true"
      buttonReverse
      :asyncClose="true"
    >
      <view class="slot-content testClass">
        <view class="item">
          <view class="title">停车场确认</view>
          <u-picker
            :show="showParkingPicker"
            :columns="[parkingList]"
            keyName="dicName"
            :immediateChange="true"
            @confirm="confirmPark"
            @cancel="showParkingPicker = false"
          >
          </u-picker>
          <u--input
            border="surround"
            disabled
            fontSize="26"
            placeholder="请选择停车场"
            :value="getParkingName(parking)"
            @tap="showParkingPicker = true"
          >
          </u--input>
        </view>
      </view>
    </u-modal>
  </view>
</template>

<script>
import { getUser } from "@/utils/auth.js";
import stora from "@/utils/storage";
import { checkButtonPermission } from "@/utils/permission.js";
export default {
  options: {
    styleIsolation: "shared", // 解除样式隔离
  },
  data() {
    return {
      current: 0,
      list: ["待还车", "全部"],
      currRowId: "",
      queryPage: {
        pageNo: 1, // 页码
        pageSize: 10, //每页查询条数
        total: 0, //总页数
        pages: -1, //总页数
        taskStatus: "0", // 编辑完成 0 表示待编辑 1 表示编辑完成
        // deliveryPermits: ['1']	// 交车许可 1表示 准许交车
      },
      dataList: [],
      pageNo: 1,
      userInfo: {},
      noMoreData: false,
      loading: false,
      showParkingPicker: false,
      showParkingModal: false,
      parking: "",
      parkingList: [],
      keyword: "", //搜索关键字
      pageCode: "carapplicationForDelivery", //页面编码
      //   banPlateNumber: [工单#7045017 工单 1023 标红车辆车辆车牌号恢复为黑色
      //     "粤AGP7018",
      //     "粤AGR6879",
      //     "粤AGR9815",
      //     "粤AGP9825",
      //     "粤AGP6639",
      //     "粤AGP5158",
      //     "粤AGP6651",
      //     "粤AGP9331",
      //     "粤AGP9786",
      //     "粤AGR9866",
      //     "粤AGR8500",
      //     "粤AGR9877",
      //     "粤AGR5547",
      //     "粤AGR8531",
      //     "粤AGQ0119",
      //   ],
    };
  },
  computed: {
    editButton: function () {
      return checkButtonPermission(
        "carapplicationForDeliveryEdit",
        this.pageCode
      );
    },
    isCostUser() {
      return this.isEnergyRole || this.isBussinessDep || this.isFinanceDep;
    },
    isOutServiceRole() {
      const ids = this.userInfo?.roles?.map((item) => item.id) || [];
      if (ids.includes("202306091251370002")) {
        console.log("运维外勤");
        return true; //运维外勤
      } else {
        return false; //其他
      }
    },
    isServiceDep() {
      //const ids = this.userInfo?.roles?.map((item) => item.id) || [];
      if (this.userInfo.depCode === "0601") {
        console.log("运维部");
        return true; //运维部
      } else {
        return false; //其他
      }
    },
    isEnergyRole() {
      //const ids = this.userInfo?.roles?.map((item) => item.id) || [];
      if (this.userInfo.depCode === "0502") {
        console.log("能源部");
        return true; //
      } else {
        return false; //其他
      }
    },
    isFinanceDep() {
      //const ids = this.userInfo?.roles?.map((item) => item.id) || [];
      if (this.userInfo.depCode === "02") {
        console.log("财务部");
        return true; //财务部
      } else {
        return false; //其他
      }
    },
    isBussinessDep() {
      console.log(this.userInfo);
      if (this.userInfo.depCode === "0501") {
        console.log("业务服务组-业务助理");
        return true; //业务服务组-业务助理
      } else {
        return false; //其他
      }
      //   const ids = this.userInfo?.roles?.map((item) => item.id) || [];
      //   if (ids.includes("1066262176854999040")) {
    },
  },
  onLoad() {
    this.userInfo = getUser() || {};
    // this.$nextTick(() => {
    //   if (this.isBussinessDep) {
    //     this.list = ["费用核算", "已提交"];
    //   } else if (this.isFinanceDep) {
    //     this.list = ["费用核算", "费用结算"];
    //   }
    // });
  },
  methods: {
    async getParkList() {
      await this.$api.returnCar
        .getParkingPageList({
          pageNo: 1,
          pageSize: 999,
        })
        .then((res) => {
          if (res) {
            let datas = res?.data;
            this.parkingList = datas.records.map((item) => {
              return {
                dicCode: item.id,
                dicName: item.parkingName,
              };
            });
          }
        });
    },
    cancelModal() {
      this.parking = "";
      this.currRowId = "";
      this.showParkingModal = false;
    },
    getDicValue(dic, dicCode) {
      if (dic.length == 0) {
        return "";
      }

      return dic.find((x) => x.dicCode == dicCode)?.dicName ?? "";
    },
    async parkingFunc(val) {
      this.currRowId = val;
      this.parking = "";
      await this.getParkList();
      this.showParkingModal = true;
    },
    confirmModal() {
      if (!this.parking) {
        uni.showToast({
          title: "停车场不能为空",
          icon: "none",
          duration: 1500,
        });
        this.showParkingModal = false;
        return;
      }
      const _this = this;
      this.$api.returnCar
        .updateParking({
          id: this.currRowId,
          returnLocation: this.parking,
          returnLocationType: 1,
        })
        .then((res) => {
          if (res) {
            uni.showToast({
              title: "操作成功",
              icon: "success",
              duration: 1500,
              success() {
                _this.sectionChange(_this.current);
              },
            });
          }
        });
      this.showParkingModal = false;
    },
    confirmPark(e) {
      console.log(e);
      this.parking = e.value[0].dicCode;
      this.showParkingPicker = false;
    },
    getParkingName(dicCode) {
      console.log(dicCode);
      return this.getDicValue(this.parkingList, dicCode);
    },
    // 新增的搜索方法
    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 (index == 1) {
        this.queryPage.vehicleArrival = "";
        this.queryPage.taskStatus = "1";
        if (this.isServiceDep) {
          this.queryPage.vehicleArrival = "1"; // 已到车
        }
        // if (this.isBussinessDep || this.isFinanceDep) {
        //   this.queryPage.vehicleArrival = "1";
        //   this.queryPage.returnCostApprovalStatus = [10, 30]; // 已大提交
        // }
      } else {
        // 仅显示待还车
        this.queryPage.vehicleArrival = "";
        this.queryPage.taskStatus = "0";
        // if (this.isBussinessDep || this.isEnergyRole || this.isFinanceDep) {
        //   this.queryPage.vehicleArrival = "1"; // 已到车
        //   this.queryPage.taskStatus = "1";
        //   this.queryPage.returnCostApprovalStatus = [0, 40]; //未大提交
        // }
        //偷懒写法
        // if (this.isBussinessDep) {
        //   this.queryPage.vehicleArrival = "0";
        // }
      }

      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;
      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;
        });
    },
    goto(e) {
      uni.navigateTo({ url: e.target.dataset.url });
    },
    reachCar(id) {
      const _this = this;
      uni.showModal({
        title: "提示",
        content: "确认到达?",
        success: (res) => {
          if (res.confirm) {
            this.$api.returnCar.sureReturn({ id }).then((res) => {
              if (res) {
                uni.showToast({
                  title: "操作成功",
                  icon: "success",
                  duration: 1500,
                  success() {
                    _this.sectionChange(_this.current);
                  },
                });
              }
            });
          }
        },
      });
    },
  },

  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-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/ .testClass {
  width: 80%;
}
.item {
  .title {
    font-size: 26rpx;
    margin-bottom: 15rpx;

    &.required::before {
      content: "*";
      color: red;
      margin-right: 3rpx;
    }
  }
}
.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>
