<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="channelId" >
              <el-select v-model="ruleForm.channelId" placeholder="请选择渠道">
                <el-option
                  :label="item.name"
                  :value="item.id"
                  v-for="item in channelList"
                  :key="item.id"
                ></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="companyName">
              <el-input
                v-model="ruleForm.companyName"
                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="tax">
              <el-input
                v-model="ruleForm.tax "
                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="reportType">
              <el-select disabled v-model="ruleForm.reportType" placeholder="请选择类型">
                <el-option
                  :label="item.name"
                  :value="item.state"
                  v-for="item in reportTypeList"
                  :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="staffName">
              <el-input disabled
                v-model="ruleForm.staffName "
                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 :disabled="true" label="状态" prop="status">
              <el-select disabled v-model="ruleForm.status" placeholder="请选择状态">
                <el-option
                  :label="item.name"
                  :value="item.status"
                  v-for="item in stateList"
                  :key="item.status"
                ></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 {
      channelList: [],
      action: "",
      disableFlag: false,
      phoneFlag: false,
      flag: 3,
      dialogVisible: false,
      //渠道列表
      stateList: [
        { name: "已生成", status: "1" },
        { name: "生成中", status: "0" },
      ],
      reportTypeList:[
        { name: "邀约使用", state: "1" },
        { name: "渠道使用", state: "2" },
        { name: "公众号使用", state: "3" }
      ],
      //渠道级别
      productlLevelList: [
        { name: "未完成", level: "1" },
        { name: "已完成", level: "2" },
      ],
      ruleForm: {
        id: "",
        //渠道id
        channelId:'',
        //渠道名称
        channelName:'',
        //公司名称
        companyName: "",
        //税号
        tax : "",
        //报告类型
        reportType:'',
        //生成时间
        createTime:'',
        //渠道员工
        staffName:'',
        //状态
        status: "",
        //授权状态
        authStatus : "",
      },
      isView: true,
      rules: {
        companyName: [{ required: true, message: "请输入产品名", trigger: "blur" }],
        tax: [{ required: true, message: "请输入报告名", trigger: "blur" }],
      },
    };
  },
  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.getChannel() 
    // this.ruleForm.type = "3";
  },
  methods: {
    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);
        }
      });
    },
    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;
          }
        }
      }
      
    },
    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.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.companyName = val.companyName;
      this.ruleForm.createTime = val.createTime;
      this.ruleForm.linkId = val.linkId;
      this.ruleForm.reportPath = val.reportPath;
      this.ruleForm.reportType  = val.reportType ;
      this.ruleForm.staffName = val.staffName;
      this.ruleForm.status = val.status;
      this.ruleForm.tax = val.tax;
      this.ruleForm.updateTime = val.updateTime;
      console.log(val.channelLevel)
    },
    cancle() {
      this.ruleForm.id ='';
      this.ruleForm.channelId ='';
      this.ruleForm.channelName = '';
      this.ruleForm.companyName = '';
      this.ruleForm.createTime = '';
      this.ruleForm.linkId = '';
      this.ruleForm.reportPath = '';
      this.ruleForm.reportType  = '';
      this.ruleForm.staffName = '';
      this.ruleForm.status ='';
      this.ruleForm.tax = '';
      this.ruleForm.updateTime = '';

      // this.ruleForm.id = "";
      // this.ruleForm.productName = "";
      // this.ruleForm.reportName = "";
      // this.ruleForm.price = "";
      // this.ruleForm.times = "";
      // this.ruleForm.status = "";
      // this.ruleForm.type = "";
      // this.ruleForm.description = "";
      // this.ruleForm.isDelete = "";
      this.$refs["ruleForm"].clearValidate();
      this.dialogVisible = false;
    },
    submitCom() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          //判断是编辑还是新增
          if (this.isView) {
            this.register();
          } else {
            this.editUserFun();
          }

          //都校验通过后可以触发注册接口了
          //调用方法进行入参
        }
      });
    },
    register() {
      let that = this;
      this.$http.post(
        `/product/save`,
        {
          productName: this.ruleForm.productName,
          reportName : this.ruleForm.reportName ,
          price : this.ruleForm.price ,
          times : this.ruleForm.times ,
          status : this.ruleForm.status ,
          type : this.ruleForm.type ,
          description  : this.ruleForm.description,
          isDelete:'0'
          // ...this.ruleForm, //解构对象
        },
        (res) => {
          this.disableFlag = false;
          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.getChannelName();
      this.$http.post(
        `/report/save`,
        {
          ...this.ruleForm,
          // ...this.ruleForm, //解构对象
        },
        (res) => {
          this.disableFlag = false;
          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);
          }
          //清空缓存
          this.cancle();
        }
      );
    },
  },
};
</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>
