<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">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-form-item
        label="是否开启积分"
        label-width="160px"
        prop="integralFlag"
      >
        <el-radio-group v-model="form.integralFlag">
          <el-radio label="0">关闭</el-radio>
          <el-radio label="1">开启</el-radio>
        </el-radio-group>
      </el-form-item>
      <div v-show="form.integralFlag == 1">
        <el-form-item
          label="积分规则"
          prop="itemsDetail"
          :required="form.integralFlag == 1"
        >
          <div
            v-for="(item, index) in form.itemsDetail"
            :key="index"
            style="border: 1px solid"
          >
            <div>
              适用油品
              <el-select
                v-model="item.oilName"
                placeholder="请选择油品"
                clearable
                size="small"
                @change="oilNameChang(item, index)"
              >
                <el-option
                  v-for="ele in oilNameOptions"
                  :key="ele.oilName"
                  :label="ele.oilName"
                  :value="ele.oilName"
                ></el-option>
              </el-select>
            </div>
            <div v-if="item.oilType != 3">
              规则类型
              <el-select
                v-model="item.ruleType"
                placeholder="请选择规则"
                clearable
                size="small"
              >
                <el-option label="以订单实付累计" value="1"></el-option>
                <el-option label="以订单应付累计" value="2"></el-option>
                <el-option label="以加油升数累计" value="3"></el-option>
              </el-select>
            </div>
            <div v-if="item.oilType != 3">
              适用等级
              <el-select
                v-model="item.grade"
                placeholder="请选择等级"
                clearable
                size="small"
                @change="gradeChange(item)"
              >
                <el-option
                  v-for="ele in item.gradeList || []"
                  :key="ele.id"
                  :label="ele.grade"
                  :value="ele.id.toString()"
                ></el-option>
                <el-option key="0" label="所有人" value="0"></el-option>
              </el-select>
            </div>
            <div>
              满
              <el-input-number
                v-model="item.ruleTerms"
                :min="0"
                size="small"
              />元（L） 开始积分
            </div>
            <div>
              每消费
              <el-input-number
                v-model="item.saleAmt"
                size="small"
                :min="0"
              />元获得
              <el-input-number
                v-model="item.integral"
                size="small"
                :min="0"
              />积分
            </div>
            <div>
              <el-button type="danger" @click="delItem(index)" size="small"
                >删除</el-button
              >
              <el-button
                v-show="index == form.itemsDetail.length - 1"
                type="success"
                @click="addItem()"
                size="small"
                >新增</el-button
              >
            </div>
          </div>
        </el-form-item>

        <el-form-item
          label="积分有效期"
          prop="integralTermSetting"
          :required="form.integralFlag == 1"
        >
          <el-radio-group v-model="form.integralTermSetting">
            <el-radio label="1">永久有效</el-radio>
            <el-radio label="2">指定清空积分时间</el-radio>
          </el-radio-group>
          <div v-show="form.integralTermSetting == 2">
            <el-date-picker
              clearable
              size="small"
              style="width: 200px; margin-left: 10px"
              v-model="form.integralEmptyTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
            >
            </el-date-picker>
          </div>
        </el-form-item>

        <el-form-item
          label="积分规则时限"
          prop="termDateManage"
          :required="form.integralFlag == 1"
        >
          <el-radio-group v-model="form.termDateManage">
            <el-radio label="1">永久有效</el-radio>
            <el-radio label="2">指定活动结束时间</el-radio>
          </el-radio-group>
          <div v-show="form.termDateManage == 2">
            <el-date-picker
              clearable
              size="small"
              style="width: 200px; margin-left: 10px"
              v-model="form.emptyDate"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
            >
            </el-date-picker>
          </div>
        </el-form-item>
        <el-form-item
          label="多倍积分"
          prop="integralActivity"
          :required="form.integralFlag == 1"
        >
          <el-radio-group v-model="form.integralActivity">
            <el-radio label="0">关闭</el-radio>
            <el-radio label="1">开启</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="周期类型"
          prop="datePicker"
          :required="form.integralActivity == 1"
          v-show="form.integralActivity == 1"
        >
          <el-select
            v-model="form.datePicker"
            clearable
            size="small"
            @change="timeClear"
          >
            <el-option label="每周指定日" value="1"></el-option>
            <el-option label="每月指定日" value="2"></el-option>
            <el-option label="固定活动日" value="3"></el-option>
          </el-select>
          <div
            v-show="form.datePicker != 3"
            style="
              display: flex;
              flex-wrap: wrap;
              border-style: solid;
              border-color: #f5f7fa;
            "
          >
            <div
              v-for="(item, index) in timeSelect[form.datePicker]"
              :key="index"
              style="margin: 3px"
            >
              <div
                class="hover-style"
                style="
                  border-radius: 5px;
                  font-weight: bold;
                  font-size: 12px;
                  cursor: pointer;
                "
                @click="clickCalendar(index)"
              >
                <div>{{ item }}</div>
                <div
                  v-if="form.collectClickCalendar.indexOf(index) > -1"
                  style="
                    width: 4px;
                    height: 4px;
                    border-radius: 50%;
                    background-color: red;
                    position: relative;
                    left: calc(50% - 2px);
                  "
                ></div>
                <div v-else style="width: 4px; height: 4px"></div>
              </div>
            </div>
          </div>
          <div v-show="form.datePicker == 3">
            <el-date-picker
              clearable
              size="small"
              style="margin-left: 10px; width: 200px"
              v-model="form.collectClickDay"
              type="dates"
              value-format="yyyy-MM-dd"
              placeholder="选择提醒时间设置"
            >
            </el-date-picker>
          </div>
        </el-form-item>
        <el-form-item
          label="积分比例"
          prop="integralProportion"
          v-show="form.integralActivity == 1"
          :required="form.integralActivity == 1"
        >
          <el-input-number
            v-model="form.integralProportion"
            :min="1"
            placeholder="请输入加倍比例"
            size="small"
          />
          <span>倍</span>
        </el-form-item>
        <el-form-item> </el-form-item>
        <el-row v-show="form.integralActivity == 1">
          <el-col :span="8" style=""> </el-col>

          <el-col :span="8"> </el-col>
        </el-row>
        <el-form-item label="积分轮播图" prop="imgFileList">
          <el-upload
            class="avatar-uploader"
            :action="addressUrl"
            :headers="headers"
            multiple
            list-type="picture-card"
            :limit="5"
            :file-list="form.imgFileList"
            accept="image/gif,image/jpeg,image/png,image/jpg,image/bmp"
            :before-upload="beforeAvatarUpload"
            :on-remove="handleRemove"
            :on-success="handlepaymentSuccess"
          >
            <i class="el-icon-plus"></i>
            <div class="el-upload__tip" slot="tip">
              只能上传jpg/png文件，最多上传5张且单张图片不超过1M
            </div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible" append-to-body>
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>
      </div>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm" :disabled="false"
        >确 定</el-button
      >
    </div>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
