<template>
  <el-dialog :visible.sync="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()" label-width="120px">
        <el-form-item label="商品名称" prop="name">
            <el-input v-model="dataForm.name" placeholder="商品名称"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="content">
            <el-input type="textarea" :rows="2" v-model="dataForm.content" placeholder="描述"></el-input>
        </el-form-item>
        <el-form-item label="积分" prop="points">
            <el-input-number v-model="dataForm.points" :min="0" :max="1000000000" label="积分" style="width: 200px"></el-input-number>
        </el-form-item>
        <el-form-item label="显示图片" prop="headPic">
            <el-upload
                    class="avatar-uploader"
                    :action="uploadUrl"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload">
                <img v-if="dataForm.headPic" :src="dataForm.headPic" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <el-upload
                    ref="upload"
                    :action="uploadUrl"
                    :class="{hide:hideUpload}"
                    list-type="picture-card"
                    :file-list="dataForm.images"
                    :limit=1
                    :on-preview="handlePictureCardPreview"
                    :on-remove="handleRemove"
                    :on-success="handleAvatarSuccess"
                    :on-error="handelError"
                    :before-upload="beforeAvatarUpload"
                    style="width:480px">
                <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
            <div><font color="gray">1张图</font></div>
        </el-form-item>
        <el-form-item label="兑换开始时间" prop="startTime">
            <el-date-picker
                    v-model="dataForm.startTime"
                    type="datetime"
                    placeholder="兑换开始时间"
                    style="width: 200px">
            </el-date-picker>
        </el-form-item>
        <el-form-item label="兑换结束时间" prop="endTime">
            <el-date-picker
                    v-model="dataForm.endTime"
                    type="datetime"
                    placeholder="兑换结束时间"
                    style="width: 200px">
            </el-date-picker>
        </el-form-item>
        <el-form-item label="上架状态" prop="state">
            <el-select v-model="dataForm.state" placeholder="上架状态" style="width: 200px">
                <el-option v-for="item in stateArr" :key="item.dictValue" :label="item.dictName" :value="item.dictValue">
                </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="库存数量" prop="amount">
            <el-input-number v-model="dataForm.amount" :min="0" :max="1000000000" label="库存数量" style="width: 200px"></el-input-number>
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
            <el-cascader
                    ref="name"
                    v-model="dataForm.deptIdsArr"
                    :options="options"
                    :props="{ checkStrictly: true }"
                    @visible-change="changeHandle"
                    style="width:50%;"
            >
            </el-cascader>
        </el-form-item>
      </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
      <el-button type="primary" :disabled="isAble" @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from 'lodash/debounce'
