<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" v-loading="loading">
            <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>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
        </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: '',
        startTime: '',
        endTime: '',
        state: '',
        amount: '',
        deptName: '',
        deptId: '',
        deptIdsArr: [],
        allDeptIds: '',
        allDeptNames: '',
        parentDeptIds: '',
        parentDeptNames: ''
      },
      stateArr: [
        { dictValue: '1', dictName: '上架' },
        { dictValue: '0', dictName: '下架' }
      ],
      options: [],
      isAble: false,
      uploadUrl: '',
      loading: 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: true, 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 = `${window.SITE_CONFIG['apiURL']}/oss/file/upload?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('-', '')
    },
    // 上传图片
    handleAvatarSuccess (res, file) {
      this.loading = false
      this.dataForm.headPic = res.data.url
    },
    beforeAvatarUpload (file) {
      this.loading = 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
        }
        // 校验兑换开始时间、结束时间
        let startTime = new Date(this.dataForm.startTime)
        let endTime = new Date(this.dataForm.endTime)
        if (startTime.getTime() > endTime.getTime()) {
          this.$message({
            message: '兑换开始时间大于结束时间、请修改后提交！',
            type: 'error',
            duration: 2000,
            onClose: () => {
              return false
            }
          })
          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>
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409eff;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>
