<template>
  <div>
    <el-dialog
      :title="isView ? '价格新增' : '价格编辑'"
      :visible.sync="dialogVisible"
      :before-close="cancle"
      width="60%"
    >
      <el-form
        :inline="true"
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-row>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-form-item label="标题" prop="title">
              <el-input
                v-model="ruleForm.title"
                class="inputCom"
                placeholder="请输入标题"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-form-item label="价格" prop="price">
              <el-input-number
                v-model="ruleForm.price"
                class="inputCom"
                placeholder="请输入价格"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-form-item label="次数起始(包含)" prop="beginNum">
              <el-input-number
                v-model="ruleForm.beginNum"
                class="inputCom"
                placeholder="请输入次数起始"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-form-item label="次数结束(包含)" prop="endNum">
              <el-input-number
                v-model="ruleForm.endNum"
                class="inputCom"
                placeholder="请输入次数结束"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="ruleForm.status" placeholder="请选择状态">
                <el-option
                  :label="item.name"
                  :value="item.state"
                  v-for="item in stateList"
                  :key="item.state"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-form-item label="渠道级别" prop="channelLevel ">
              <el-select v-model="ruleForm.channelLevel" placeholder="请选择渠道级别">
                <el-option
                  :label="item.name"
                  :value="item.level"
                  v-for="item in channelLevelList"
                  :key="item.level"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancle" round>取 消</el-button>
        <el-button
          v-show="isView"
          type="primary"
          round
          :disabled="disableFlag"
          @click="submitCom"
          >确 定</el-button
        >
        <el-button
          v-show="!isView"
          type="primary"
          round
          :disabled="disableFlag"
          @click="submitCom"
          >修 改</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
