<template>
  <div>
    <el-scrollbar
      wrap-class="column-wrapper scrollable-items-container"
      :native="false"
      style="height: 250px;"
    >
      <el-form
        :model="Formdata"
        ref="newTaskForm"
        :rules="FormRules"
        @submit.native.prevent
        style="padding-right:20px;"
      >
        <el-form-item label="名称" prop="name" label-width="60px">
          <el-input v-model="Formdata.name" :value="Formdata.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="remark" label-width="60px">
          <el-input type="textarea" :value="Formdata.content" v-model="Formdata.content"></el-input>
        </el-form-item>
        <el-form-item label prop="type" label-width="60px">
          <el-radio v-model="Formdata.type" label="0">公告</el-radio>
          <el-radio v-model="Formdata.type" label="1">福利</el-radio>
        </el-form-item>
        <el-form-item label="附件" label-width="60px">
          <upload_oss
            :headers="Xtoken"
            class="avatar-uploader"
            ref="upload"
            :action="'http://'+'integralsys.oss-cn-shenzhen.aliyuncs.com'"
            :show-file-list="true"
            :file-list="Formdata.file_list"
            :on-success="handleFilesSuccess"
            :on-preview="onFilePreView"
            :before-upload="beforeFilesUpload"
            :on-remove="onFileRemove"
            accept="image/gif, image/jpeg, image/png, image/bmp"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </upload_oss>

          <div style="display:none;">
            <img
              v-for="(item,index) in Formdata.file_list"
              :key="index"
              v-if="(['jpg', 'png', 'bmp', 'jpeg','JPG','PNG']).indexOf(item.name.split('.')[1]) >= 0"
              :src="item.url"
              :preview="index"
              :preview-text="item.name"
            >
          </div>
        </el-form-item>
      </el-form>
    </el-scrollbar>
  </div>
</template>
<script>
import Vue from 'vue'
import preview from '@/views/dashboard/components/preview/lib/index'
import 'vue-photo-preview/dist/skin.css'
import upload_oss from "@/views/upload_oss/upload"
Vue.use(preview, {
  tapToClose: false
})
import qs from 'qs'
import { getToken } from '@/utils/auth'
export default {
  name: 'RewardCreate',
  components: {
    upload_oss
  },
  props: {
    type: {
      type: String,
      default: 'notice'
    }
  },
  data() {
    return {
      Xtoken: { 'X-Token': getToken() },
      files: [],
      profile: this.$store.getters.user_info,
      FormApi: '/integral.php/reward/add',
      Formdata: {
        name: '',
        content: '',
        file_list: [],
        type: '0'
      },
      FormRules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 3, max: 30, message: '长度在 3 到 50 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    onFilePreView(file) {
      // 点击时查看文件
      const $ext_list = ['doc', 'docx', 'pptx', 'xls', 'xlsx', 'ppt', 'txt']
      const $ext_name = file.name.split('.')[1]
      if ($ext_list.indexOf($ext_name) >= 0) {
        // console.log(
        //   'https://view.officeapps.live.com/op/view.aspx?src=' +
        //     this.serverdomain +
        //     file.url
        // )
        window.open(
          // 'https://view.officeapps.live.com/op/view.aspx?src=' +
          //   this.serverdomain +
            file.response.url,
          '_blank'
        )
      }
      const $ext_list1 =  ['jpg', 'png', 'bmp', 'jpeg','JPG','PNG']
      const $ext_name1 = file.name.split('.')[1]
      if ($ext_list1.indexOf($ext_name1) >= 0) {
        // console.log(this.serverdomain + file.url)

        let ii = 0
        for (const i in this.Formdata.file_list) {
          if (
             ['jpg', 'png', 'bmp', 'jpeg','JPG','PNG'].indexOf(
              this.Formdata.file_list[i].name.split('.')[1]
            ) >= 0
          ) {
            if (this.Formdata.file_list[i].name == file.name) {
              console.log(ii)
              this.openPhotoSwipe(
                ii,
                document.querySelectorAll('img[preview]')
              )

              return
            }
            ii++
          }
        }
      }
    },

    onFileRemove(file, fileList) {
      this.Formdata.file_list = fileList
    },

    handleFilesSuccess(response, file, fileList) {
      // this.Formdata.file_list = fileList
      let self = this
      if(response.status == 0){
        self.$message({
          message: response.msg,
          type: 'error'
        })
        return false
      }else{
        this.$set(this.Formdata, 'file_list', fileList)
      }

    },
    beforeFilesUpload() {},
    FormReset: function(id) {
      this.Formdata = {
        name: '',
        content: '',
        type: '0'
      }
      this.$nextTick(() => {
        const form = this.$refs['newTaskForm']
        if (typeof id === 'undefined') {
          form.resetFields()
          form.clearValidate()
          // 重置表单数据之后设置默认类型 公告或福利
          this.type == 'notice' ? this.Formdata.type = '0' : this.Formdata.type = '1'
        }
      })
    },

    loadInfo(id) {
      const self = this

      this.$http('get','/integral.php/reward/get_reward_info',{id: id})
        .then(function(response) {
          if (response.status == 200) {
            var jsonData = response.data
            self.Formdata.name = jsonData.data.name
            self.Formdata.id = jsonData.data.id
            self.Formdata.type = jsonData.data.type + ''
            self.Formdata.content = jsonData.data.content_text
            self.Formdata.file_list = jsonData.data.file_list
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },

    FormSend() {
      const self = this
      const form = this.$refs['newTaskForm']
      form.validate(valid => {
        if (valid) {
          this.$http('post',self.FormApi,qs.stringify({ row: this.Formdata }),
            // headers: {
            //   'Content-Type': 'application/x-www-form-urlencoded'
            // }
          )
            .then(function(response) {
              var message = ''
              var status = 0
              if (response.status == 200) {
                var data = response.data
                message = data.msg
                console.log(data.code)
                console.log("kkkkkkkkk")
                if (data.code == 1) {
                  self.$emit('send-success', data)
                
                  form.resetFields()
                  form.clearValidate()
                  
                  self.Formdata.file_list = [];
                  self.$message({
                    message: message,
                    type: 'success'
                  })
                } else {
                  self.$message({
                    message: message,
                    type: 'error'
                  })
                }
              } else {
                message = '服务器太忙了'
              }
            })
            .catch(function(error) {
              console.log(error)
            })
        } else {
          return false
        }
      })
    }
  },
  created() {}
}
</script>
