<template>
  <BaseDialog v-bind="$attrs" v-on="listeners" @submit="onSubmit" :loading="loading" @closed="onClosed">
    <el-form class="form" ref="form" v-bind="{ labelWidth: '6em', size: 'small' }" :model="formData" :rules="rules">
      <el-form-item required label="设备类型" prop="dictionaryId">
        <el-select v-model="formData.dictionaryId" @change="onNameChange" :disabled="data.id">
          <el-option v-for="item of dictionary" :key="item.id" :value="item.id" :label="item.deviceTypeName" />
        </el-select>
      </el-form-item>
      <el-form-item required label="图标" prop="file">
        <el-upload
          class="icon-uploader"
          action="somefakeurl"
          :show-file-list="false"
          :auto-upload="false"
          :on-change="onFileChange"
          accept=".jpg,.jpeg,.png"
        >
          <el-image v-if="imageUrl" class="icon" :src="imageUrl" />
          <i v-else class="el-icon-plus icon-uploader-icon" />
        </el-upload>
      </el-form-item>
    </el-form>
  </BaseDialog>
</template>

<script lang="ts">
import { Vue, Component, Prop, Watch } from 'vue-property-decorator'
import BaseDialog from '@/components/BaseDialog/index.vue'
import { ElForm } from 'element-ui/types/form'
import { IDeviceTypeDictionary, IDeviceType } from '../api/common'
import { getRemoteImg } from '@/api/ftp'
import { ElUploadInternalFileDetail } from 'element-ui/types/upload'

const getDefaultValue = () => ({ dictionaryId: undefined, file: undefined, fileTypeID: 803 })

@Component({ name: 'TypeForm', components: { BaseDialog } })
export default class TypeForm extends Vue {
  @Prop({ type: Object, default: () => ({}) }) data!: IDeviceType
  @Prop({ type: Boolean, default: false }) loading!: boolean
  @Prop({ type: Array, default: () => [] }) dictionary!: IDeviceTypeDictionary[]
  $refs!: { form: ElForm }
  formData: Partial<IDeviceType> & {
    file?: ElUploadInternalFileDetail | string
  } = getDefaultValue()
  imageUrl: string = ''
  get listeners() {
    const { submit, closed, ...rest } = this.$listeners
    return rest
  }

  get projectInfo() {
    return this.$store.getters['project/info']
  }

  rules = {
    dictionaryId: [{ type: 'number', required: true, message: '请选择设备类型' }],
    file: [{ validator: (rule, value, callback) => (!value ? callback(new Error('请上传图标')) : callback()) }]
  }

  onSubmit() {
    this.$refs.form.validate((valid) => valid && this.$emit('submit', { ...this.formData, ...this.projectInfo }))
  }

  onNameChange(id) {
    const { dataUploadTime, deviceTypeName } = this.dictionary.find((item) => item.id === id) || {}
    this.formData.dataUploadTime = dataUploadTime
    this.formData.deviceTypeName = deviceTypeName
  }

  onFileChange(file) {
    const allowedTypes = ['image/jpeg', 'image/png']
    const isLt10M = file.size / 1024 / 1024 < 10
    let pass = true

    if (!allowedTypes.includes(file.raw.type)) {
      this.$message.error('上传文件只能是 JPG/JPEG、png 格式!')
      pass = false
    }

    if (!isLt10M) {
      this.$message.error('上传文件大小不能超过 10MB!')
      pass = false
    }
    if (pass) {
      const reader = new FileReader()
      reader.onload = (e) => {
        this.imageUrl = e.target.result.toString()
      }
      reader.readAsDataURL(file.raw)
      this.formData.file = file.raw
    }
  }

  onClosed() {
    this.imageUrl = ''
    this.$emit('closed')
  }

  @Watch('data', { immediate: true })
  setDefaultData(val: IDeviceType) {
    const { iconFiles } = val || {}
    const { filePath } = (iconFiles || [])[0] || {}
    if (val.id) {
      this.formData = { ...val }
      const { iconFiles } = val || {}
      const { filePath } = (iconFiles || [])[0]
      this.imageUrl = getRemoteImg(filePath)
    } else {
      this.formData = getDefaultValue()
      this.imageUrl = ''
    }

    if (filePath) this.imageUrl = getRemoteImg(filePath)
  }
}
</script>
<style lang="scss" scoped>
.form {
  >>> .icon {
    $width: 128px;
    $height: 128px;
    width: $width;
    height: $height;
    display: block;
    border-radius: $--border-radius-base;
    overflow: hidden;
    &-uploader .el-upload {
      border: 1px dashed $--border-color-base;
      border-radius: $--border-radius-base;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      background-color: rgba(#000, 0.1);
      &:hover {
        border-color: $--color-primary;
      }
    }
    &-uploader-icon {
      font-size: 28px;
      color: $--color-text-secondary;
      width: $width;
      height: $height;
      line-height: $height;
      text-align: center;
    }
  }
}
</style>
