<template>
  <div class="tab3Add">
    <div class="insideTop">
      学籍管理 > {{ruleForm.id?'编辑':'新增'}}学籍信息
      <div class="add">
        <el-button type="primary" @click="goBack">返 回</el-button>
      </div>
    </div>
    <div class="obstruct"></div>
    <!-- 主要内容 -->
    <div class="conten">
      <div class="con_top">基本信息</div>
      <!-- 表单 -->
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item label="姓名：" prop="name">
          <el-input
            v-model="ruleForm.name"
            maxlength="25"
            show-word-limit
            style="width: 500px"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别：" prop="sex">
          <el-radio v-model="ruleForm.sex" label="M">男</el-radio>
          <el-radio v-model="ruleForm.sex" label="F">女</el-radio>
        </el-form-item>
        <el-form-item label="政治面貌：" prop="politics">
          <el-select
            v-model="ruleForm.politics"
            placeholder="请选择"
            style="width: 500px"
          >
            <el-option label="中共党员" value="中共党员"></el-option>
            <el-option label="中共预备党员" value="中共预备党员"></el-option>
            <el-option label="共青团员" value="共青团员"></el-option>
            <el-option label="民革党员" value="民革党员"></el-option>
            <el-option label="民盟盟员" value="民盟盟员"></el-option>
            <el-option label="民建会员" value="民建会员"></el-option>
            <el-option label="民进会员" value="民进会员"></el-option>
            <el-option label="农工党党员" value="农工党党员"></el-option>
            <el-option label="致公党党员" value="致公党党员"></el-option>
            <el-option label="九三学社社员" value="九三学社社员"></el-option>
            <el-option label="台盟盟员" value="台盟盟员"></el-option>
            <el-option label="无党派人士" value="无党派人士"></el-option>
            <el-option label="群众" value="群众"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学籍号：" prop="num">
          <el-input
            v-model="ruleForm.num"
            maxlength="25"
            show-word-limit
            style="width: 500px"
          ></el-input>
        </el-form-item>
        <el-form-item label="专业：" prop="job">
          <el-input
            v-model="ruleForm.job"
            maxlength="25"
            show-word-limit
            style="width: 500px"
          ></el-input>
        </el-form-item>
        <el-form-item label="学年：">
          <i class="biaoshi biaoshi1"></i>
          <el-date-picker
            style="width: 500px"
            v-model="time"
            type="monthrange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <!-- 图片和附件 -->
        <el-form-item label="学生照片">
          <i class="biaoshi biaoshi2"></i>
          <el-upload
            class="avatar-uploader"
            :action="baseURL + '/cms/student/upload'"
            :headers="{
              token,
            }"
            :show-file-list="true"
            :before-upload="beforethumbUpload"
            :on-success="upload_thumb_success"
          >
            <div v-if="ruleForm.thumb" class="imgdiv">
              <img
                style="max-width: 200px; max-height: 200px;display: block;"
                :src="baseURL + ruleForm.thumb"
              />
              <i
                class="el-icon-circle-close"
                @click.stop="ruleForm.thumb = ''"
              ></i>
            </div>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <p class="upHint">
            格式要求：支持png、jpg、gif和jpeg的图片格式；最大支持20M。
          </p>
        </el-form-item>
      </el-form>
      <!-- 富文本 -->
      <div class="con_top">校园动态</div>
      <div id="div1" style="z-index: 1"></div>
      <!-- 底部按钮 -->
      <div class="con_btn">
        <el-button type="primary"  @click="saveLeader">保 存</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { studentSave, studentDetail } from '@/apis/tab3'
