<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-form :rules="rules" ref="dianPingddForm" :model="addDianping" label-position="left" label-width="120px"
              style='margin-left:20px'>
      <el-row :gutter="24" >
        <el-col :xs="23" :sm="23" :md="12" :lg="8" :xl="8">
          <div class="grid-content bg-purple">
            <el-form-item  :label="$t('wxmini.wd_username')" prop="wd_username">
              <div class="block">
                <el-input style="width: 100%;" class="filter-item" v-model="addDianping.wd_username" :maxlength = 20>
                </el-input>
              </div>
            </el-form-item>
          </div>
        </el-col>
        <el-col :xs="23" :sm="23" :md="11" :lg="8" :xl="8">
          <div class="grid-content bg-purple">
            <el-form-item  :label="$t('wxmini.wd_date')" prop="wd_date">
              <div class="block">
                <el-date-picker v-model="addDianping.wd_date" value-format="yyyy-MM-dd" align="right" type="date" placeholder="选择日期" :picker-options="pickerOptions1" style="width: 100%;">
                </el-date-picker>
              </div>
            </el-form-item>
          </div>
        </el-col>
        <el-col :xs="23" :sm="23" :md="23" :lg="7" :xl="7">
          <div class="grid-content bg-purple">
            <el-form-item  :label="$t('wxmini.wd_result')" prop="wd_result" >
              <div class="block">
                <el-rate v-model="addDianping.wd_result" ></el-rate>
              </div>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="24" >
        <el-col :xs="23" :sm="23" :md="23" :lg="23" :xl="23">
          <div class="grid-content bg-purple">
            <el-form-item  :label="$t('wxmini.wd_pic')">
              <div class="block">
                <el-upload
                  :action="UploadUrl()"
                  list-type="picture-card"
                  :data="datacomment"
                  :on-preview="handlePictureCardPreview"
                  :on-success="uploadSuccess"
                  :before-upload="checksize"
                  :file-list="fileListcomment"
                  :on-remove="handleRemovecomment">
                  <i class="el-icon-plus"></i>
                </el-upload>
              </div>
            </el-form-item>
             <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="24" >
        <el-col :xs="23" :sm="23" :md="23" :lg="23" :xl="23">
          <div class="grid-content bg-purple">
            <el-form-item  :label="$t('wxmini.wd_comment')" prop="wd_comment">
              <div class="editor-container">
                <tinymce :height=200 ref="tinymce-comment" v-model="addDianping.wd_comment"></tinymce>
              </div>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer" align="center" style="width: 90%">
        <el-button type="primary" @click="saveDianping()" :loading ="buttonloading">{{$t('table.save')}}</el-button>
        <el-button @click="resetForm()">{{$t('navbar.reset')}}</el-button>
      </div>
  </div>
