<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="unuse">
              <el-input-number
                v-model="ruleForm.unuse"
                class="inputCom"
                :min="0"
                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="rechargeUsed">
              <el-input-number
                v-model="ruleForm.rechargeUsed"
                class="inputCom"
                  :min="0"
                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="rechargeCount">
              <el-input-number
                v-model="ruleForm.rechargeCount"
                class="inputCom"
                :min="0"
                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="signAmount">
              <el-input-number
               :min="0"
                v-model="ruleForm.signAmount"
                class="inputCom"
                placeholder="请输入签约单次金额"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-form-item label="海报背景图" prop="background">
              <el-upload
                accept=".png, .jpg, .jpeg"
                class="avatar-uploader"
                name="file"
                :action="action"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="ruleForm.background" :src="ruleForm.background" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                <div class="el-upload__tip" slot="tip">
                  海报背景图建议上传720*1280分辨率图片
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
          
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="info" round @click="cancle">取 消</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();
      }
    };
    return {
      channelList: [],
      action: "",
      disableFlag: false,
      phoneFlag: false,
      flag: 3,
      dialogVisible: false,
      //渠道列表
      statusList: [
        { name: "签约", status: "1" },
        { name: "解约", status: "0" },
      ],
      selfPageList:[
        { name: "是", status: "1" },
        { name: "否", status: "0" },
      ],
      ruleForm: {
        id: "",
        //渠道id
        channelId: "",
        //渠道名字
        channelName:'',
        //已使用次数
        used:'',
        //单次价格
        singlePrice:'',
        //充值使用次数
        rechargeUsed:'',
        //剩余次数
        unuse:'',
        //累计充值次数
        rechargeCount:'',
        //签约单次金额
        signAmount:'',
        //有效时间起
        effectiveDate:'',
        //有效时间止
        expirationDate:'',
        //签约状态
        status:'',
        //自定义收尾页
        selfPage:'',
        //备注
        remarks:'',
        //背景图地址
        background:'',
        //海报
        poster:'',
        isDelete:'0'
      },
      isView: true,
      rules: {
        singlePrice: [{ required: true, message: "请输入单次价格", trigger: "blur" }],
        used: [{ required: true, message: "请输入已使用次数", trigger: "blur" }],
        rechargeUsed: [{ required: true, message: "请输入充值使用次数", trigger: "blur" }],
        unuse: [{ required: true, message: "请输入剩余次数", trigger: "blur" }],
        rechargeCount: [{ required: true, message: "请输入累计充值次数", trigger: "blur" }],
        signAmount: [{ 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";
    //获取渠道信息
    this.getChannel();

    // this.ruleForm.type = "3";
    this.getChannel();
  },
  methods: {
    disableFlagStatus() {
      setTimeout(() => {
        this.disableFlag = false;
      }, 1500);
    },
    getChannel() {
      this.$http.get(`/channel/findAll`, {}, (res) => {
        //  this.$toast.success({message:'成功'});
        if (res && res.code == 200) {
          //将值赋值给list
          this.channelList = res.data;
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    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.background = 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.channelId=val.channelId;
      this.ruleForm.channelName=val.channelName;
      this.ruleForm.used=val.used;
      this.ruleForm.singlePrice=val.singlePrice;
      this.ruleForm.rechargeUsed=val.rechargeUsed;
      this.ruleForm.unuse=val.unuse;
      this.ruleForm.rechargeCount=val.rechargeCount;
      this.ruleForm.signAmount=val.signAmount;
      this.ruleForm.effectiveDate=val.effectiveDate;
      this.ruleForm.expirationDate=val.expirationDate;
      this.ruleForm.status=val.status;
      this.ruleForm.selfPage=val.selfPage;
      this.ruleForm.remarks=val.remarks;
      this.ruleForm.background=val.background;
      this.ruleForm.poster=val.poster;
    },
    cancle() {
      //清空表单
      this.ruleForm.id=''
      this.ruleForm.channelId=''
      this.ruleForm.channelName=''
      this.ruleForm.used=''
      this.ruleForm.singlePrice=''
      this.ruleForm.rechargeUsed=''
      this.ruleForm.unuse=''
      this.ruleForm.rechargeCount=''
      this.ruleForm.signAmount=''
      this.ruleForm.effectiveDate=''
      this.ruleForm.expirationDate=''
      this.ruleForm.status=''
      this.ruleForm.selfPage=''
      this.ruleForm.remarks=''
      this.ruleForm.background=''
      this.ruleForm.poster=''
      this.$refs["ruleForm"].clearValidate();
      this.dialogVisible = false;
    },
    submitCom() {
      if (this.disableFlag) {
        return;
      }
      this.disableFlag = true;
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          //判断是编辑还是新增
          if (this.isView) {
            this.register();
          } else {
            this.editUserFun();
          }

          //都校验通过后可以触发注册接口了
          //调用方法进行入参
        }else{
          this.disableFlagStatus()
        }
      });
    },
    getChannelName(){
      if(this.ruleForm.channelId==''){
        this.ruleForm.channelName=''
      }else{
        for(let i=0;i<this.channelList.length;i++){
          if(this.ruleForm.channelId==this.channelList[i].id){
            this.ruleForm.channelName=this.channelList[i].name;
          }
        }
      }
      
    },
    register() {

      this.getChannelName();

      let that = this;
      this.$http.post(
        `/sign/save`,
        {
          channelId: this.ruleForm.channelId,
          channelName: this.ruleForm.channelName,
          singlePrice: this.ruleForm.singlePrice,
          used:this.ruleForm.singlePrice,
          unuse:this.ruleForm.unuse,
          rechargeUsed:this.ruleForm.rechargeUsed,
          rechargeCount:this.ruleForm.rechargeCount,
          signAmount:this.ruleForm.signAmount,
          effectiveDate:this.ruleForm.effectiveDate,
          expirationDate:this.ruleForm.expirationDate,
          status:this.ruleForm.status,
          selfPage:this.ruleForm.selfPage,
          remarks:this.ruleForm.remarks,
          background:this.ruleForm.background,
          poster:this.ruleForm.poster,
          // ...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() {
      this.getChannelName();
      let that = this;
      this.$http.post(
        `/sign/save`,
        {
          ...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>
.el-date-picker__editor-wrap>>> .el-input{
  width:auto !important
}
.el-date-picker__editor-wrap>>> .el-input__inner{
  width:auto !important
}
</style>
<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>

