<template>
  <div v-if="pageStatus == 0">配置加载中...</div>
  <div v-else-if="pageStatus == 1">此页面不对此账号开放</div>
  <div v-else-if="pageStatus == 2">权限已下放到站点，请登录站点账号配置</div>
  <div v-else-if="pageStatus == 3">加载发生错误</div>
  <div v-else-if="pageStatus == 4" class="app-container">
    <el-form
      ref="ruleForm"
      :model="ruleForm"
      :rules="rules"
      label-width="130px"
    >
      <el-form-item label="当前执行优惠方案">
        {{ currentDiscountName }}
      </el-form-item>
      <el-form-item label="优惠方案">
        <el-select
          v-model="ruleForm.discountSetting"
          placeholder="请选择优惠方案"
          clearable
          size="small"
          @change="discountSettingChang"
        >
          <el-option label="无" value="0"></el-option>
          <el-option label="满减" value="1"></el-option>
          <el-option label="立减" value="2"></el-option>
          <el-option label="直降" value="3"></el-option>
        </el-select>
        <el-button size="mini" @click="save" type="primary"
          >确定执行该优惠方案</el-button
        >
      </el-form-item>
    </el-form>

    <hr />
    <el-dialog
      :visible.sync="openDialog"
      width="600px"
      append-to-body
      :title="['', '满减方案', '立减方案', '直降方案'][discountSetting]"
    >
      <el-form
        ref="updateForm"
        :model="updateForm"
        :rules="rules"
        label-width="140px"
      >
        <el-form-item label="方案名称" prop="grade">
          <el-input v-model="updateForm.grade" placeholder="请输入方案名称" />
        </el-form-item>
        <el-form-item label="油品名称" prop="oilName">
          <el-select
            v-model="updateForm.oilName"
            placeholder="油品名称"
            clearable
            size="small"
          >
            <el-option
              v-for="dict in filterOilNameOptions"
              :key="dict.oilName"
              :label="dict.oilName"
              :value="dict.oilName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="优惠条件" prop="gasoilDiscountAmt" required>
          <el-radio-group
            v-model="updateForm.discountTerm"
            v-if="discountSetting == 3"
          >
            <el-radio :label="2">按加油金额优惠</el-radio>
            <el-radio :label="1">按加油升数优惠</el-radio>
          </el-radio-group>
          <div
            v-show="
              updateForm.discountTerm == 2 ||
              updateForm.discountTerm == 1 ||
              discountSetting == 1 ||
              discountSetting == 2
            "
          >
            {{ ["", "每满", "满", "满"][discountSetting] }}
            <el-input-number
              v-model="updateForm.discountAmt"
              size="mini"
              :min="0"
            />

            <span>{{ updateForm.discountTerm == 1 && discountSetting == 3 ? "L" : "元" }}</span>
            ，{{ ["", "减", "减", "每升优惠"][discountSetting] }}
            <el-input-number
              v-model="updateForm.gasoilDiscountAmt"
              size="mini"
              :min="0"
            />元
          </div>
        </el-form-item>
        <el-form-item label="叠加等级优惠" prop="vipDiscountyPlus">
          <el-radio-group v-model="updateForm.vipDiscountyPlus">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
          <div style="margin-left: 20px; color: red">
            注："否" 客户只享受 {{ discountName }} 优惠
          </div>
        </el-form-item>
        <el-form-item label="可否叠加劵" prop="couponPlus">
          <el-radio-group v-model="updateForm.couponPlus">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
          <div style="margin-left: 20px; color: red">
            注："否" 客户只享受 {{ discountName }} 优惠
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="cancelSubmit">取 消</el-button>
      </div>
    </el-dialog>

    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="68px"
      v-show="discountSetting != 0"
    >
      <div>
        <span style="color: #ff9955; font-size: 25px">|</span
        ><span style="font-size: 25px">
          {{
            this.discountSetting == 1
              ? "满减方案"
              : this.discountSetting == 2
              ? "立减方案"
              : this.discountSetting == 3
              ? "直降方案"
              : "无"
          }}
        </span>
        <el-button
          icon="el-icon-plus"
          size="mini"
          @click="handleUpdateClick"
          style="float: right"
          type="warning"
        >
          {{
            this.discountSetting == 1
              ? "添加满减方案条目"
              : this.discountSetting == 2
              ? "添加立减方案条目"
              : this.discountSetting == 3
              ? "添加直降方案条目"
              : "无"
          }}
        </el-button>
      </div>
    </el-form>
    <el-table :data="discountList" v-show="discountSetting != 0">
      <af-table-column label="id" align="center" prop="id" v-if="false" />
      <af-table-column label="方案名称" align="center" prop="grade" />
      <af-table-column label="油品名称" align="center" prop="oilName" />
      <af-table-column
        label="优惠条件"
        align="center"
        v-if="discountSetting == 3"
      >
        <template slot-scope="scope">
          满 {{ scope.row.discountAmt }}
          {{ scope.row.discountTerm == 2 ? "元" : "L" }}，每升优惠
          {{ scope.row.gasoilDiscountAmt }} 元
        </template>
      </af-table-column>
      <af-table-column
        label="优惠条件"
        align="center"
        v-if="discountSetting == 1"
      >
        <template slot-scope="scope">
          每满 {{ scope.row.discountAmt }} 元，减
          {{ scope.row.gasoilDiscountAmt }} 元
        </template>
      </af-table-column>
      <af-table-column
        label="优惠条件"
        align="center"
        v-if="discountSetting == 2"
      >
        <template slot-scope="scope">
          满 {{ scope.row.discountAmt }} 元，减
          {{ scope.row.gasoilDiscountAmt }} 元
        </template>
      </af-table-column>
      <af-table-column
        label="优惠条件金额"
        v-if="false"
        align="center"
        prop="discountAmt"
      />
      <af-table-column
        label="优惠金额"
        v-if="false"
        align="center"
        prop="gasoilDiscountAmt"
      />
      <af-table-column
        label="是否叠加等级优惠"
        align="center"
        prop="vipDiscountyPlus"
        :formatter="vipDiscountyPlusFotmat"
      />
      <af-table-column
        label="可否叠加劵"
        align="center"
        prop="couponPlus"
        :formatter="couponPlusFotmat"
      />
      <af-table-column
        label="优惠方案类型"
        v-if="false"
        align="center"
        prop="discountPlanType"
      />
      <af-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)"
            >修改</el-button
          > -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </af-table-column>
    </el-table>
  </div>
