<template>
  <div style="overflow-y: auto; height: 500px">
    <el-form ref="form" :model="form" :rules="tempRules">
      <el-form-item label="类型" prop="type" label-width="150px">
        <el-radio v-model="form.type" label="1">电动汽车</el-radio>
        <el-radio v-model="form.type" label="2">电动自行车</el-radio>
      </el-form-item>
      <el-form-item label="名称" prop="name" label-width="150px">
        <el-input
          v-model="form.name"
          style="width: 50%"
          placeholder="请输入模板名称"
        />
      </el-form-item>
      <el-form-item label="描述" prop="remark" label-width="150px">
        <el-input
          v-model="form.remark"
          style="width: 50%"
          placeholder="请输入模板备注"
        />
      </el-form-item>
      <el-divider />
      <!-- 设置费率 -->

      <!-- 电动汽车费率设置  -->
      <div
        v-if="form.type === '1'"
        style="width: 80%; margin-left: 90px; position: relative"
      >
        <!-- 电汽车 -->
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="grid-content bg-purple" style="margin-left: 20px">
              时段
            </div>
          </el-col>

          <el-col :span="8">
            <div class="grid-content bg-purple">电费(元/度)</div>
          </el-col>

          <el-col :span="6">
            <div class="grid-content bg-purple">服务费(元/度)</div>
          </el-col>
        </el-row>
        <!-- 表单数据 -->

        <!-- 尖 -->
        <el-row :gutter="20">
          <el-col :span="4">
            <el-button type="danger">尖时段</el-button>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="electricityPriceA">
              <el-input
                v-model="form.electricityPriceA"
                type="text"
                placeholder="0"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="servicePriceA">
              <el-input
                v-model="form.servicePriceA"
                placeholder="0"
                clearable
                type="text"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 峰 -->
        <el-row :gutter="20">
          <el-col :span="4">
            <el-button type="warning">峰时段</el-button>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="electricityPriceB">
              <el-input
                v-model="form.electricityPriceB"
                type="text"
                placeholder="0"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="servicePriceB">
              <el-input
                v-model="form.servicePriceB"
                placeholder="0"
                clearable
                type="text"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 平 -->
        <el-row :gutter="20">
          <el-col :span="4">
            <el-button type="success">平时段</el-button>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="electricityPriceC">
              <el-input
                v-model="form.electricityPriceC"
                type="text"
                placeholder="0"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="servicePriceC">
              <el-input
                v-model="form.servicePriceC"
                placeholder="0"
                clearable
                type="text"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 谷 -->
        <el-row :gutter="20">
          <el-col :span="4">
            <el-button type="info">谷时段</el-button>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="electricityPriceD">
              <el-input
                v-model="form.electricityPriceD"
                type="text"
                placeholder="0"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="servicePriceD">
              <el-input
                v-model="form.servicePriceD"
                placeholder="0"
                clearable
                type="text"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <span>24小时尖峰平谷分布设置</span>
        <div>
          <el-tag
            v-for="item in dynamicTags"
            :key="item.label"
            :type="item.type"
            style="margin: 10px 10px 10px 0; width: 160px; height: 30px"
            effect="dark"
          >
            {{ item.label }}
            <i
              class="el-icon-edit el-icon&#45;&#45;right"
              @click="editBtn(item.label)"
            />
            <i class="el-icon-close" @click="deleteBtn(item.label)" />
          </el-tag>
        </div>
        <div>
          <el-button @click="reviseVisible = true">增加计费时段</el-button>
          <!--<el-button>占桩收费模板</el-button>-->
          <!--<div style="position: absolute; bottom: 0px; right: 10px">
            <el-button @click="hCancel">取 消</el-button>
            <el-button type="primary" @click="onSubmit">确 定</el-button>
          </div>-->
        </div>
        <el-dialog
          title="设置计费时段"
          :visible.sync="reviseVisible"
          width="40%"
          append-to-body
        >
          <p>开始时间</p>
          <el-time-select
            v-model="startTime"
            :picker-options="{
              start: '00:00',
              step: '00:30',
              end: '24:00',
            }"
            placeholder="选择开始时间"
            :disabled="selectDisabled"
          />
          <p>标签</p>
          <el-radio-group v-model="radio">
            <el-radio :label="1">尖</el-radio>
            <el-radio :label="2">峰</el-radio>
            <el-radio :label="3">平</el-radio>
            <el-radio :label="4">谷</el-radio>
          </el-radio-group>
          <span slot="footer" class="dialog-footer">
            <el-button @click="reviseVisible = false">取 消</el-button>
            <el-button type="primary" @click="clickSelectStartTimeConfirm"
              >确 定</el-button
            >
          </span>
        </el-dialog>
      </div>
      <div v-else>
        <!-- 电单车页面 -->
        <div class="txt">
          <p>
            <b>
              以下配置应用于电动汽车占桩费计算。例如
              免费占桩时间30分钟，封顶金额25元 占桩费单价2元/分钟
            </b>
          </p>
          <p>
            表示：充电结束30分钟内不收取费用，超过30分钟的时间按每分钟2元收费，封顶25元。
          </p>
        </div>
        <el-form-item
          label="最小单位费用(元):"
          prop="minMoney"
          label-width="150px"
        >
          <el-input v-model="form.minMoney" type="text" placeholder="0" />
        </el-form-item>
        <div class="txt">
          <p>
            <b>
              本设置只应用于电动自行车（按功率时长）的计费策略，当费用不足最小单位费用的整数倍时，将会安装最小单位费用的整数倍收取（前几分钟不参与计费）。
            </b>
          </p>
          <p>
            如，最小单位费用的是0.5元，当费用为1.1元时，将会收取1.5元；当费用为1.5元时，将会收取1.5元
          </p>
          <p>
            如，<i>免费充电时长的是5分钟</i>，当充电时长是4分钟时，将不会收取费用；当充电时长是6分钟，将会根据计费模板收取6分钟的费用
          </p>
        </div>
        <el-form-item
          label="免费充电时长(分钟):"
          prop="minute"
          label-width="150px"
        >
          <el-input v-model="form.minute" type="text" placeholder="5" />
        </el-form-item>

        <!-- 按钮 -->
        <div class="btn">
          <div class="p1">
            功率-0W至300W
            <el-link :underline="false">
              <i
                class="el-icon-edit el-icon--right"
                @click="dialogFormVisible = true"
              />
            </el-link>
            <el-link :underline="false"><i class="el-icon-close" /></el-link>
          </div>
          <div class="energy">
            电费:1元<span>{{ num }}小时</span>
          </div>
        </div>

        <el-button
          style="width: 170px"
          type="text"
          @click="dialogFormVisible = true"
          >增加功率分段</el-button
        >

        <el-dialog
          title="设置功率分段"
          :visible.sync="dialogFormVisible"
          append-to-body
        >
          <el-form :model="form">
            <el-form-item label="充电功率(W):" :label-width="formLabelWidth">
              <el-input
                v-model.number="form.name"
                min="0"
                type="number"
                autocomplete="off"
              />
            </el-form-item>
            <el-form-item label="费用(1元X小时):" :label-width="formLabelWidth">
              <el-input
                v-model.number="form.region"
                type="number"
                placeholder="2"
                min="0"
              />
            </el-form-item>
          </el-form>
          <!--设置功率分段dialog的按钮-->
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="dialogFormVisible = false"
              >确 定</el-button
            >
          </div>
        </el-dialog>
      </div>
    </el-form>

    <!-- 电动汽车 电动自行车 公用一组按钮 -->
    <div style="position: absolute; bottom: 0px; right: 30px">
      <el-button @click="hCancel">取 消</el-button>
      <el-button type="primary" @click="onSubmit">确 定</el-button>
    </div>
  </div>
