<template>
  <div v-loading="isLoading" class="addProduct">
    <el-form ref="addFormRef" label-width="120px" class="addForm" :model="formData" :rules="rules">
      <el-form-item label="设备名称:" prop="productName">
        <el-input v-model="formData.productName" placeholder="请输入设备名称" disabled />
      </el-form-item>

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

      <el-form-item v-if="shopType === 2" label="所属品牌:" prop="brandId">
        <el-select v-model="formData.brandId" placeholder="请选择品牌" style="width: 100%" filterable disabled>
          <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 ref="uploadImageRef2" :file-list="fileList1" disabled @success="imageUploadSuccess1" />
        <el-input v-model="formData.productImage" class="hiddenInput" />
      </el-form-item>
      <el-form-item label="授权牌:" prop="certificateImage">
        <upload-image ref="uploadImageRef2" :file-list="fileList2" disabled @success="imageUploadSuccess2" />
        <el-input v-model="formData.certificateImage" class="hiddenInput" />
      </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="参数名称" maxlength="10" disabled />
          <el-input v-model="item.paramContent" class="param-info" placeholder="请输入参数信息" maxlength="50" disabled />
          <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 '@/views/components/uploadImage.vue'
import { saveProduct, getProductById } from '@/api/product'
import { fetchBrandList } from '@/api/brand'
import { mapGetters } from 'vuex'
export default {
  components: { UploadImage },
  data() {
    return {
      isLoading: false,
      paramsCount: 4,
      formData: {
        authUserId: '',
        authId: '', //	授权id
        certificateImage: '', //	授权牌照
        createBy: '', //	创建人id
        // 	设备参数列表
        paramList: [],
        productId: '', //	授权设备id
        productImage: '', //	设备图片
        productName: '', //	设备名称
        snCode: '', //	设备SN码
        brandId: ''
      },
      paramList: [],
      brandList: [],
      rules: {
        certificateImage: [{ required: true, message: '授权牌照不能为空' }],
        paramList: [{ required: true, message: '参数不能为空' }],
        productImage: [{ required: true, message: '设备图片不能为空' }],
        snCode: [{ required: true, message: 'SN码不能为空' }],
        productName: [
          { required: true, message: '设备名称不能为空' },
          { max: 50, message: '字数在50字符以内' }
        ]
      },
      fileList1: [],
      fileList2: []
    }
  },
  computed: {
    ...mapGetters(['authUserId', 'proxyInfo', 'shopType', 'brandId'])
  },
  watch: {
    paramList: {
      deep: true,
      handler: function() {
        this.formData.paramList = this.setParamToFormData()
      }
    }
  },
  created() {
    this.formData.productId = parseInt(this.$route.query.id)
    this.formData.authUserId = this.proxyInfo?.authUserId || this.authUserId
    this.initFormData()
    if (this.shopType === 2) {
      this.getBrandList()
    }
    // 如果供应商类型为品牌方，则自动设置品牌id
    if (this.shopType === 1) {
      this.formData.brandId = this.proxyInfo?.brandId || this.brandId || ''
    }
  },
  methods: {
    // 提交
    submit() {
      this.formData.paramList = this.setParamToFormData()
      this.$refs.addFormRef.validate(valide => {
        if (valide) {
          this.save()
        }
      })
    },
    // 初始化表单数据
    initFormData() {
      this.isLoading = true
      getProductById({ productId: this.formData.productId }).then(res => {
        console.log(res)
        // const { authId, certificateImage, paramList, productId, productImage, productName, snCode, status } = res.data
        for (const key in res.data) {
          if (Object.hasOwnProperty.call(res.data, key)) {
            if (key !== 'paramList') {
              this.formData[key] = res.data[key]
            }
          }
        }
        // 初始化参数
        this.paramList = res.data.paramList
        this.paramsCount = this.paramList.length
        if (this.paramsCount < 4) {
          this.initParamList(4 - this.paramsCount)
        }
        this.initImageList()
        this.isLoading = false
      })
    },
    // 获取品牌信息
    getBrandList() {
      fetchBrandList({ type: 3, authUserId: this.formData.authUserId }).then(res => {
        console.log(res)
        this.brandList = res.data
      })
    },
    // 初始化上传图片列表
    initImageList() {
      setTimeout(() => {
        const productImage = this.formData.productImage
        const certificateImage = this.formData.certificateImage
        if (productImage) {
          this.fileList1.push({ name: 'productImage', url: productImage })
        }
        if (certificateImage) {
          this.fileList2.push({ name: 'certificateImage', url: certificateImage })
        }
      }, 200)
    },
    // 保存表单数据
    save() {
      this.isLoading = true
      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.$store.dispatch('tagsView/delView', this.$route)
          this.$router.back()
        })
        .finally(() => {
          this.isLoading = false
        })
    },
    // 保存参数到formdata
    setParamToFormData() {
      return this.paramList.filter(item => item.paramContent !== '' && item.paramName !== '')
    },
    // 添加一栏参数
    handleAddParam() {
      this.paramsCount += 1
      this.paramList.push({
        paramContent: '',
        paramName: ''
      })
    },
    // 删除一栏参数
    handleRemoveParam(index) {
      this.paramsCount -= 1
      this.paramList.splice(index, 1)
    },
    // 图片上传成功 产品图片
    imageUploadSuccess1(data) {
      this.formData.productImage = data.data
    },
    // 图片上传成功 授权牌照
    imageUploadSuccess2(data) {
      this.formData.certificateImage = data.data
    },
    setParamList(data) {
      this.paramList = data.paramList
    },
    // 初始化参数列表
    initParamList(count) {
      for (let i = 0; i < count; i++) {
        this.paramList.push({
          paramContent: '',
          paramName: ''
        })
      }
    }
  }
}
</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: 500px;
  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>