import Cookies from 'js-cookie'
export default {
  data () {
    return {
      visible: false,
      dataForm: {
        id: '',
        name: '',
        content: '',
        points: '',
        headPic: '',
        images: [],
        startTime: '',
        endTime: '',
        state: '',
        amount: '',
        deptName: '',
        deptId: '',
        deptIdsArr: [],
        allDeptIds: '',
        allDeptNames: '',
        parentDeptIds: '',
        parentDeptNames: ''
      },
      stateArr: [
        { dictValue: '1', dictName: '上架' },
        { dictValue: '0', dictName: '下架' }
      ],
      options: [],
      isAble: false,
      uploadUrl: '',
      loading: false,
      dialogImageUrl: '',
      dialogVisible: false,
      hideUpload: false
    }
  },
  computed: {
    dataRule () {
      return {
        name: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        content: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        points: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        headPic: [
          { required: false, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        startTime: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        endTime: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        state: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        amount: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        deptName: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        deptId: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  created: function () {
    this.getOptions()
    this.uploadUrl = `${window.SITE_CONFIG['apiURL']}/oss/file/uploadImg?token=${Cookies.get('token')}`
    // this.uploadUrl = `http://219.146.91.110:10000/epdc-api/oss/file/uploadImg?token=${Cookies.get('token')}`
  },
  methods: {
    init () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.getInfo()
        }
      })
    },
    getOptions () {
      this.$http.get(`/sys/user/deptOptions/getDeptAuthByUser`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.options = res.data.options
      }).catch(() => {})
    },
    changeHandle (value, selectedData) {
      let allDeptIds = '0,'
      let allDeptNames = '市北区委-'
      if (this.$refs['name']._data.checkedValue !== null && this.$refs['name']._data.checkedValue.length > 0) {
        let nameArrStr = this.$refs['name']._data.inputValue
        let nameArr = nameArrStr.split(' / ')
        for (var i = 0; i < this.$refs['name']._data.checkedValue.length; i++) {
          allDeptIds += this.$refs['name']._data.checkedValue[i] + ','
          allDeptNames += nameArr[i] + '-'
        }
      }
      this.dataForm.allDeptIds = allDeptIds.length > 0 ? allDeptIds.substring(0, allDeptIds.length - 1) : allDeptIds
      this.dataForm.allDeptNames = allDeptNames.length > 0 ? allDeptNames.substring(0, allDeptNames.length - 1) : allDeptNames
      this.dataForm.parentDeptIds = this.dataForm.allDeptIds.substring(0, this.dataForm.allDeptIds.lastIndexOf(','))
      this.dataForm.parentDeptNames = this.dataForm.allDeptNames.substring(0, this.dataForm.allDeptNames.lastIndexOf('-'))
      this.dataForm.deptId = this.dataForm.allDeptIds.substring(this.dataForm.allDeptIds.lastIndexOf(',')).replace(',', '')
      this.dataForm.deptName = this.dataForm.allDeptNames.substring(this.dataForm.allDeptNames.lastIndexOf('-')).replace('-', '')
    },
    beforeAvatarUpload (file) {
      if (this.dataForm.images.length === 1) {
        this.$message.error('最多上传1张图片!')
        return false
      }
      this.loading = true
      this.isAble = true
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      // const isLt1M = file.size / 1024 / 1024 < 1
      // 判断是否符合格式要求
      if (!isJPG && !isPNG) {
        this.$message.error('上传文件必须是jpg、png格式!')
        this.loading = false
        this.isAble = false
        return false
      }
    },
    handleAvatarSuccess (res, file) {
      this.loading = false
      this.isAble = false
      if (res === null || res.data === null || res.data.imgUrl === null) {
        this.$message.error('文件上传失败！')
        this.handleErrorRemove(file)
        return false
      }
      this.dataForm.images.push({ url: res.data.imgUrl, thumbnail: res.data.thumbnail, fileType: 1 })
      this.hideUpload = this.dataForm.images.length >= 1
      // 头像控件使用 to do
      this.dataForm.headPic = res.data.imgUrl
    },
    handleErrorRemove (file) {
      // 实现缩略图模板时删除文件
      let fileList = this.$refs.upload.uploadFiles
      for (var i = 0; i < fileList.length; i++) {
        let item = fileList[i]
        if (item.url === file.url) {
          fileList.splice(i, 1)
        }
      }
    },
    handelError () {
      this.loading = false
      this.isAble = false
      this.$message.error('上传文件失败!')
    },
    handleRemove (file, fileList) {
      for (var i = 0; i < this.dataForm.images.length; i++) {
        let item = this.dataForm.images[i]
        if (item.url === file.url) {
          this.dataForm.images.splice(i, 1)
        }
      }
      this.hideUpload = this.dataForm.images.length >= 1
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 获取信息
    getInfo () {
      this.$http.get(`/points/acitveproductinfo/${this.dataForm.id}`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }
      }).catch(() => {})
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.$http[!this.dataForm.id ? 'post' : 'put']('/points/acitveproductinfo/', this.dataForm).then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        }).catch(() => {})
      })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>
<style>
    .hide .el-upload--picture-card {
        display: none;
    }
</style>
