<template>
  <div class="device-edit page-form-container">
    <el-form ref="form" label-width="130px" :model="formData" :rules="rules">
      <el-form-item label="认证方式：">
        <span>{{ authTypeName }}</span>
      </el-form-item>
      <el-form-item label="设备名称：" prop="productTypeId">
        <el-select v-model="formData.productTypeId" style="width: 100%" clearable>
          <el-option
            v-for="item in productCateList"
            :key="item.productTypeId"
            :label="item.name"
            :value="item.productTypeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备SN码：" prop="snCode">
        <el-input v-model="formData.snCode" placeholder="设备SN码" />
      </el-form-item>
      <el-form-item label="授权牌：" prop="certificateImageType">
        <el-radio-group v-model="formData.certificateImageType" size="mini">
          <el-radio :label="1">模板库生成</el-radio>
          <el-radio :label="2">自定义上传</el-radio>
        </el-radio-group>
        <template v-if="formData.certificateImageType === 1">
          <div>
            <preview-image v-if="formData.certificateImage" :src="formData.certificateImage" />
          </div>
        </template>
        <template v-else>
          <upload-image
            tip="建议尺寸：150px * 112px"
            :image-list="certificateImageList"
            :before-upload="beforeCertificateImageUpload"
            @success="uploadCertificateImageSuccess"
            @remove="handleCertificateImageRemove"
          />
        </template>
      </el-form-item>
      <el-form-item label="购买渠道：" prop="purchaseWay">
        <el-input v-model="formData.purchaseWay" placeholder="购买渠道" />
      </el-form-item>
      <el-form-item label="发票：" prop="invoiceImage">
        <upload-image
          tip="建议图片分辨率：242px*242px"
          :limit="1"
          :image-list="invoiceImageList"
          :before-upload="beforeInvoiceImageUpload"
          @success="uploadInvoiceImageSuccess"
          @remove="handleInvoiceImageRemove"
        />
        <el-input v-show="false" v-model="formData.invoiceImage" />
      </el-form-item>
    </el-form>

    <!-- 表单提交 返回 -->
    <div class="control-box">
      <el-button type="primary" @click="submit">保存</el-button>
      <el-button type="warning" @click="navigateBack">返回</el-button>
    </div>
  </div>
</template>

<script>
import UploadImage from '@/components/UploadImage'
import { fetchProductSelectList, getProductById, saveProduct } from '@/api/product'
import { isSnCode } from '@/utils/validate'
import { getStorage } from '@/utils/storage'
export default {
  components: { UploadImage },
  data() {
    const valideSNcode = (rules, value, callback) => {
      if (!isSnCode(value)) {
        return callback(new Error('只能是字母+数字组合'))
      }
      callback()
    }
    return {
      editType: 'add',
      isLoading: false,
      formData: {
        authId: '', //	授权id
        relationId: '',
        authType: 1, // 认证类型
        authUserId: '',
        certificateImage: '', //	授权牌照
        // 	设备参数
        productId: '', //	授权设备id
        snCode: '', //	设备SN码
        certificateImageType: 1,
        productTypeId: '',
        purchaseWay: '', // 购买渠道
        invoiceImage: '' // 发票
      },
      productCateList: [],
      certificateImageList: [],
      invoiceImageList: [],
      rules: {
        certificateImage: [{ required: true, message: '授权牌照不能为空', trigger: 'change' }],
        snCode: [{ required: true, message: 'SN码不能为空' }, { validator: valideSNcode }],
        productTypeId: [{ required: true, message: '设备名称不能为空', trigger: 'change' }]
      }
    }
  },
  computed: {
    authTypeName() {
      return this.formData.authType === 1 ? '新设备认证' : '关联已认证设备'
    }
  },
  created() {
    this.editType = this.$route.query.type || 'add'
    this.formData.relationId = this.$route.query.relationId
    this.formData.productId = this.$route.query.id
    // 获取当前设备所属机构的id
    this.formData.authId = getStorage('device-setting-authId')
    this.fetchProductCateList()
    if (this.editType === 'edit') {
      this.fetchProductDetail()
    }
  },
  methods: {
    // 提交
    async submit() {
      try {
        await this.$refs.form.validate()
        this.onSave()
      } catch (error) {
        console.log(error)
      }
    },

    // 保存
    async onSave() {
      try {
        await saveProduct(this.formData)
        const h = this.$createElement
        const tip = this.editType === 'add' ? '添加' : '修改'
        this.$notify.success({
          title: tip + '设备',
          message: h('i', { style: 'color: #333' }, `已${tip}设备`),
          duration: 2000
        })
        this.$store.dispatch('tagsView/delView', this.$route)
        this.$router.push(`/club/device-list?id=${this.formData.authId}`)
      } catch (error) {
        console.log(error)
      }
    },

    // 获取设备信息
    async fetchProductDetail() {
      try {
        this.isLoading = true
        const { productId, relationId } = this.formData
        const res = await getProductById({ productId, relationId })
        this.initFormData(res.data)
      } catch (error) {
        console.log(error)
      }
    },

    // 初始化表单数据
    initFormData(data) {
      for (const key in this.formData) {
        if (Object.hasOwnProperty.call(data, key)) {
          if (key === 'productTypeId') {
            this.formData[key] = parseInt(data[key])
          } else {
            this.formData[key] = data[key]
          }
        }
      }
      if (data.invoiceImage) {
        this.invoiceImageList = [{ name: '发票', url: data.invoiceImage }]
      }
      if (data.certificateImage) {
        this.certificateImageList = [{ name: '授权牌图片', url: data.certificateImage }]
      }
      this.isLoading = false
    },

    // 获取设备分类列表
    async fetchProductCateList() {
      try {
        const res = await fetchProductSelectList({ authUserId: this.authUserId })
        this.productCateList = res.data
      } catch (error) {
        console.log(error)
      }
    },

    // 授权牌照上传
    beforeCertificateImageUpload(file) {
      const flag = file.size / 1024 / 1024 < 1
      if (!flag) {
        this.$message.error('上传授权牌图片大小不能超过 1MB!')
      }
      return flag
    },
    uploadCertificateImageSuccess({ response, file, fileList }) {
      this.certificateImageList = fileList
      this.formData.certificateImage = response.data
    },
    handleCertificateImageRemove({ file, fileList }) {
      this.certificateImageList = fileList
      this.formData.certificateImage = ''
    },

    // 发票上传
    beforeInvoiceImageUpload(file) {
      const flag = file.size / 1024 / 1024 < 1
      if (!flag) {
        this.$message.error('上传授权牌图片大小不能超过 1MB!')
      }
      return flag
    },
    uploadInvoiceImageSuccess({ response, file, fileList }) {
      this.invoiceImageList = fileList
      this.formData.invoiceImage = response.data
    },
    handleInvoiceImageRemove({ file, fileList }) {
      this.invoiceImageList = fileList
      this.formData.invoiceImage = ''
    }
  }
}
</script>

<style lang="scss" scoped></style>