</template>

<script>
import {
  listPlan,
  getPlan,
  delPlan,
  addPlan,
  updatePlan,
  exportPlan,
} from "@/api/market/plan";
import { getStationPay, updatePay } from "@/api/station/pay";
import { getDept } from "@/api/system/dept";
import { listPrice } from "@/api/station/price";
export default {
  name: "Market_Discount",
  data() {
    const validatorGasoilDiscountAmt = (rule, value, callback) => {
      console.log(this.updateForm.discountTerm);
      if (this.discountSetting == 3) {
        if (
          this.updateForm.discountTerm === undefined ||
          this.updateForm.discountTerm === ""
        ) {
          callback(new Error("请选择优惠方式"));
          return;
        }
      }
      const start = +this.updateForm.discountAmt;
      const end = +this.updateForm.gasoilDiscountAmt;
      if (isNaN(start) || isNaN(end)) {
        callback(new Error("检查优惠方式完整性"));
        return;
      }
      callback();
    };

    return {
      pageStatus: 0,
      discountList: [],
      total: 0,
      oilNameOptions: [],
      title: "",
      openDialog: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        grade: null,
        discountWay: null,
        gasoilDiscountLitre: null,
        dieseloilDiscountLitre: null,
        gradeType: null,
        gasoilConsume: null,
        gasoilGrowthValue: null,
        dieseloilConsume: null,
        dieseloilGrowthValue: null,
        growthValue: null,
        date: null,
        deductionGrowthValue: null,
      },
      updateFormDynamic1: ["", "满", "每满", "满"],
      updateFormDynamic2: ["", "减", "减", "每升优惠"],
      ruleForm: {},
      // 表单校验
      rules: {
        grade: [{ required: true, message: "请输入方案名称", trigger: "blur" }],
        oilName: [
          { required: true, message: "请选择油品名称", trigger: "change" },
        ],
        discountTerm: [
          { required: true, message: "选择油品名称", trigger: "change" },
        ],
        gasoilDiscountAmt: [
          { validator: validatorGasoilDiscountAmt, trigger: "change" },
        ],
        discountAmt: [
          { required: true, message: "请填写优惠金额", trigger: "blur" },
        ],
        vipDiscountyPlus: [
          {
            required: true,
            message: "选择等级优惠是否叠加",
            trigger: "change",
          },
        ],
        couponPlus: [
          { required: true, message: "选择可否叠加券", trigger: "change" },
        ],
      },
      dtrules: {},
      discountSetting: 0,
      updateForm: {},
      currentDiscountName: "",
    };
  },
  computed: {
    discountName() {
      return this.discountSetting == 1
        ? "满减"
        : this.discountSetting == 2
        ? "立减"
        : this.discountSetting == 3
        ? "直降"
        : "无";
    },
    filterOilNameOptions(){
      return this.oilNameOptions.filter((ele)=>{
        let flag = true;
        this.discountList.forEach(item=>{
          if(ele.oilName == item.oilName){
            flag = false;
          }
        })
        return flag
      })
    }
  },
  created() {
    this.setPageStatus();
    this.init();
  },
  methods: {
    init() {
      listPrice().then((response) => {
        this.oilNameOptions = response.rows;
        console.log(this.oilNameOptions)
      });
      this.getPay().then(() => {
        this.getList();
      });
    },
    setPageStatus() {
      this.queryPageStatus([2]).then((res) => {
        this.pageStatus = res;
      });
    },
    getPay() {
      return getStationPay().then((response) => {
        this.ruleForm = response.data;
        this.discountSetting = response.data.discountSetting;
        this.currentDiscountName = this.discountName;
      });
    },
    save() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          if (this.ruleForm.deptId != null) {
            let e = this.ruleForm.discountSetting;
            if (e == "0") {
              updatePay(this.ruleForm).then((response) => {
                this.msgSuccess("优惠方案设置成功");
              });
            } else if (e == "1") {
              if (this.discountList.length > 0) {
                updatePay(this.ruleForm).then((response) => {
                  this.msgSuccess("优惠方案设置成功");
                });
              } else {
                this.msgError("满减规则下无方案");
              }
            } else if (e == "2") {
              if (this.discountList.length > 0) {
                updatePay(this.ruleForm).then((response) => {
                  this.msgSuccess("优惠方案设置成功");
                });
              } else {
                this.msgError("立减规则下无方案");
              }
            } else if (e == "3") {
              if (this.discountList.length > 0) {
                updatePay(this.ruleForm).then((response) => {
                  this.msgSuccess("优惠方案设置成功");
                });
              } else {
                this.msgError("直降规则下无方案");
              }
            }
          }
          this.getPay();
        }
      });
    },
    discountSettingChang(e) {
      this.discountSetting = e;
      this.getList();
    },
    getList() {
      const query = {
        pageNum: 1,
        pageSize: 10,
        discountPlanType: this.discountSetting,
      };
      listPlan(query).then((response) => {
        this.discountList = response.rows;
        console.log(this.discountList);
        this.total = response.total;
      });
    },
    vipDiscountyPlusFotmat(row, column) {
      if (row.vipDiscountyPlus === "1") {
        return "是";
      } else if (row.vipDiscountyPlus === "0") {
        return "否";
      }
    },
    couponPlusFotmat(row, column) {
      if (row.couponPlus === "1") {
        return "是";
      } else if (row.couponPlus === "0") {
        return "否";
      }
    },
    handleUpdateClick() {
      this.openDialog = true;
      this.updateForm = {
        discountPlanType: this.discountSetting,
      };
    },
    handleSubmit() {
      this.$refs["updateForm"].validate((valid) => {
        if (valid) {
          if (this.updateForm.id != null) {
            updatePlan(this.updateForm).then((response) => {
              this.msgSuccess("修改成功");
              this.openDialog = false;
              this.getList();
            });
          } else {
            addPlan(this.updateForm).then((response) => {
              this.msgSuccess("新增成功");
              this.openDialog = false;
              this.getList();
            });
          }
        }
      });
    },
    cancelSubmit() {
      this.openDialog = false;
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row.id;
      this.title = "修改满减优惠";
      this.openDialog = true;
      this.updateForm = row;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id;
      this.$confirm("是否确认删除满减优惠方案?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delPlan(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    // /** 导出按钮操作 */
    // handleExport() {
    //   const queryParams = this.queryParams;
    //   this.$confirm("是否确认导出所有优惠设置数据项?", "警告", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消",
    //     type: "warning",
    //   })
    //     .then(function () {
    //       return exportPlan(queryParams);
    //     })
    //     .then((response) => {
    //       this.download(response.msg);
    //     });
    // },
  },
};
</script>
<style>
</style>