import axios from '@/utils/request'
import E from 'wangeditor'
export default {
  name: 'tab3Add',
  components: {},
  data () {
    // 这里存放数据
    return {
      time: '',
      // 服务器前缀地址
      baseURL: '',
      token: '',
      ruleForm: {
        name: '',
        sex: 'M',
        politics: '',
        num: '',
        job: '',
        thumb: ''
      },
      rules: {
        name: [{ required: true, message: '不能为空', trigger: 'blur' }],
        sex: [{ required: true, message: '不能为空', trigger: 'blur' }],
        politics: [{ required: true, message: '不能为空', trigger: 'change' }],
        num: [{ required: true, message: '不能为空', trigger: 'blur' }],
        job: [{ required: true, message: '不能为空', trigger: 'blur' }]
      }
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {
  },
  // 方法集合
  methods: {
    // 点击保存
    async saveLeader () {
      if (this.ruleForm.thumb === '') { return this.$message.warning('图片不能为空') }
      if (!this.time) { return this.$message.warning('学年不能为空') }
      if (this.editor.txt.html() === '') { return this.$message.warning('校园动态不能为空') }
      try {
        await this.$refs.ruleForm.validate()
        const obj = { ...this.ruleForm, description: this.editor.txt.html(), tenure: this.time[0] + ',' + this.time[1] }
        const res = await studentSave(obj)
        if (res.code === 0) {
          this.$message.success('操作成功')
          this.$router.push('/layout/tab3')
        } else this.$message.warning(res.msg)
        // console.log(998, obj)
      } catch (error) {
        console.log(error)
        this.$message.warning('有字段不符合要求')
      }
    },
    // 上传图片
    beforethumbUpload (file) {
      // console.log(998, file)
      // 限制图片大小和格式
      const sizeOk = file.size / 1024 / 1024 < 20
      const typeOk =
        file.type === 'image/png' ||
        file.type === 'image/jpeg' ||
        file.type === 'image/gif'

      return new Promise((resolve, reject) => {
        if (!typeOk) {
          this.$message.error('照片格式有误！')
          reject(file)
        } else if (!sizeOk) {
          this.$message.error('照片大小超过20M！')
          reject(file)
        } else if (file.name.length > 32) {
          this.$message.error('照片名字不能超过32个字！')
          reject(file)
        } else {
          this.$message.success('上传成功')
          resolve(file)
        }
      })
    },
    upload_thumb_success (data) {
      // console.log('图片上传成功', data.data.urlPath)
      this.ruleForm.thumb = data.data.urlPath
    },
    // 点击返回
    goBack () {
      this.$confirm('点击返回后，编辑的信息将无法保存，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.$router.push('/layout/tab3')
        })
        .catch(() => {
          this.$message.info('已取消')
        })
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {
    // 获取服务器前缀地址
    this.baseURL = axios.defaults.baseURL
    // 获取用户token
    this.token = localStorage.getItem('CQLJXU_token')
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  async mounted () {
    // 初始化富文本
    // 富文本
    this.editor = new E('#div1')
    // 配置字体
    this.editor.config.fontNames = [
      '黑体',
      '仿宋',
      '楷体',
      '标楷体',
      '华文仿宋',
      '华文楷体',
      '宋体',
      '微软雅黑',
      'Arial',
      'Tahoma',
      'Verdana',
      'Times New Roman'
    ]
    this.editor.config.uploadImgShowBase64 = true // 图片地址
    this.editor.config.showLinkVideo = false
    this.editor.create()
    // 如果是编辑
    if (this.$route.query.id) {
      const res = await studentDetail(Number(this.$route.query.id))
      this.ruleForm = res.data
      console.log(998, res)
      // 富文本回显
      this.editor.txt.html(res.data.description)
      // 日期回显
      this.time = res.data.tenure.split(',')
    }
  },
  beforeCreate () {}, // 生命周期 - 创建之前
  beforeMount () {}, // 生命周期 - 挂载之前
  beforeUpdate () {}, // 生命周期 - 更新之前
  updated () {}, // 生命周期 - 更新之后
  beforeDestroy () {}, // 生命周期 - 销毁之前
  destroyed () {}, // 生命周期 - 销毁完成
  activated () {} // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang='less' scoped>
.tab3Add {
  height: 100%;
  .conten {
  padding-bottom: 10px;
  overflow-y: auto;
    height: calc(100% - 32px);
    .con_top {
      margin-bottom: 12px;
      height: 40px;
      line-height: 40px;
      padding-left: 20px;
      background-color: #fbfbfb;
    }
    .biaoshi1::before {
      left: -64px;
      top: -10px;
    }
    .biaoshi2::before {
      left: -78px;
    }
    /deep/.el-icon-plus {
      border: 1px dashed #ccc;
    }
    .avatar-uploader .el-upload {
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #3e5eb3;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    #div1{
      width: 85%;
      margin: 0 auto;
    }
    .con_btn {
      width: 80px;
      margin: 15px auto 0;
    }
    .imgdiv {
      max-width: 200px;
      max-height: 200px;
      &>img{
        border: 10px solid #ccc;
      }
    }
    .el-icon-circle-close {
      font-size: 24px;
    }
  }
}
</style>
