<template>
  <div v-loading="isLoading" class="edit-cate-info page-form-container">
    <el-form ref="form" :model="formData" :rules="rules" label-width="100px">
      <el-form-item prop="name" label="设备名称：">
        <el-input v-model="formData.name" placeholder="请输入设备名称" />
      </el-form-item>
      <el-form-item prop="image" label="设备图片：" class="pd-10">
        <el-input v-show="false" v-model="formData.image" />
        <upload-image
          tip="建议尺寸：542px * 542px"
          :image-list="productImageList"
          :before-upload="beforeUploadImage"
          @success="onUploadImageSuccess"
          @remove="onUploadImageRemove"
        />
      </el-form-item>
      <el-form-item label="所属品牌:" prop="infoId">
        <el-select v-model="formData.infoId" placeholder="请选择品牌" style="width: 100%" filterable clearable>
          <el-option v-for="item in brandList" :key="item.infoId" :label="item.brandName" :value="item.infoId" />
        </el-select>
      </el-form-item>
      <el-form-item label="相关参数:" prop="paramList">
        <div v-for="item in formData.paramList" :key="item.uuid" class="form-group">
          <el-input v-model="item.paramName" class="param-title" :placeholder="item.firstTip || '参数名称'" />
          <el-input v-model="item.paramContent" class="param-info" placeholder="请输入参数信息" />
          <span v-if="paramCount > 4" class="closed el-icon-close" @click="handleRemoveParam(item)" />
        </div>
        <el-button type="primary" size="mini" @click="handleAddParam">添加参数</el-button>
      </el-form-item>
    </el-form>
    <div class="submit-btn">
      <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 { tipList, resetFormData } from './configs'
import { createProductCate, fetchAuthProductFormData } from '@/api/product'
import { mapGetters } from 'vuex'
import { fetchBrandList } from '@/api/brand'

let uuid = 0

export default {
  components: {
    UploadImage
  },
  data() {
    const paramListValidate = (rules, value, callback) => {
      value.every((item) => item.paramName && item.paramContent)
      const notEmptyList = value.filter((item) => item.paramName.trim() && item.paramContent.trim())
      if (notEmptyList.length === 0) {
        callback(new Error('参数列表不能为空'))
      } else if (notEmptyList.length < 4) {
        callback(new Error('请填写至少4项参数'))
      } else {
        callback()
      }
    }

    const valideBrandId = (rules, value, callback) => {
      if (!value) {
        return callback(new Error('所属品牌不能为空'))
      }
      callback()
    }

    return {
      isLoading: false,
      formData: resetFormData(),
      rules: {
        name: [{ required: true, message: '请输入设备名称', trigger: ['blur'] }],
        image: [{ required: true, message: '请上传设备图片', trigger: ['change'] }],
        paramList: [
          { required: true, message: '请填写设备参数', trigger: ['change'] },
          { validator: paramListValidate, trigger: ['change'] }
        ],
        infoId: [{ required: true, validator: valideBrandId, trigger: 'change' }]
      },
      brandList: [],
      productImageList: []
    }
  },
  computed: {
    ...mapGetters(['authUserId']),
    // 参数长度
    paramCount() {
      return this.formData.paramList.length
    }
  },
  created() {
    this.initEmptyParamList()
    const type = this.$route.query.type
    this.getBrandList()
    if (type === 'edit') {
      this.fetchProductData()
    }
  },
  methods: {
    // 提交
    async submit() {
      this.isLoading = true
      try {
        await this.$refs.form.validate()
        this.createProductCate()
      } catch (error) {
        console.log(error)
        this.isLoading = false
      }
    },

    // 保存设备信息
    async createProductCate() {
      this.formData.authUserId = this.authUserId
      const data = {
        ...this.formData,
        paramList: this.generageParamList()
      }
      try {
        await createProductCate(data)
        this.$message.success('保存设备分类成功')
        this.$store.dispatch('tagsView/delView', this.$route)
        this.$router.push('device-cate')
      } catch (error) {
        console.log(error)
      } finally {
        this.isLoading = false
      }
    },

    // 获取设备数据信息
    async fetchProductData() {
      try {
        const id = this.$route.query.id
        const { data } = await fetchAuthProductFormData({ productTypeId: id })
        this.initProductData(data)
      } catch (error) {
        console.log(error)
      }
    },

    // 初始化设备信息
    initProductData(data) {
      for (const key in this.formData) {
        if (Object.hasOwnProperty.call(data, key)) {
          if (key === 'paramList') {
            this.initParamList(data[key])
          } else {
            this.formData[key] = data[key]
          }
        }
      }
      if (data.image) {
        this.productImageList = [{ name: '设备图片', url: this.formData.image }]
      }
    },

    // 获取品牌信息
    async getBrandList() {
      try {
        const { data } = await fetchBrandList()
        this.brandList = data
      } catch (error) {
        console.log(error)
      }
    },

    // 生成最终的设备参数
    generageParamList() {
      return this.formData.paramList.map((param) => ({
        paramContent: param.paramContent,
        paramName: param.paramName
      }))
    },

    // 初始化参数列表
    initParamList(list) {
      if (!list) return
      this.formData.paramList.splice(0, list.length, ...list)
    },

    // 初始化空参数列表
    initEmptyParamList() {
      for (const item of tipList) {
        this.formData.paramList.push({
          uuid: ++uuid,
          paramContent: '',
          paramName: '',
          firstTip: item
        })
      }
    },

    // 添加一栏参数
    handleAddParam() {
      this.formData.paramList.push({
        uuid: ++uuid,
        paramContent: '',
        paramName: ''
      })
    },

    // 删除一栏参数
    handleRemoveParam(index) {
      this.formData.paramList.splice(index, 1)
    },

    // 设备图片上传
    beforeUploadImage(file) {
      return true
    },
    onUploadImageSuccess({ response, file, fileList }) {
      this.formData.image = response.data
      this.productImageList = fileList
    },
    onUploadImageRemove({ file, fileList }) {
      this.formData.image = ''
      this.productImageList = []
    }
  }
}
</script>
<style lang="scss" scoped>
.edit-cate-info {
  .form-group {
    position: relative;
    margin-bottom: 2%;
    .param-title {
      width: 30%;
    }
    .param-info {
      width: 68%;
      margin-left: 2%;
    }

    .closed {
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      right: -20px;
      cursor: pointer;
      color: #ddd;
      &:hover {
        color: #333;
      }
    }
  }

  .submit-btn {
    text-align: center;
    margin-top: 60px;
    .el-button {
      width: 140px;
    }
  }
}
</style>