</template>
<script>
  import waves from '@/directive/waves' // 水波纹指令
  import { createArticle } from '@/api/article'
  import { parseTime } from '@/utils'
  import config from '@/utils/config'
  import { formatDate } from '@/utils/validate'
  import { deleteWXDianPingImage, insertWXDianPing } from '@/api/wxmini'
  // 富文本
  import Tinymce from '@/components/Tinymce'
  import Upload from '@/components/Upload/singleImage3'
  import MDinput from '@/components/MDinput'
  import Multiselect from 'vue-multiselect'// 使用的一个多选框组件，element-ui的select不能满足所有需求
  import Sticky from '@/components/Sticky' // 粘性header组件
  export default {
    // name: 'dianpingadd111', 不支持keep-alive
    components: { Tinymce, MDinput, Upload, Multiselect, Sticky },
    directives: {
      waves
    },
    data() {
      return {
        url: config.BASE_URL + '/uploadDianPingImg',
        datacomment: {},
        fileListcomment: [],
        dialogVisible: false,
        dialogImageUrl: null,
        tableKey: 0,
        buttonloading: false,
        pickerOptions1: {
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date())
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }]
        },
        sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
        addDianping: {
          wd_username: null,
          wd_date: null,
          wd_result: 1,
          wd_comment: '',
          wd_create_date: null,
          wd_create_user: null,
          image_list: []
        },
        dialogPvVisible: false,
        pvData: [],
        rules: {
          wd_username: [{ required: true, message: '请输入用户姓名', trigger: 'blur' }],
          wd_date: [{ required: true, message: '请输入评论日期', trigger: 'blur' }],
          wd_result: [{ required: true, message: '请输入评分', trigger: 'blur' }],
          wd_comment: [{ required: true, message: '请输入评论内容', trigger: 'blur' }]
        },
        downloadLoading: false
      }
    },
    created() {
      this.getList()
    },
    methods: {
      getList() {
        this.listLoading = false
        this.addDianping.wd_date = formatDate(new Date(), 'yyyy-MM-dd')
      },
      UploadUrl() {
        return this.url
      },
      resetForm(formName) {
        this.$refs['tinymce-comment'].setContent('')
        this.addDianping.wd_username = null
        this.addDianping.wd_date = formatDate(new Date(), 'yyyy-MM-dd')
        this.addDianping.wd_result = null
        this.addDianping.wd_comment = null
        this.addDianping.wd_create_date = null
        for (var f of this.fileListcomment) {
          var removeImge = {
            filepath: null
          }
          removeImge.filepath = f.response
          deleteWXDianPingImage(removeImge).then(response => {
          })
        }
        this.fileListcomment = []
      },
      saveDianping() {
        this.$refs['dianPingddForm'].validate((valid) => {
          if (valid) {
            if (this.fileListcomment.length === 0) {
              createArticle(this.temp).then(() => {
                this.$confirm('评论没有图片?点击确认继续保存', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                  var fileList = []
                  for (let i = 0; i < this.fileListcomment.length; i++) {
                    fileList.push(this.fileListcomment[i].response)
                  }
                  var date1 = new Date()
                  this.addDianping.wd_create_date = date1.getFullYear() + '-' + (date1.getMonth() + 1) + '-' + date1.getDate() + ' ' + date1.getHours() + ':' + date1.getMinutes() + ':' + date1.getSeconds()
                  this.addDianping.wd_username = this.$store.state.user.introduction
                  this.addDianping.image_list = fileList.join(',')
                  insertWXDianPing(this.addDianping).then(response => {
                    if (response.data === 1) {
                      this.addDianping.wd_username = null
                      this.addDianping.wd_date = formatDate(new Date(), 'yyyy-MM-dd')
                      this.$refs['tinymce-comment'].setContent('')
                      this.addDianping.wd_result = null
                      this.addDianping.wd_comment = null
                      this.addDianping.wd_create_date = null
                      this.fileListcomment = []
                      this.$notify({
                        title: '成功',
                        message: '保存成功!',
                        type: 'success',
                        duration: 2000
                      })
                    } else {
                      this.$notify({
                        title: '失败',
                        message: '请联系管理员！',
                        type: 'error',
                        duration: 2000
                      })
                    }
                  })
                }).catch(() => {})
              })
            } else {
              var fileList = []
              for (let i = 0; i < this.fileListcomment.length; i++) {
                fileList.push(this.fileListcomment[i].response)
              }
              var date1 = new Date()
              this.addDianping.wd_create_date = date1.getFullYear() + '-' + (date1.getMonth() + 1) + '-' + date1.getDate() + ' ' + date1.getHours() + ':' + date1.getMinutes() + ':' + date1.getSeconds()
              this.addDianping.wd_create_user = this.$store.state.user.introduction
              this.addDianping.image_list = fileList.join(',')
              insertWXDianPing(this.addDianping).then(response => {
                if (response.data === 1) {
                  this.addDianping.wd_username = null
                  this.addDianping.wd_date = formatDate(new Date(), 'yyyy-MM-dd')
                  this.$refs['tinymce-comment'].setContent('')
                  this.addDianping.wd_result = null
                  this.addDianping.wd_comment = null
                  this.addDianping.wd_create_date = null
                  this.fileListcomment = []
                  this.$notify({
                    title: '成功',
                    message: '保存成功!',
                    type: 'success',
                    duration: 2000
                  })
                } else {
                  this.$notify({
                    title: '失败',
                    message: '请联系管理员！',
                    type: 'error',
                    duration: 2000
                  })
                }
              })
            }
          }
        })
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      uploadSuccess(res, file) {
        this.fileListcomment.push(file)
      },
      checksize(file) {
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!')
        }
      },
      handleRemovecomment(file, fileList) {
        var removeImge = {
          filepath: null
        }
        removeImge.filepath = file.response
        deleteWXDianPingImage(removeImge).then(response => {
          if (response.data === 1) {
            this.fileListcomment.splice(this.fileListcomment.indexOf(file), 1)
          } else {
            this.$notify({
              title: '失败',
              message: '请联系管理员！',
              type: 'error',
              duration: 2000
            })
          }
        })
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      }
    }
  }
</script>
<style>
.el-form--label-left .el-form-item__label{
  text-align:right
}
.el-rate{
  line-height: 0;
  margin-top:8px;
}
.el-checkbox.el-checkbox {
    margin-left: 30px;
}
</style>
<style rel="stylesheet/scss" lang="scss" scoped>
  @import "src/styles/mixin.scss";
  .title-prompt{
    position: absolute;
    right: 0px;
    font-size: 12px;
    top:10px;
    color:#ff4949;
  }
  .createPost-container {
    position: relative;
    .createPost-main-container {
      padding: 40px 45px 20px 50px;
      .postInfo-container {
        position: relative;
        @include clearfix;
        margin-bottom: 10px;
        .postInfo-container-item {
          float: left;
        }
      }
      .editor-container {
        min-height: 500px;
        margin: 0 0 30px;
        .editor-upload-btn-container {
            text-align: right;
            margin-right: 10px;
            .editor-upload-btn {
                display: inline-block;
            }
        }
      }
    }
    .word-counter {
      width: 40px;
      position: absolute;
      right: -10px;
      top: 0px;
    }
  }
</style>