<template>
  <div style="display: block !important; width: 100%; margin: 0; padding: 0">
    <!-- 使用内联样式的筛选区域 -->
    <div
      style="
        display: block !important;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        padding: 20px;
        margin-bottom: 20px;
        background-color: #fff;
      "
    >
      <div
        style="
          display: flex !important;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 15px;
        "
      >
        <h3 style="margin: 0; padding: 0; font-size: 16px">高级筛选</h3>
        <el-button type="text" @click="resetFilters">重置筛选</el-button>
      </div>

      <el-form
        :inline="true"
        :model="filterForm"
        style="display: flex !important; flex-wrap: wrap"
      >
        <!-- 日期范围筛选 -->
        <el-form-item
          label="日期范围"
          style="
            display: inline-flex !important;
            margin-right: 20px;
            margin-bottom: 18px;
          "
        >
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            @change="handleDateRangeChange"
          >
          </el-date-picker>
        </el-form-item>

        <!-- 租借类型筛选 -->
        <el-form-item
          label="租借类型"
          style="
            display: inline-flex !important;
            margin-right: 20px;
            margin-bottom: 18px;
          "
        >
          <el-select
            v-model="filterForm.mode"
            placeholder="全部"
            clearable
            @change="handleFilterChange"
          >
            <el-option label="按时租定" :value="0"></el-option>
            <el-option label="按天租定" :value="1"></el-option>
          </el-select>
        </el-form-item>

        <!-- 金额范围筛选 -->
        <el-form-item
          label="金额范围"
          style="
            display: inline-flex !important;
            margin-right: 20px;
            margin-bottom: 18px;
          "
        >
          <el-input-number
            v-model="filterForm.minAmount"
            :min="0"
            :precision="1"
            :step="10"
            placeholder="最小金额"
            @change="handleFilterChange"
          >
          </el-input-number>
          <span style="margin: 0 5px">至</span>
          <el-input-number
            v-model="filterForm.maxAmount"
            :min="0"
            :precision="1"
            :step="10"
            placeholder="最大金额"
            @change="handleFilterChange"
          >
          </el-input-number>
        </el-form-item>

        <!-- 停车场筛选 -->
        <el-form-item
          label="停车场"
          style="
            display: inline-flex !important;
            margin-right: 20px;
            margin-bottom: 18px;
          "
        >
          <el-select
            v-model="filterForm.parking_id"
            placeholder="全部停车场"
            clearable
            @change="handleFilterChange"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 搜索关键词 -->
        <el-form-item
          label="关键词"
          style="
            display: inline-flex !important;
            margin-right: 20px;
            margin-bottom: 18px;
          "
        >
          <el-input
            v-model="filterForm.keyword"
            placeholder="车牌号/用户名"
            prefix-icon="el-icon-search"
            clearable
            @input="handleFilterChange"
          >
          </el-input>
        </el-form-item>

        <!-- 订单状态筛选 -->
        <el-form-item
          label="订单状态"
          style="
            display: inline-flex !important;
            margin-right: 20px;
            margin-bottom: 18px;
          "
        >
          <el-select
            v-model="filterForm.orderStatus"
            placeholder="全部"
            clearable
            @change="handleFilterChange"
          >
            <el-option label="进行中" :value="0"></el-option>
            <el-option label="已完成" :value="1"></el-option>
            <el-option label="已取消" :value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格区域 -->
    <el-table :data="tableData" border style="width: 100%" v-loading="loading">
      <el-table-column prop="orderId" label="订单ID" width="120">
      </el-table-column>
      <el-table-column prop="userName" label="租借人" width="120">
      </el-table-column>
      <el-table-column prop="carContent" label="车牌号" width="120">
      </el-table-column>
      <el-table-column label="租借类型">
        <template slot-scope="scope">
          {{ scope.row.mode == 0 ? "按时租定" : "按天租定" }}
        </template>
      </el-table-column>
      <el-table-column prop="orderMoney" label="金额"> </el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button size="mini" @click="open(scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 订单详情对话框 -->
    <el-dialog
      title="结束订单(订单详细)"
      :visible.sync="dialogVisible"
      width="40%"
      :close-on-click-modal="false"
      :before-close="close"
    >
      <div class="text">
        <el-row>
          <el-col :span="5">租借人</el-col>
          <el-col :span="16">{{ datas.userName }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="5">当前车牌</el-col>
          <el-col :span="16">{{ datas.carContent || "无" }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="5">停车位</el-col>
          <el-col :span="16">{{ datas.carNumber || "无" }}</el-col>
        </el-row>

        <el-row>
          <el-col :span="5">当前套餐</el-col>
          <el-col :span="16">{{ datas.modeName || "无" }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="5">租借类型</el-col>
          <el-col :span="16">{{
            datas.mode == 0 ? "按时租定" : "按天租定"
          }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="5">租借时长</el-col>
          <el-col :span="16">{{
            rentalHours == ""
              ? rentalDays.toFixed(1) + "天"
              : rentalHours.toFixed(1) + "小时"
          }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="5">费用合计</el-col>
          <el-col :span="16">{{
            hourMoney == ""
              ? dayMoney.toFixed(1) + "元"
              : hourMoney.toFixed(1) + "元"
          }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="5">选择当前停车场</el-col>
          <el-select v-model="value" filterable placeholder="请选择停车场">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-row>
        <el-row>
          <!-- 上传车辆照片 -->
          <el-col :span="5">上传实时照片</el-col>
          <Upload @upload-success="handleUploadSuccess"></Upload>
          <img
            v-if="imageUrl"
            :src="imageUrl"
            alt="Uploaded Image"
            style="width: 30%"
          />
        </el-row>
        <el-row>
          <el-col :span="5">确认归还</el-col>
          <el-button type="success" @click="returnCar()">确认归还</el-button>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Upload from "@/components/Upload/index";
export default {
  name: "orderPact",
  components: { Upload },
  data() {
    return {
      dialogVisible: false,
      datas: {},
      rentalDays: "",
      rentalHours: "",
      dayMoney: "",
      hourMoney: "",
      options: [],
      value: "",
      imageUrl: "",
      // 筛选表单数据
      filterForm: {
        mode: null,
        minAmount: null,
        maxAmount: null,
        parking_id: null,
        keyword: "",
        orderStatus: null,
      },
      dateRange: null, // 日期范围数据
      tableData: [], // 表格数据
      loading: false, // 添加加载状态
    };
  },
  created() {
    console.log("组件创建 - created 钩子被调用");
    // 组件创建时获取停车场选项和订单数据
    this.getOptions();
    this.fetchOrderList();
  },
  mounted() {
    console.log("组件挂载 - mounted 钩子被调用");
    // 检查DOM元素是否存在
    this.$nextTick(() => {
      console.log(
        "筛选区域是否存在:",
        document.querySelector(".filter-container") !== null
      );
    });
  },
  methods: {
    // 获取停车场选项
    getOptions() {
      console.log("开始获取停车场选项");
      this.$API.parking
        .getParking()
        .then((result) => {
          console.log("获取停车场选项成功:", result.status === 200);
          if (result.status == 200) {
            let options = [];
            result.data.forEach((item) => {
              options.push({
                value: item.id,
                label: item.parkingName,
              });
            });
            this.options = options;
          } else {
            this.$message.error(result.message);
          }
        })
        .catch((error) => {
          console.error("获取停车场选项失败:", error);
          this.$message.error("获取停车场信息失败");
        });
    },

    // 获取订单列表数据
    fetchOrderList() {
      console.log("开始获取订单列表");
      this.loading = true;

      // 构建请求参数
      const params = this.buildFilterParams();
      console.log("筛选参数:", params);

      // 调用API获取数据
      this.$API.order
        .getOrderList(params)
        .then((result) => {
          console.log("获取订单列表成功:", result.status === 200);
          if (result.status == 200) {
            this.tableData = result.data;
            console.log("获取到的数据条数:", this.tableData.length);
          } else {
            this.$message.error(result.message);
          }
        })
        .catch((error) => {
          console.error("获取订单列表失败:", error);
          this.$message.error("获取订单列表失败");
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 构建筛选参数
    buildFilterParams() {
      const params = {};

      // 添加日期范围参数
      if (this.dateRange && this.dateRange.length === 2) {
        params.startDate = this.dateRange[0];
        params.endDate = this.dateRange[1];
      }

      // 添加其他筛选条件
      if (this.filterForm.mode !== null) {
        params.mode = this.filterForm.mode;
      }

      if (this.filterForm.minAmount !== null) {
        params.minAmount = this.filterForm.minAmount;
      }

      if (this.filterForm.maxAmount !== null) {
        params.maxAmount = this.filterForm.maxAmount;
      }

      if (this.filterForm.parking_id !== null) {
        params.parking_id = this.filterForm.parking_id;
      }

      if (this.filterForm.keyword) {
        params.keyword = this.filterForm.keyword;
      }

      if (this.filterForm.orderStatus !== null) {
        params.orderStatus = this.filterForm.orderStatus;
      }

      return params;
    },

    // 处理日期范围变化
    handleDateRangeChange() {
      console.log("日期范围变化:", this.dateRange);
      this.handleFilterChange();
    },

    // 处理筛选条件变化
    handleFilterChange() {
      console.log("筛选条件变化");
      this.fetchOrderList();
    },

    // 重置筛选条件
    resetFilters() {
      console.log("重置筛选条件");
      this.filterForm = {
        mode: null,
        minAmount: null,
        maxAmount: null,
        parking_id: null,
        keyword: "",
        orderStatus: null,
      };
      this.dateRange = null;

      // 重新获取数据
      this.fetchOrderList();
    },

    handleUploadSuccess(url) {
      this.imageUrl = url;
    },
    close() {
      this.dialogVisible = false;
    },
    open(data) {
      this.dialogVisible = true;
      this.fetchOrderPact(data);
      console.log(data);
    },
    // 获取信息
    async fetchOrderPact(data) {
      this.datas = data;
      // 获取停车场信息
      this.$API.parking
        .getParking()
        .then((result) => {
          if (result.status == 200) {
            this.$message.success(result.message);
            let options = [];
            result.data.forEach((item) => {
              options.push({
                value: item.id,
                label: item.parkingName,
              });
            });
            this.options = options;
          } else {
            this.$message.error(result.message);
          }
        })
        .catch((error) => {
          console.error(error);
        });
      // 租车模式为小时
      if (data.mode == 0) {
        let hourMoney = data.hourMoney;
        let startTime = new Date(); // 假设这是起租时间，可以根据实际情况设置
        let outTime = new Date(data.outTime); // 将字符串转换为日期对象
        // 将 outTime 转换为本地时间
        outTime = new Date(
          outTime.getTime() + outTime.getTimezoneOffset() * 60000
        );
        // 判断是否是有效的日期对象
        if (!isNaN(outTime.getTime())) {
          // 计算时间差
          let rentalHours =
            (startTime.getTime() - outTime.getTime()) / (1000 * 3600); // 毫秒转小时
          // 按时租计算费用
          let totalCost = rentalHours * hourMoney;
          console.log("小时时间", rentalHours.toFixed(1));
          console.log("小时总费用", totalCost.toFixed(1));
          this.rentalHours = rentalHours;
          this.hourMoney = totalCost;
        } else {
          console.error("出错了:", data.outTime);
        }
        // 按天租计算费用
      } else if (data.mode == 1) {
        let dayMoney = data.dayMoney;
        let startTime = new Date(); // 开始时间（假设为当前时间）
        // 将结束时间转换为日期对象
        let endTime = new Date(data.outTime);
        // 判断是否是有效的日期对象
        if (!isNaN(endTime.getTime())) {
          // 计算租车天数，向上取整
          let rentalDays = Math.ceil(
            (endTime.getTime() - startTime.getTime()) / (1000 * 3600 * 24)
          );
          // 按天租计算费用
          let totalCost = rentalDays * dayMoney;
          console.log("天数:", rentalDays.toFixed(1));
          console.log("总费用:", totalCost.toFixed(1));
          this.rentalDays = rentalDays;
          this.dayMoney = totalCost;
        } else {
          console.error("Invalid outTime:", data.OutTime);
        }
      }
    },

    returnCar() {
      this.$confirm(
        "确认归还该车辆，请尽快支付避免逾期造成征信黑名单, 是否继续?",
        "提示",
        {
          confirmButtonText: "去付款",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          // 显示支付方式选择对话框
          this.$confirm(
            '<div style="text-align: center;">请选择支付方式</div>',
            "选择支付方式",
            {
              dangerouslyUseHTMLString: true,
              confirmButtonText: "支付宝",
              cancelButtonText: "现金结算",
              distinguishCancelAndClose: true,
              closeOnClickModal: false,
            }
          )
            .then(() => {
              // 用户选择支付宝支付
              this.handlePayment("支付宝");
            })
            .catch((action) => {
              if (action === "cancel") {
                // 用户选择现金结算
                this.handlePayment("现金");
              }
            });
        })
        .catch(() => {
          // 用户取消付款不显示任何消息
        });
    },

    // 处理支付流程
    handlePayment(paymentMethod) {
      // 显示加载中提示
      const loading = this.$loading({
        lock: true,
        text: "支付处理中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });

      // 准备提交的数据
      let data = {
        // 车辆id
        carId: this.datas.carId,
        // 订单id
        orderId: this.datas.orderId,
        // 订单状态为已归还
        OrderStatus: 1,
        // 停车场id
        parking_id: this.value,
        // 改车辆状态为可用
        CarStatus: 1,
        // 入库照片
        InPicture: this.imageUrl,
        // 订单金额
        OrderMoney:
          this.hourMoney == ""
            ? this.dayMoney.toFixed(1)
            : this.hourMoney.toFixed(1),
        // 支付方式
        paymentMethod: paymentMethod,
      };

      console.log(data);

      // 模拟支付过程，实际项目中应该调用真实的支付接口
      setTimeout(() => {
        // 关闭加载提示
        loading.close();

        // 调用API进行还车处理
        this.$API.car
          .returnCar(data)
          .then((result) => {
            if (result.status == 200) {
              // 显示支付成功提示
              this.$notify({
                title: "支付成功",
                message: "车辆已成功归还",
                type: "success",
                duration: 3000,
                iconClass: "el-icon-check",
              });

              this.$message.success(result.message);
              this.$router.push({ path: "/carManage/carList" });
            } else {
              this.$message.error(result.message);
            }
          })
          .catch((error) => {
            console.error(error);
            this.$message.error("支付过程中发生错误");
          });
      }, 2000); // 2秒后完成支付处理（模拟）
    },
  },
};
</script>

<style>
/* 注意：移除了scoped标记以防止样式隔离 */
.text {
  height: 100%;
  font-size: 18px;
}
</style>
