<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-form :rules="rules" ref="dianPingddForm" :model="updateDianping" 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="updateDianping.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="updateDianping.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="updateDianping.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-updatecomment" v-model="updateDianping.wd_comment"></tinymce>
              </div>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      </el-form>
    </div>
    <span style="color:red;font-size:16px;">删除的图片将不能恢复,请谨慎操作</span>
    <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 { deleteWXDianPingImage, updateWXDianPing, getWXDianPingsByID, getWXDianPingImages } 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: 'dianpingedit222', 不支持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' }],
        updateDianping: {
          id: null,
          wd_username: null,
          wd_date: null,
          wd_result: null,
          wd_comment: null,
          wd_create_date: null,
          wd_create_user: null,
          image_list: []
        },
        updateDianpingOld: {
          wd_username: null,
          wd_date: null,
          wd_result: null,
          wd_comment: null
        },
        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,
        view: {
          name: undefined,
          path: undefined,
          title: undefined
        }
      }
    },
    destroyed() {
      this.view.name = 'dianpingedit'
      this.view.path = '/wxmini/dianpingedit'
      this.view.title = 'dianpingedit'
      this.$store.dispatch('delVisitedViews', this.view)
    },
    created() {
      this.getList()
    },
    methods: {
      getList() {
        this.listLoading = false
        var queryByID = {
          id: null
        }
        var queryImgsByID = {
          wd_id: null
        }
        this.updateDianping.id = this.$route.params.dianpingID
        queryByID.id = this.$route.params.dianpingID
        queryImgsByID.wd_id = this.$route.params.dianpingID
        getWXDianPingsByID(queryByID).then(response => {
          this.updateDianping.wd_username = response.data.wd_username
          this.updateDianping.wd_date = response.data.wd_date
          this.updateDianping.wd_result = response.data.wd_result
          this.updateDianping.wd_comment = response.data.wd_comment
          this.updateDianpingOld.wd_username = response.data.wd_username
          this.updateDianpingOld.wd_date = response.data.wd_date
          this.updateDianpingOld.wd_result = response.data.wd_result
          this.updateDianpingOld.wd_comment = response.data.wd_comment
          // this.$refs['tinymce-updatecomment'].setContent(response.data.wd_comment)
        })
        getWXDianPingImages(queryImgsByID).then(response => {
          for (var i = 0; i < response.data.length; i++) {
            var imgs = {
              name: null,
              url: null,
              response: null
            }
            imgs.name = i
            imgs.url = response.data[i].wdi_image_path
            imgs.response = response.data[i].wdi_image_path
            this.fileListcomment.push(imgs)
          }
        })
      },
      UploadUrl() {
        return this.url
      },
      resetForm(formName) {
        this.updateDianping.wd_username = this.updateDianpingOld.wd_username
        this.updateDianping.wd_date = this.updateDianpingOld.wd_date
        this.updateDianping.wd_result = this.updateDianpingOld.wd_result
        this.updateDianping.wd_comment = this.updateDianpingOld.wd_comment
        this.$refs['tinymce-updatecomment'].setContent(this.updateDianpingOld.wd_comment)
      },
      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.updateDianping.wd_create_date = date1.getFullYear() + '-' + (date1.getMonth() + 1) + '-' + date1.getDate() + ' ' + date1.getHours() + ':' + date1.getMinutes() + ':' + date1.getSeconds()
                  this.updateDianping.wd_username = this.$store.state.user.introduction
                  this.updateDianping.image_list = fileList.join(',')
                  updateWXDianPing(this.updateDianping).then(response => {
                    if (response.data === 1) {
                      this.getList()
                      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.updateDianping.wd_create_date = date1.getFullYear() + '-' + (date1.getMonth() + 1) + '-' + date1.getDate() + ' ' + date1.getHours() + ':' + date1.getMinutes() + ':' + date1.getSeconds()
              this.updateDianping.wd_create_user = this.$store.state.user.introduction
              this.updateDianping.image_list = fileList.join(',')
              updateWXDianPing(this.updateDianping).then(response => {
                if (response.data === 1) {
                  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>
