<template>
  <div v-loading="isLoading" class="addProduct">
    <el-form ref="addFormRef" label-width="130px" class="addForm" :model="formData" :rules="rules">
      <el-form-item label="设备名称:" prop="productName">
        <el-input v-model="formData.productName" placeholder="建议输入30个字符效果最佳" />
      </el-form-item>

      <el-form-item label="设备SN码:" prop="snCode">
        <el-input v-model="formData.snCode" placeholder="请输入设备SN码" />
      </el-form-item>

      <el-form-item v-if="shopType === 2" label="所属品牌:" prop="brandId">
        <el-select
          v-model="formData.brandId"
          placeholder="请选择品牌"
          style="width: 100%"
          filterable
          @change="handleChange"
        >
          <el-option v-for="item in brandList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="设备图片:" prop="productImage">
        <upload-image
          tip="建议尺寸：542px * 542px"
          :image-list="productImageList"
          :before-upload="beforeProductImageUpload"
          @success="uploadProductImageSuccess"
          @remove="handleProductImageRemove"
        />
        <el-input v-model="formData.productImage" class="hiddenInput" />
      </el-form-item>
      <el-form-item label="授权牌:" prop="certificateImage">
        <upload-image
          tip="建议尺寸：150px * 112px"
          :image-list="certificateImageList"
          :before-upload="beforeCertificateImageUpload"
          @success="uploadCertificateImageSuccess"
          @remove="handleCertificateImageRemove"
        />
        <el-input v-model="formData.certificateImage" class="hiddenInput" />
      </el-form-item>
      <!-- 是否生成二维码授权牌 -->
      <el-form-item label="生成二维码授权牌:">
        <el-radio-group v-model="formData.addQrCodeFlag" size="mini" @change="handleRadioChange">
          <el-radio :label="0" border>否</el-radio>
          <el-radio :label="1" border :disabled="certificateImageList.length <= 0">是</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 二维码授权牌模板 -->
      <el-form-item v-if="formData.addQrCodeFlag===1" label="选择模板:">
        <auth-card-template v-model="formData.addTemplateType" :image-list="certificateImageList" />
      </el-form-item>

      <el-form-item label="相关参数:" prop="paramList">
        <div v-for="(item, index) in paramList" :key="index" class="form-group paramsItem">
          <el-input v-model="item.paramName" class="param-title" :placeholder="item.tip.first" maxlength="10" />
          <el-input v-model="item.paramContent" class="param-info" placeholder="请输入参数信息" maxlength="50" />
          <span v-if="paramsCount > 4" class="closed el-icon-close" @click="handleRemoveParam(index)" />
        </div>
        <el-button type="primary" size="mini" @click="handleAddParam">添加参数</el-button>
      </el-form-item>
      <!-- <el-form-item label="上线状态:">
        <el-select
          v-model="formData.status"
          placeholder="上线状态"
          style="width: 100%"
        >
          <el-option label="上线" :value="1" />
          <el-option label="下线" :value="0" />
        </el-select>
      </el-form-item> -->
    </el-form>
    <div class="submit-btn">
      <el-button type="primary" @click="submit">保存</el-button>
      <el-button type="warning" @click="$_back()">返回</el-button>
    </div>
  </div>
</template>

