<template>
  <div class="club-device">
    <template v-for="formItem in formList">
      <div :key="formItem.uid">
        <el-form :model="formItem" :rules="rules" ref="form">
          <el-form-item prop="productName" :label="`设备名称${formItem.uuid}:`">
            <el-select
              v-model="formItem.productName"
              filterable
              allow-create
              placeholder="请输入新设备名称或选择已有设备"
              @change="onProductNameChange(formItem, $event)"
            >
              <el-option
                v-for="item in deviceList"
                :key="item.productTypeId"
                :label="item.name"
                :value="item.productTypeId"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="productImage" label="设备图片:">
            <br />
            <el-input v-show="false" v-model="formItem.productImage"></el-input>
            <SimpleUploadImage
              :disabled="Boolean(formItem.productTypeId)"
              :limit="1"
              :image-list="formItem.productImageList"
              :before-upload="beforeProductImageUpload"
              @success="uploadProductImageSuccess(formItem, $event)"
              @remove="handleProductImageRemove(formItem, $event)"
            />
          </el-form-item>
          <el-form-item label="所属品牌:" prop="brandId">
            <el-select v-model="formItem.brandId" placeholder="请选择品牌">
              <el-option
                v-for="item in brandList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="purchaseWay" label="购买渠道:">
            <el-input
              placeholder="请输入购买渠道"
              v-model="formItem.purchaseWay"
            ></el-input>
          </el-form-item>
          <el-form-item prop="invoiceImage" label="发票:">
            <br />
            <el-input v-show="false" v-model="formItem.invoiceImage"></el-input>
            <SimpleUploadImage
              :limit="1"
              :image-list="formItem.invoiceImageList"
              :before-upload="beforeInvoiceImageUpload"
              @success="uploadInvoiceImageSuccess(formItem, $event)"
              @remove="handleInvoiceImageRemove(formItem, $event)"
            />
          </el-form-item>
          <el-form-item prop="snCode" label="设备SN码:">
            <el-input
              placeholder="请输入设备SN码"
              v-model="formItem.snCode"
            ></el-input>
          </el-form-item>
          <el-form-item prop="paramList" label="设备参数:">
            <br />
            <div class="device-param-list">
              <span class="add-param" @click="insertParam(formItem)"
                >添加参数</span
              >
              <template v-for="(param, index) in formItem.paramList">
                <div :key="index">
                  <div class="param flex justify-between mb-4">
                    <el-input
                      style="width: 40%"
                      placeholder="例如：品牌"
                      class="mr-2"
                      v-model="param.paramName"
                    ></el-input>
                    <el-input
                      placeholder="请输入参数信息"
                      v-model="param.paramContent"
                    ></el-input>
                    <span
                      class="remove el-icon-close"
                      @click="removeParam(formItem, index)"
                      v-if="formItem.paramList.length > 4"
                    ></span>
                  </div>
                </div>
              </template>
            </div>
          </el-form-item>
        </el-form>
        <el-divider></el-divider>
      </div>
    </template>

    <div class="add-device" @click="insertOne">
      <div class="add-icon"></div>
      添加设备
    </div>

    <SimpleDialog
      v-model="active"
      @confirm="active = false"
      :cancel="false"
      description="请慎重填写机构信息，认证通过后将无法更改!"
      :center="true"
    />
  </div>
</template>