</template>

<script>
import {addBillingTemplate, getTemplate, updateBillingTemplate} from "@/api/billing/template.js";
export default {
  data() {
    return {
      // 所有的校验规则
      tempRules: {
        name: [
          {
            type: "string",
            required: true,
            message: "请输入名称",
            trigger: "blur",
          },
        ],
        remark: [
          {
            type: "string",
            required: true,
            message: "请输入名称",
            trigger: "blur",
          },
        ],
        // 电汽车
        electricityPriceA: [
          { required: true, message: "请输入数字", trigger: "blur" },
          {
            pattern: /^[0-9]+(.[0-9]{1,5})?$/,
            message: "可以保留五位小数",
            trigger: "blur",
          },
        ],
        servicePriceA: [
          { required: true, message: "请输入数字", trigger: "blur" },
          {
            pattern: /^[0-9]+(.[0-9]{1,5})?$/,
            message: "可以保留五位小数",
            trigger: "blur",
          },
        ],
        electricityPriceB: [
          { required: true, message: "请输入数字", trigger: "blur" },
          {
            pattern: /^[0-9]+(.[0-9]{1,5})?$/,
            message: "可以保留五位小数",
            trigger: "blur",
          },
        ],
        servicePriceB: [
          { required: true, message: "请输入数字", trigger: "blur" },
          {
            pattern: /^[0-9]+(.[0-9]{1,5})?$/,
            message: "可以保留五位小数",
            trigger: "blur",
          },
        ],
        electricityPriceC: [
          { required: true, message: "请输入数字", trigger: "blur" },
          {
            pattern: /^[0-9]+(.[0-9]{1,5})?$/,
            message: "可以保留五位小数",
            trigger: "blur",
          },
        ],
        servicePriceC: [
          { required: true, message: "请输入数字", trigger: "blur" },
          {
            pattern: /^[0-9]+(.[0-9]{1,5})?$/,
            message: "可以保留五位小数",
            trigger: "blur",
          },
        ],
        electricityPriceD: [
          { required: true, message: "请输入数字", trigger: "blur" },
          {
            pattern: /^[0-9]+(.[0-9]{1,5})?$/,
            message: "可以保留五位小数",
            trigger: "blur",
          },
        ],
        servicePriceD: [
          { required: true, message: "请输入数字", trigger: "blur" },
          {
            pattern: /^[0-9]+(.[0-9]{1,5})?$/,
            message: "可以保留五位小数",
            trigger: "blur",
          },
        ],
        // 电单车校验规则
        minMoney: [
          { required: true, message: "最小单位费用多少元", trigger: "blur" },
          {
            pattern: /^[0-9]+(.[0-9]{1,5})?$/,
            message: "可以保留五位小数",
            trigger: "blur",
          },
        ],
        minute: [
          { required: true, message: "免费充电时长", trigger: "blur" },
          { pattern: /^\d+$/, message: "请输入数字", trigger: "blur" },
        ],
      },
      // 父组件传来的id
      // billingTemplateId: "",
      // 电动汽车
      form: {
        electricityPriceA: "",
        servicePriceA: "",
        electricityPriceB: "",
        servicePriceB: "",
        electricityPriceC: "",
        servicePriceC: "",
        electricityPriceD: "",
        servicePriceD: "",
        timeArray: [
          {
            type: "1",
            startTime: "00:00",
            endTime: "24:00",
          },
        ],
        type: "1",
        name: "",
        remark: "",
        minMoney: "",
        minute: "",
      },
      // 设置计费模板
      reviseVisible: false,
      // 开始时间
      startTime: "",
      // 结束时间
      endTime: "",
      // 标签 单选框
      radio: 3,
      selectDisabled: false,
      // 选择的开始时间 默认00:00开始，24:00结束（云快充协议需要24:00,不认23:59）
      selectStartTime: [
        {
          startTime: "00:00",
          type: 1,
        },
      ],
      // 弹框
      dialogFormVisible: false,
      formLabelWidth: "120px",
      num: "2",
    };
  },
  methods: {
    // car组件里面的内容
    // 确定按钮
    clickSelectStartTimeConfirm() {
      let e = {
        startTime: this.startTime,
        type: this.radio,
      };
      // startTime在原数组中存在，把老的删掉
      this.selectStartTime = this.selectStartTime.filter(
        (item) => item.startTime !== this.startTime
      );
      // 新时间插入数组最后
      this.selectStartTime.push(e);
      // selectStartTime根据startTime排序
      this.selectStartTime.sort((a, b) =>
        a.startTime.localeCompare(b.startTime)
      );
      // 关闭对话框
      this.reviseVisible = false;
      // 调生成方法
      this.generateTimeArray();
    },
    // 生成timeArray
    generateTimeArray() {
      // 原来的timeArray初始化为空数组
      this.form.timeArray = [];
      // 使用selectStartTime中的数据重新生成数据
      for (let i = 0; i < this.selectStartTime.length; i++) {
        let start = this.selectStartTime[i];
        let end = this.selectStartTime[i + 1];
        // 遍历到最后一位时，取不到end，就给默认结束时间24:00
        if (end === undefined) {
          end = {
            startTime: "24:00",
          };
        }
        let time = {
          type: String(start.type),
          startTime: start.startTime,
          endTime: end.startTime,
        };
        this.form.timeArray.push(time);
      }
    },
    // 重置表单
    resetForm() {
      this.$refs.form.resetFields();
      this.form = {
        name: "",
        remark: "",
        type: '1',
        electricityPriceA: "",
        servicePriceA: "",
        electricityPriceB: "",
        servicePriceB: "",
        electricityPriceC: "",
        servicePriceC: "",
        electricityPriceD: "",
        servicePriceD: "",
        timeArray: [
          {
            type: "1",
            startTime: "00:00",
            endTime: "24:00",
          },
        ],
        region: "",
        minMoney: "",
        minute: "",
      };
    },
    // 取消按钮
    hCancel() {
      this.resetForm();
      this.$emit("success");
    },
    // 确认按钮
    onSubmit() {
      // this.carBillList();
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.billingTemplateId === '') {
            // 没有id 新增
            this.create();
          } else {
            // 存在id 更新
            this.update();
          }
          // 重置表单
          this.resetForm();
          this.$emit("success");
        }
      });
    },
    create() {
      addBillingTemplate(this.form).then((response) => {
        console.log("接口返回", response);
        this.$message.success("新增成功");
      });
    },
    update() {
      this.$set(this.form, 'billingTemplateId', this.billingTemplateId);
      updateBillingTemplate(this.form).then((response) => {
        console.log("接口返回", response);
        this.$message.success("修改成功");
      });
    },
    // 查计费模板详情
    queryInfo(billingTemplateId) {
      getTemplate(billingTemplateId).then((response) => {
        // console.log("更新计费模板 查询计费模板详情", response);
        this.form = response.data;
        console.log("timeArray", this.form.timeArray);
        const selectStartTimeArr = [];
        this.form.timeArray.forEach(x => {
          const startTime = {
            startTime: x.startTime,
            type: x.type
          };
          selectStartTimeArr.push(startTime);
        })
        this.selectStartTime = selectStartTimeArr;
      });
    },
    editBtn(param) {
      console.log("点击修改按钮", param);
      const splitArr = param.split("-");
      const editType = splitArr[0].trim();
      if (editType === "尖") {
        this.radio = 1;
      } else if (editType === "峰") {
        this.radio = 2;
      } else if (editType === "平") {
        this.radio = 3;
      } else {
        this.radio = 4;
      }
      // console.log("radio", this.radio);
      this.startTime = splitArr[1].trim();
      // 打开对话框
      this.reviseVisible = true;
      this.selectDisabled = true;
    },
    deleteBtn(param) {
      const splitArr = param.split("-");
      const delObj = splitArr[1].trim();
      if (delObj === "00:00") {
        return;
      }
      this.selectStartTime = this.selectStartTime.filter(
        (item) => item.startTime !== delObj
      );
      // 调生成方法
      this.generateTimeArray();
    },
  },
  // 接受父组件的值
  props: {
    billingTemplateId: String,
    required: true
  },
  mounted() {
    // console.log("billingTemplateId 的值是：", this.billingTemplateId);
    if (this.billingTemplateId !== "") {
      this.queryInfo(this.billingTemplateId);
    }
  },
  watch: {
    reviseVisible(newName, oldName) {
      // console.log("reviseVisible发生变化", newName);
      if (newName === false) {
        this.selectDisabled = false;
      }
    },
    billingTemplateId(newId, oldId) {
      // console.log("billingTemplateId发生变化 newId:", newId);
      if (newId !== "") {
        this.queryInfo(newId);
      }
    }
  },
  computed: {
    dynamicTags() {
      let tags = [];
      this.form.timeArray.map((x) => {
        // console.log(x.type);
        let type;
        let desc;
        if (x.type === "1") {
          type = "danger";
          desc = "尖";
        } else if (x.type === "2") {
          type = "warning";
          desc = "峰";
        } else if (x.type === "3") {
          type = "success";
          desc = "平";
        } else {
          type = "info";
          desc = "谷";
        }
        let label = desc + " - " + x.startTime + " - " + x.endTime;
        let tag = {
          type: type,
          label: label,
        };
        tags.push(tag);
      });
      return tags;
    },
  },
};
</script>
<style scoped lang="scss">
.txt {
  margin-left: 150px;
  margin-bottom: 20px;
  border: 1px solid #fff;
  background-color: skyblue;
}
.btn {
  margin-left: 150px;
  width: 180px;
  height: 70px;
  border: 1px solid green;
  .p1 {
    font-size: 18px;
    padding: 2px;
    height: 35px;
    background-color: #30aff8;
  }
  .energy {
    margin: 5px;
  }
}
.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.frame {
  width: 126px;
  height: 36px;
  line-height: 36px;
  background-color: #409eff;
}

.el-tag + .el-tag {
  margin-left: 10px;
  // min-height: 100px;
  // padding-bottom: 95px;
}
</style>