<script>
import UploadImage from '@/components/UploadImage'
import { saveProduct } from '@/api/product'
import { fetchBrandList } from '@/api/brand'
import { mapGetters } from 'vuex'
import { isSnCode } from '@/utils/validate'
import AuthCardTemplate from '@/views/components/authCardTemplate.vue'
export default {
  components: { UploadImage, AuthCardTemplate },
  data() {
    const valideSNcode = (rules, value, callback) => {
      if (!isSnCode(value)) {
        return callback(new Error('只能是字母+数字组合'))
      }
      callback()
    }
    const valideBrandId = (rules, value, callback) => {
      if (!value) {
        return callback(new Error('所属品牌不能为空'))
      }
      callback()
    }
    return {
      isLoading: false,
      paramsCount: 4,
      brandList: [],
      formData: {
        authUserId: '',
        authId: '', //	授权id
        certificateImage: '', //	授权牌照
        createBy: '', //	创建人id
        // 	设备参数列表
        paramList: [],
        productId: '', //	授权设备id
        productImage: '', //	设备图片
        productName: '', //	设备名称
        snCode: '', //	设备SN码
        status: 2, //	上架状态：0下线，1上线 2待审核
        brandId: '',
        addQrCodeFlag: 0,
        addTemplateType: 1
      },
      paramList: [], // 参数列表
      rules: {
        certificateImage: [{ required: true, message: '授权牌照不能为空' }],
        paramList: [{ required: true, message: '参数不能为空' }],
        productImage: [{ required: true, message: '设备图片不能为空' }],
        snCode: [{ required: true, message: 'SN码不能为空' }, { validator: valideSNcode }],
        productName: [
          { required: true, message: '设备名称不能为空' },
          { max: 50, message: '字数在50字符以内' }
        ],
        brandId: [{ required: true, validator: valideBrandId, tigger: 'change' }]
      },
      // 参数框的提示语
      tipList: ['例如：品牌', '例如：尺寸', '例如：功率', '例如：重量'],

      // 商品图片列表
      productImageList: [],
      // 授权牌照图片列表
      certificateImageList: []
    }
  },
  computed: {
    ...mapGetters(['authUserId', 'proxyInfo', 'shopType', 'brandId'])
  },
  watch: {
    paramList: {
      deep: true,
      handler: function() {
        this.formData.paramList = this.setParamToFormData()
      }
    }
  },
  created() {
    this.formData.authId = this.$route.query.id
    this.formData.authUserId = this.proxyInfo?.authUserId || this.authUserId
    this.initParamList()
    // 如果供应商类型为代理商  则需要获取它代理的品牌列表
    if (this.shopType === 2) {
      this.getBrandList()
    }
    // 如果供应商类型为品牌方，则自动设置品牌id
    if (this.shopType === 1) {
      this.formData.brandId = this.proxyInfo?.brandId || this.brandId || ''
    }
  },
  methods: {

    authCardChange(current) {
      console.log(current)
      this.formData.addTemplateType = current
    },

    handleChange() {
      console.log(this.formData)
    },

    handleRadioChange(index) {
      if (index === 1 && this.certificateImageList.length <= 0) {
        this.$message.warning('请先上传授权牌')
        this.formData.addQrCodeFlag = 0
        return
      }
    },

    // 提交
    submit() {
      this.formData.paramList = this.setParamToFormData()
      this.$refs.addFormRef.validate(valide => {
        if (valide) {
          this.save()
        }
      })
    },
    // 保存表单数据
    save() {
      this.isLoading = true
      // createBy先判断是否为代理操作，是就从代理数据中获取，否则直接获取当前登录用户的信息
      this.formData.createBy = this.proxyInfo?.authUserId || this.authUserId
      this.formData.authUserId = this.proxyInfo?.authUserId || this.authUserId
      saveProduct(this.formData)
        .then(res => {
          if (res.code !== 0) return
          const h = this.$createElement
          this.$notify.success({
            title: '新增设备',
            message: h('i', { style: 'color: #333' }, `已添加设备："${this.formData.productName}"`),
            duration: 2000
          })
          this.$refs.addFormRef.resetFields()
          this.clearFormData()
          this.$store.dispatch('tagsView/delView', this.$route)
          this.$router.push(`/product/list?id=${this.formData.authId}`)
        })
        .finally(() => {
          this.isLoading = false
        })
    },
    // 保存参数到formdata
    setParamToFormData() {
      return this.paramList.filter(item => item.paramContent !== '' && item.paramName !== '')
    },
    // 初始化参数列表
    initParamList() {
      for (let i = 0; i < this.paramsCount; i++) {
        this.paramList.push({
          paramContent: '',
          paramName: '',
          tip: {
            first: this.tipList[i],
            second: '请输入参数信息'
          }
        })
      }
    },
    // 获取品牌信息
    getBrandList() {
      fetchBrandList({ type: 3, authUserId: this.formData.authUserId }).then(res => {
        console.log(res)

        this.brandList = res.data
      })
    },
    // 添加一栏参数
    handleAddParam() {
      this.paramsCount += 1
      this.paramList.push({
        paramContent: '',
        paramName: '',
        tip: {
          first: '参数名称',
          second: '请输入参数信息'
        }
      })
    },
    // 删除一栏参数
    handleRemoveParam(index) {
      this.paramsCount -= 1
      this.paramList.splice(index, 1)
    },

    // 产品图片上传
    beforeProductImageUpload(file) {
      const flag = file.size / 1024 / 1024 < 1
      if (!flag) {
        this.$message.error('上传产品图片大小不能超过 1MB!')
      }
      return flag
    },
    uploadProductImageSuccess({ response, file, fileList }) {
      this.productImageList = fileList
      this.formData.productImage = response.data
    },
    handleProductImageRemove({ file, fileList }) {
      this.productImageList = fileList
      this.formData.productImage = ''
    },
    // 授权牌照上传
    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 = ''
      this.formData.addQrCodeFlag = 0
    },

    clearFormData() {
      this.paramList = []
      this.paramsCount = 4
      this.initParamList()
    }
  }
}
</script>

<style lang="scss" scoped>
.addProduct {
  margin-bottom: 80px;
  .form-group {
    margin-bottom: 2%;
    .param-title {
      width: 30%;
    }
    .param-info {
      width: 68%;
      margin-left: 2%;
    }
  }
}
.addForm {
  width: 800px;
  margin: 0 auto;
  margin-top: 80px;
}
.submit-btn {
  text-align: center;
  .el-button {
    width: 140px;
  }
}
.paramsItem {
  position: relative;
  .closed {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    right: -20px;
    cursor: pointer;
    color: #ddd;
    &:hover {
      color: #333;
    }
  }
}
.hiddenInput {
  height: 0;
  display: none;
}
</style>