// import { oSessionStorage } from "../../utils/utils";
import { oSessionStorage } from "../utils/utils";
import { basePath } from "../utils/http";
import md5 from "md5";
export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (value.length < 6) {
        callback(new Error("密码至少6位"));
      } else {
        callback();
      }
    };
    var validatePhone = (rule, value, callback) => {
      let myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else if (!myreg.test(value)) {
        callback(new Error("请输入正确格式"));
      } else {
        callback();
      }
    };
    return {
      action: "",
      disableFlag: false,
      phoneFlag: false,
      flag: 3,
      dialogVisible: false,
      //渠道列表
      stateList: [
        { name: "生效中", state: "1" },
        { name: "已停用", state: "0" },
      ],
      //渠道级别
      channelLevelList: [
        { name: "级别1", level: "1" },
        { name: "级别2", level: "2" },
      ],
      ruleForm: {
        id: "",
        //标题
        title: "",
        //价格
        price: "",
        //起始次数
        beginNum: "",
        //结束次数
        endNum: "",
        //状态
        status: "",
        //渠道级别
        channelLevel: "",
      },
      isView: true,
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        price: [{ required: true, message: "请输入价格", trigger: "blur" }],
        beginNum: [{ required: true, message: "请输入起始次数", trigger: "blur" }],
        endNum: [{ required: true, message: "请输入结束次数", trigger: "blur" }],
        status: [{ required: true, message: "请选择状态", trigger: "change" }],
      },
    };
  },
  mounted() {
    let userInfo = JSON.parse(oSessionStorage.getItem("userInfo"));
    this.ruleForm.parentCode = userInfo.invitationCode;
    this.action = basePath + "/file/customUpload";
    //获取到router 传输过来的信息
    this.ruleForm.channelId = this.$route.query.channelId;

    //获取渠道信息

    // this.ruleForm.type = "3";
  },
  methods: {
    disableFlagStatus() {
      setTimeout(() => {
        this.disableFlag = false;
      }, 1500);
    },
    beforeAvatarUpload(file) {
      const fileName = file.name;
      const fileType = fileName.substring(fileName.lastIndexOf("."));
      if (fileType !== ".jpg" && fileType !== ".jpeg" && fileType !== ".png") {
        // alert("请上传jpg、jpge或png的图片！");
        this.$message.error("请上传jpg、jpge或png的图片！");
        return false;
      }
      return true;
    },
    //handleAvatarSuccess
    //上传成功后的回调
    handleAvatarSuccess(data) {
      if (data.code == 200) {
        this.ruleForm.avatar = basePath + "/file/show?filePath=" + data.data;
        console.log(basePath + "/file/show?filePath=" + data.data);
      } else {
        //失败
      }
    },
    phoneCheck() {
      //判断是否重复
      this.$http.get(`v1/system/checkPhone/${this.ruleForm.phone}`, {}, (res) => {
        //  this.$toast.success({message:'成功'});
        if (res && res.code == 200) {
          if (res.data) {
            this.phoneFlag = true;
          } else {
            this.phoneFlag = false;
            // this.$toast.success({ message: "手机号重复" });
            this.$message.warning("手机号重复");
          }
        } else {
          // this.$toast.fail({ message: res.msg });
          this.$message.error(res.msg);
        }
      });
    },
    timeChange(val) {
      if (val !== null) {
        //根据时间得到格式化的数据
        this.ruleForm.birthDate = this.formatterTime(val);
      }
    },
    formatterTime(val) {
      let date = new Date(val);
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      month = this.formatterMon(month);
      let day = date.getDate();
      day = this.formatterMon(day);
      return year + "-" + month + "-" + day;
    },
    formatterMon(val) {
      if (val < 10) {
        return "0" + val;
      } else {
        return val;
      }
    },
    open(val) {
      this.cancle();
      this.dialogVisible = true;
      this.isView = val;

      this.$nextTick(() => {
        this.$refs["ruleForm"].clearValidate();
      });
    },
    edit(val) {
      this.dialogVisible = true;
      this.isView = false;
      this.ruleForm.id = val.id;
      this.ruleForm.title = val.title;
      this.ruleForm.price = val.price;
      this.ruleForm.beginNum = val.beginNum;
      this.ruleForm.endNum = val.endNum;
      this.ruleForm.status = val.status;
      this.ruleForm.channelLevel = val.channelLevel;
      console.log(val.channelLevel)
    },
    cancle() {
      //清空表单

      this.ruleForm.id = "";
      this.ruleForm.title = "";
      this.ruleForm.price = "";
      this.ruleForm.beginNum = "";
      this.ruleForm.endNum = "";
      this.ruleForm.status = "";
      this.ruleForm.channelLevel = "";
      this.$refs["ruleForm"].clearValidate();
      this.dialogVisible = false;
    },
    submitCom() {
      if (this.disableFlag) {
        return;
      }
      this.disableFlag = true;
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          this.disableFlag=true;
          //判断是编辑还是新增
          if (this.isView) {
            this.register();
          } else {
            this.editUserFun();
          }

          //都校验通过后可以触发注册接口了
          //调用方法进行入参
        }else{
          this.disableFlagStatus()
        }
      });
    },
    register() {
      let that = this;
      this.$http.post(
        `/price/save`,
        {
          title: this.ruleForm.title,
          price: this.ruleForm.price,
          beginNum: this.ruleForm.beginNum,
          endNum: this.ruleForm.endNum,
          status : this.ruleForm.status ,
          channelLevel: this.ruleForm.channelLevel,
          // ...this.ruleForm, //解构对象
        },
        (res) => {
          this.disableFlagStatus()
          if (res && res.code == 200) {
            this.dialogVisible = false;
            this.$message.success(res.msg);
            // this.$toast.success({ message: "成功" });
            //调用父组件的查询方法
            that.$emit("search");
          } else {
            // this.$toast.fail({ message: res.msg });
            this.$message.error(res.msg);
          }
          //清空缓存
          this.cancle();
        }
      );
    },
    editUserFun() {
      let that = this;
      this.$http.post(
        `/price/update`,
        {
          ...this.ruleForm,
          // ...this.ruleForm, //解构对象
        },
        (res) => {
          this.disableFlagStatus()
          if (res && res.code == 200) {
            this.dialogVisible = false;
            // this.$toast.success({ message: "成功" });
            //调用父组件的查询方法
            that.$emit("search");
            this.$message.success("修改成功");
          } else {
            // this.$toast.fail({ message: res.msg });
            this.$message.error(res.msg);
          }
          //清空缓存
        }
      );
    },
  },
};
</script>
<style scoped>
.inputCom {
  width: 200px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px solid;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
