<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="套餐名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入套餐名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 按钮和表格 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:fee:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:fee:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:fee:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:fee:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="feeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="ruleId" />
      <el-table-column label="套餐名称" align="center" prop="name" />
      <el-table-column label="说明" align="center" prop="explain" />
      <el-table-column label="时间(小时)" align="center" prop="time" />
      <el-table-column label="费用(元)" align="center" prop="fee" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:fee:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:fee:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改收费方式对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <!-- ...其他表单项... -->
        
        <!-- 区间计费选项 -->
        <div v-if="form.billingRule === '区间计费'">
          <el-form-item label="启用区间">
            <el-switch v-model="form.intervalEnabled" @change="toggleInterval" />
          </el-form-item>
          <div v-if="form.intervalEnabled">
            <div v-for="(interval, index) in form.intervals" :key="index" class="interval-group">
              <el-row :gutter="10">
                <el-col :span="2">
                  <span>在</span>
                </el-col>
                <el-col :span="4">
                  <el-input v-model="interval.start" :placeholder="'请输入开始时间（' + timeUnit + '）'" />
                </el-col>
                <el-col :span="1" style="line-height: 32px;">
                  ~
                </el-col>
                <el-col :span="4">
                  <el-input v-model="interval.end" :placeholder="'请输入结束时间（' + timeUnit + '）'" />
                </el-col>
                <el-col :span="1" style="line-height: 32px;">
                  {{ timeUnit }} 之间，每
                </el-col>
                <el-col :span="4">
                  <el-input v-model="interval.each" placeholder="请输入时间间隔" />
                </el-col>
                <el-col :span="1" style="line-height: 32px;">
                  {{ timeUnit }} 收费
                </el-col>
                <el-col :span="4">
                  <el-input v-model="interval.fee" placeholder="请输入费用" />
                </el-col>
                <el-col :span="1" style="line-height: 32px;">
                  元
                </el-col>
                <el-col :span="2">
                  <el-button type="danger" icon="el-icon-delete" @click="removeInterval(index)">删除</el-button>
                </el-col>
              </el-row>
            </div>
            <el-form-item>
              <el-button type="primary" icon="el-icon-plus" @click="addInterval">添加区间</el-button>
            </el-form-item>
          </div>
          <div v-else>
            <el-form-item>
              <el-row :gutter="10">
                <el-col :span="2">
                  <span>在</span>
                </el-col>
                <el-col :span="4">
                  <el-input placeholder="请输入开始时间" disabled />
                </el-col>
                <el-col :span="1" style="line-height: 32px;">
                  ~
                </el-col>
                <el-col :span="4">
                  <el-input placeholder="请输入结束时间" disabled />
                </el-col>
                <el-col :span="1" style="line-height: 32px;">
                  {{ timeUnit }} 之间，每
                </el-col>
                <el-col :span="4">
                  <el-input placeholder="请输入时间间隔" disabled />
                </el-col>
                <el-col :span="1" style="line-height: 32px;">
                  {{ timeUnit }} 收费
                </el-col>
                <el-col :span="4">
                  <el-input placeholder="请输入费用" disabled />
                </el-col>
                <el-col :span="1" style="line-height: 32px;">
                  元
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item>
              <el-row :gutter="10">
                <el-col :span="2">
                  <span>大于</span>
                </el-col>
                <el-col :span="4">
                  <el-input placeholder="请输入时间" />
                </el-col>
                <el-col :span="1" style="line-height: 32px;">
                  {{ timeUnit }} 之后，每
                </el-col>
                <el-col :span="4">
                  <el-input placeholder="请输入时间间隔" />
                </el-col>
                <el-col :span="1" style="line-height: 32px;">
                  {{ timeUnit }} 收费
                </el-col>
                <el-col :span="4">
                  <el-input placeholder="请输入费用" />
                </el-col>
                <el-col :span="1" style="line-height: 32px;">
                  元
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item>
              <div>
                注：
                <br />1) 不是单位时间的仍按单位时间收取费用；超出起步时间后的均匀计算。
                <br />2) 为避免免费用户使用，切勿频繁切换。
              </div>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFee, getFee, delFee, addFee, updateFee } from "@/api/system/fee";

export default {
  name: "Fee",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      feeList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        status: null,
      },
      form: {
        name: null,
        explain: null,
        unit: '按分钟',
        billingCycle: null,
        maxAmount: null,
        billingRule: '起步价计费',
        startPrice: null,
        startTime: null,
        exceedTime: null,
        exceedPrice: null,
        intervalEnabled: false,
        intervals: [{ start: '', end: '', each: '', fee: '' }],
      },
      timeUnit: '分钟',
      rules: {
        name: [{ required: true, message: '请输入套餐名称', trigger: 'blur' }],
        explain: [{ required: true, message: '请输入说明', trigger: 'blur' }],
        unit: [{ required: true, message: '请选择租赁单位', trigger: 'change' }],
        billingRule: [{ required: true, message: '请选择骑行计费规则', trigger: 'change' }],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleUnitChange() {
      this.timeUnit = this.form.unit === '按分钟' ? '分钟' : (this.form.unit === '按小时' ? '小时' : '天');
      if (this.form.unit === '按天') {
        this.form.intervals = [];
      }
    },
    handleBillingRuleChange() {
      if (this.form.billingRule === '区间计费' && this.form.intervals.length === 0) {
        this.addInterval();
      }
    },
    addInterval() {
      this.form.intervals.push({ start: '', end: '', each: '', fee: '' });
    },
    removeInterval(index) {
      this.form.intervals.splice(index, 1);
    },
    getList() {
      this.loading = true;
      listFee(this.queryParams).then(response => {
        this.feeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        name: null,
        explain: null,
        unit: '按分钟',
        billingCycle: null,
        maxAmount: null,
        billingRule: '起步价计费',
        startPrice: null,
        startTime: null,
        exceedTime: null,
        exceedPrice: null,
        intervalEnabled: false,
        intervals: [{ start: '', end: '', each: '', fee: '' }]
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.ruleId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加收费方式";
    },
    handleUpdate(row) {
      this.reset();
      const ruleId = row.ruleId || this.ids;
      getFee(ruleId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改收费方式";
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.ruleId != null) {
            updateFee(this.form).then(() => {
              this.$message.success("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFee(this.form).then(() => {
              this.$message.success("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDelete(row) {
      const ruleIds = row.ruleId || this.ids;
      this.$confirm('是否确认删除收费方式编号为"' + ruleIds + '"的数据项？')
        .then(() => {
          return delFee(ruleIds);
        }).then(() => {
          this.getList();
          this.$message.success("删除成功");
        }).catch(() => {});
    },
    handleExport() {
      this.download('system/fee/export', {
        ...this.queryParams
      }, `fee_${new Date().getTime()}.xlsx`);
    },
    resetForm(formName) {
      this.$refs[formName] && this.$refs[formName].resetFields();
    },
    toggleInterval() {
      if (!this.form.intervalEnabled) {
        this.form.intervals = [{ start: '', end: '', each: '', fee: '' }];
      }
    },
  }
};
</script>

<style scoped>
.interval-group {
  margin-bottom: 10px;
}
.el-row {
  align-items: center;
}
.el-col {
  display: flex;
  align-items: center;
}
</style>