<script>
import SimpleUploadImage from '@/components/SimpleUploadImage'
import { mapGetters } from 'vuex'
export default {
  components: {
    SimpleUploadImage,
  },
  data() {
    const productNameValidate = (rule, value, callback) => {
      if (value.toString().length > 50) {
        callback(new Error('设备名称长度需要在50个字符内'))
      } else {
        callback()
      }
    }

    return {
      active: true,
      uuid: 0, // 表单id
      productImageList: [],
      rules: {
        productName: [
          { required: true, message: '设备名称不能为空', trigger: ['change'] },
          { validator: productNameValidate, trigger: ['change'] },
        ],
        productImage: [
          { required: true, message: '设备图片不能为空', trigger: ['change'] },
        ],
        brandId: [
          { required: true, message: '所属品牌不能为空', trigger: ['change'] },
        ],
        snCode: [
          { required: true, message: '设备SN码不能为空', trigger: ['blur'] },
        ],
        paramList: [{ required: true, message: '参数不能为空' }],
      },
      formList: [],
      brandList: [],
      deviceList: [],
    }
  },

  computed: {
    ...mapGetters(['authUserId']),
  },

  created() {
    this.fetchBrandList()
    this.fetchDeviceList()
    this.initFormList()
  },

  methods: {
    // 表单验证
    validate() {
      this.$emit('step', this.formatFormList())
      return Promise.all(this.$refs.form.map((item) => item.validate()))
    },

    formatFormList() {
      const list = []
      this.formList.forEach((formItem) => {
        const obj = {}
        obj.productImage = formItem.productImage
        obj.productName = formItem.productName
        obj.snCode = formItem.snCode
        obj.brandId = formItem.brandId
        obj.productTypeId = formItem.productTypeId
        obj.purchaseWay = formItem.purchaseWay
        obj.invoiceImage = formItem.invoiceImage
        obj.paramList = formItem.paramList
        list.push(obj)
      })
      return list
    },

    generateFormData() {
      return {
        uuid: ++this.uuid,
        authUserId: '',
        authId: '', //	授权id
        createBy: '', //	创建人id
        // 	设备参数列表
        paramList: this.initParams(),
        productId: '', //	授权设备id
        productImage: '', //	设备图片
        productName: '', //	设备名称
        snCode: '', //	设备SN码
        brandId: '',
        productTypeId: '',
        purchaseWay: '', // 购买渠道
        invoiceImage: '', // 发票
        productImageList: [],
        invoiceImageList: [],
      }
    },

    generageProductParam() {
      return {
        paramContent: '',
        paramName: '',
      }
    },

    initParams() {
      const list = []
      for (let i = 0; i < 4; i++) {
        list.push(this.generageProductParam())
      }
      return list
    },

    insertParam(formItem) {
      formItem.paramList.push(this.generateFormData())
    },

    removeParam(formItem, index) {
      formItem.paramList.splice(index, 1)
    },

    initFormList() {
      this.formList.push(this.generateFormData())
      console.log(this.formList)
    },
    insertOne() {
      this.formList.push(this.generateFormData())
    },
    removeOne() {},
    onProductNameChange(formItem, value) {
      if (typeof value === 'number') {
        formItem.productTypeId = value
        const deviceInfo = this.deviceList.find(
          (item) => item.productTypeId === value
        )
        formItem.productImage = deviceInfo.image
        formItem.productImageList = [{ name: '', url: deviceInfo.image }]
      } else {
        formItem.productTypeId = ''
        formItem.productImage = ''
        formItem.productImageList = []
      }
    },

    // 获取品牌列表
    async fetchBrandList() {
      try {
        const res = await this.$http.api.fetchBrandList({
          type: 3,
          authUserId: this.authUserId,
        })
        this.brandList = res.data
      } catch (error) {
        console.log(error)
      }
    },

    // 获取设备列表
    async fetchDeviceList() {
      try {
        const res = await this.$http.api.fetchProductSelectList({
          authUserId: this.authUserId,
        })
        this.deviceList = res.data
      } catch (error) {
        console.log(error)
      }
    },

    // 产品图片上传
    beforeProductImageUpload(file) {
      const flag = file.size / 1024 / 1024 < 1
      if (!flag) {
        this.$message.error('上传产品图片大小不能超过 1MB!')
      }
      return flag
    },
    uploadProductImageSuccess(formItem, { response, file, fileList }) {
      formItem.productImageList = fileList
      formItem.productImage = response.data
    },
    handleProductImageRemove(formItem, { file, fileList }) {
      formItem.productImageList = fileList
      formItem.productImage = ''
    },

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

<style lang="scss" scoped>
// pc端
@media screen and (min-width: 768px) {
  .el-select {
    width: 100%;
  }
  .device-param-list {
    position: relative;
    .add-param {
      position: absolute;
      cursor: pointer;
      top: -40px;
      right: 0;
      text-decoration: underline;
      font-size: 14px;
      @include themify($themes) {
        color: themed('color');
      }
    }

    .param {
      position: relative;
      .remove {
        position: absolute;
        right: 0;
        top: 0;
        width: 20px;
        height: 20px;
        background: #f94b4b;
        border-radius: 2px;
        cursor: pointer;
        color: #fff;
        font-size: 14px;
        text-align: center;
        line-height: 20px;
      }
    }
  }

  .add-device {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 162px;
    height: 46px;
    border-radius: 4px;
    box-sizing: border-box;
    font-size: 18px;
    margin: 0 auto;
    cursor: pointer;

    @include themify($themes) {
      border: 1px solid themed('color');
      color: themed('color');
    }

    .add-icon {
      width: 20px;
      height: 20px;
      position: relative;
      margin-right: 16px;

      &::before,
      &::after {
        position: absolute;
        width: 3px;
        height: 20px;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        border-radius: 1px;
        content: '';
        display: block;
        @include themify($themes) {
          background: themed('color');
        }
      }
      &::after {
        transform: translate(-50%, -50%) rotateZ(90deg);
      }
    }
  }
}

// 移动端
@media screen and (max-width: 768px) {
  ::v-deep {
    .el-form-item__label {
      font-size: 3.4vw;
    }
  }
  .el-select {
    width: 100%;
  }
  .device-param-list {
    position: relative;
    .add-param {
      position: absolute;
      cursor: pointer;
      top: -40px;
      right: 0;
      font-size: 3.4vw;
      @include themify($themes) {
        color: themed('color');
      }
    }

    .param {
      position: relative;
      .remove {
        position: absolute;
        right: 0;
        top: 0;
        width: 4.4vw;
        height: 4.4vw;
        background: #f94b4b;
        border-radius: 0.2vw;
        cursor: pointer;
        color: #fff;
        font-size: 3.4vw;
        text-align: center;
        line-height: 4.4vw;
      }
    }
  }

  .add-device {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 31vw;
    height: 8.8vw;
    border-radius: 0.4vw;
    box-sizing: border-box;
    font-size: 3.4vw;
    margin: 0 auto;
    cursor: pointer;

    @include themify($themes) {
      border: 1px solid themed('color');
      color: themed('color');
    }

    .add-icon {
      width: 20px;
      height: 20px;
      position: relative;
      margin-right: 16px;

      &::before,
      &::after {
        position: absolute;
        width: 0.6vw;
        height: 4.1vw;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        border-radius: 1px;
        content: '';
        display: block;
        @include themify($themes) {
          background: themed('color');
        }
      }
      &::after {
        transform: translate(-50%, -50%) rotateZ(90deg);
      }
    }
  }
}
</style>