// import { queryPageStatus } from "@/utils/pageStatus";

import {
  addRule,
  updateRule,
  oilNameList,
  gradeList,
  listRuleOne,
} from "@/api/integral/rule";
import { getStationPay, updatePay } from "@/api/station/pay";
import { queryOilType } from "@/utils/oil";

export default {
  name: "Point_Rule",
  data() {
    let validateItemsDetail = (rule, value, callback) => {
      if (this.form.itemsDetail.length <= 0) {
        callback(new Error("请先配置设置规则"));
        return;
      }
      this.form.itemsDetail.forEach((ele) => {
        if (!ele.oilName || !ele.ruleTerms || !ele.saleAmt || !ele.integral) {
          callback(new Error("请检查规则完整性"));
          return;
        }
        if (ele.oilType != 3) {
          if (!ele.ruleType || ele.grade === undefined || ele.grade === "") {
            callback(new Error("请检查规则完整性"));
            return;
          }
        }
      });
      callback();
    };
    let validateIntegralTermSetting = (rule, value, callback) => {
      if (!this.form.integralTermSetting) {
        callback(new Error("请选择积分有效期"));
        return;
      }
      if (this.form.integralTermSetting == 2) {
        if (!this.form.integralEmptyTime) {
          callback(new Error("请填写积分指定的到期时间"));
          return;
        }
      }
      callback();
    };
    let validateTermDateManage = (rule, value, callback) => {
      if (!this.form.termDateManage) {
        callback(new Error("请选择积分活动的结束时间"));
        return;
      }
      if (this.form.termDateManage == 2) {
        if (!this.form.emptyDate) {
          callback(new Error("请填写积分活动的结束时间"));
          return;
        }
      }
      callback();
    };
    let validateDatePicker = (rule, value, callback) => {
      if (this.form.integralActivity == 0) {
        callback();
        return;
      }
      if (!this.form.datePicker) {
        callback(new Error("请选择多倍积分的周期类型"));
        return;
      }
      if (this.form.datePicker == 1 || this.form.datePicker == 2) {
        if (this.form.collectClickCalendar.length <= 0) {
          callback(new Error("请选择多倍积分的时间"));
          return;
        }
      }
      if (this.form.datePicker == 3) {
        if (
          this.form.collectClickDay == null ||
          this.form.collectClickDay.length <= 0
        ) {
          callback(new Error("请填写指定的多倍积分日"));
          return;
        }
      }
      callback();
    };
    return {
      oilNameOptions: [],
      dialogImageUrl: "",
      num: 0,
      dialogVisible: false,
      // 表单参数
      form: {
        itemsDetail: [{}],
        imgFileList: [],
        collectClickCalendar: [], // 收集固定日期选择的日子
        collectClickDay: [],
      },
      rules: {
        integralFlag: [
          { required: true, message: "请选择是否开启积分", trigger: "change" },
        ],
        integralTermSetting: [
          { validator: validateIntegralTermSetting, trigger: "change" },
        ],
        // termDateManage:[{ required: true, message: "请选择是否开启积分", trigger: "change" }],
        // integralActivity:[{ required: true, message: "请选择是否开启积分", trigger: "change" }],
        imgFileList: [{ required: true, message: "", trigger: "change" }],
        itemsDetail: [{ validator: validateItemsDetail, trigger: "change" }],
        termDateManage: [
          { validator: validateTermDateManage, trigger: "change" },
        ],
        datePicker: [{ validator: validateDatePicker, trigger: "change" }],
      },
      headers: {
        Authorization: "Bearer " + getToken(),
      },

      timeSelect: [
        ,
        ["周天", "周一", "周二", "周三", "周四", "周五", "周六"],
        [
          "01",
          "02",
          "03",
          "04",
          "05",
          "06",
          "07",
          "08",
          "09",
          "10",
          "11",
          "12",
          "13",
          "14",
          "15",
          "16",
          "17",
          "18",
          "19",
          "20",
          "21",
          "22",
          "23",
          "24",
          "25",
          "26",
          "27",
          "28",
          "29",
          "30",
          "31",
        ],
      ],
      addressUrl:
        location.protocol +
        "//" +
        location.host +
        process.env.VUE_APP_BASE_API +
        "/common/upload",
      pageStatus: 0,
    };
  },
  created() {
    this.init();
    this.setPageStatus();
  },
  methods: {
    init() {
      this.listRule();
      this.listOilName();
    },
    setPageStatus() {
      this.queryPageStatus([1, 2], 1).then((res) => {
        this.pageStatus = res;
      });
    },
    listOilName() {
      oilNameList({
        pageNum: 1,
        pageSize: 100,
      }).then((response) => {
        this.oilNameOptions = response.rows;
      });
    },
    listRule() {
      listRuleOne({
        pageNum: 1,
        pageSize: 100,
      }).then((response) => {
        this.form = response.data;
        this.form.collectClickCalendar = [];
        this.form.collectClickDay = "";
        if (!this.form.itemsDetail || this.form.itemsDetail.length == 0) {
          this.form.itemsDetail = [{}];
        }
        if (this.form.datePicker == "1" || this.form.datePicker == "2") {
          // if( this.form.datePickerTime == ""){
          //   this.form.collectClickCalendar = [];
          // }
          this.form.collectClickCalendar = this.form.datePickerTime
            .split(",")
            .map(parseFloat);
        } else if (this.form.datePicker == "3") {
          if (this.form.datePickerTime.length == 0) {
            this.form.collectClickDay = [];
          } else {
            this.form.collectClickDay = this.form.datePickerTime.split(",");
          }
        }
        this.form = { ...this.form };
      });
    },
    timeClear() {
      this.form.collectClickCalendar = [];
      this.form.collectClickDay = [];
    },
    gradeChange(item) {
      setTimeout(() => {
        this.form = { ...this.form };
      }, 0);
    },
    //添加行
    addItem() {
      this.form.itemsDetail.push({});
    },
    // 删除行
    delItem(index) {
      this.form.itemsDetail.splice(index, 1);
      if (this.form.itemsDetail.length <= 0) {
        this.form.itemsDetail = [{}];
      }
    },
    delNoil() {
      this.form.notOilList = [{}];
    },
    oilNameChang(item, index) {
      item.grade = "";
      item.gradeList = [];
      this.form = { ...this.form };
      gradeList({
        oilName: item.oilName,
      }).then((response) => {
        item.gradeList = response.rows;
        this.form = {
          ...this.form,
        };
      });
      queryOilType(item.oilName).then((res) => {
        item.oilType = res;
        this.form = {
          ...this.form,
        };
      });
    },
    handleRemove(file, fileList) {
      if (fileList != null && fileList.length > 0) {
        this.form.imgFileList = [];
        for (let i = 0; i < fileList.length; i++) {
          let fileName = fileList[i].name;
          let imgurl = fileList[i].url;
          this.form.imgFileList.push({
            name: fileName,
            url: imgurl,
          });
        }
      } else {
        this.form.imgFileList = fileList;
      }
    },
    beforeAvatarUpload(file) {
      const isLt5M = file.size / 1024 / 1024 < 1;
      if (!isLt5M) {
        this.$message.error("上传头像图片大小不能超过 1MB!");
      }
      return isLt5M;
    },
    //上传成功
    handlepaymentSuccess(response, file, fileList) {
      let imgurl =
        location.protocol +
        "//" +
        location.host +
        process.env.VUE_APP_BASE_API +
        response.fileName;
      this.form.imgFileList.push({
        name: file.name,
        url: imgurl,
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.datePicker == "1" || this.form.datePicker == "2") {
            this.form.datePickerTime = this.form.collectClickCalendar.toString();
          } else {
            this.form.datePickerTime = this.form.collectClickDay.toString();
          }

          if (this.form.id != null) {
            updateRule(this.form).then((response) => {
              this.msgSuccess("更新成功");
            });
          } else {
            addRule(this.form).then((response) => {
              this.msgSuccess("新增成功");
            });
          }
        }
      });
    },

    clickCalendar(index) {
      if (this.form.collectClickCalendar.indexOf(index) === -1) {
        this.form.collectClickCalendar.push(index);
      } else if (this.form.collectClickCalendar.indexOf(index) > -1) {
        const temp = this.form.collectClickCalendar.findIndex((ele) => {
          return ele == index;
        });
        this.form.collectClickCalendar.splice(temp, 1);
      }
      this.$refs.form.validateField("datePicker");
      this.form = { ...this.form };
    },
  },
};
</script>

<style scoped>
.hover-style:hover {
  color: white;
  background-color: blue;
}
</style>
