<template>
  <div v-loading="isLoading" class="addSupplier">
    <el-form ref="addFormRef" :model="addData" :rules="rules" label-width="120px" class="addForm">
      <el-form-item label="供应商类型:" prop="shopType">
        <el-select v-model="addData.shopType" placeholder="请选择供应商类型" style="width: 100%" @change="getBrandList">
          <el-option label="品牌方" :value="1" />
          <el-option label="代理商" :value="2" />
        </el-select>
      </el-form-item>

      <!-- 供应商名称 -->
      <el-form-item v-if="addData.shopType===2" label="供应商名称:" prop="shopName">
        <el-input v-model="addData.shopName" placeholder="请输入供应商名称" />
      </el-form-item>

      <el-form-item v-if="addData.shopType===1" label="供应商名称:" prop="shopName">
        <el-select v-model="selectedBrandIndex" placeholder="请选择品牌" style="width: 100%" filterable @change="setShopName">
          <el-option
            v-for="(item,index) in brandList"
            :key="item.id"
            :label="item.name"
            :value="index"
          />
        </el-select>
      </el-form-item>
      <!-- 供应商名称END -->

      <el-form-item label="手机号:" prop="mobile">
        <el-input v-model="addData.mobile" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="联系人:" prop="linkMan">
        <el-input v-model="addData.linkMan" placeholder="请输入联系人" />
      </el-form-item>
      <el-form-item v-if="addData.shopType===2" label="所属品牌:" prop="brandId">
        <el-select v-model="addData.brandId" placeholder="请选择所属品牌" style="width: 100%" filterable @change="setShopName">
          <el-option
            v-for="(item,index) in brandList"
            :key="item.id"
            :label="item.name"
            :value="index"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="产地:" prop="countryId">
        <el-select v-model="addData.countryId" placeholder="产地" style="width: 100%" filterable>
          <el-option
            v-for="item in countryList"
            :key="item.countryId"
            :label="item.countryName"
            :value="item.countryId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="品牌logo:" class="no-input" prop="brandAuthLogo">
        <upload-image ref="uploadImageRef1" :file-list="fileList1" @success="imageUploadSuccess1" @error="imageUploadFaild1" />
        <el-input v-model="addData.brandAuthLogo" type="hidden" class="hiddenInput" />
      </el-form-item>
      <el-form-item label="官网认证链接:">
        <el-input v-model="addData.securityLink" placeholder="请输入官网认证链接" />
      </el-form-item>
      <template v-if="addData.shopType===2">
        <el-form-item label="代理声明:">
          <el-radio v-model="addData.statementType" :label="1">弹窗</el-radio>
          <el-radio v-model="addData.statementType" :label="2">链接</el-radio>
          <el-radio v-model="addData.statementType" :label="3">图片</el-radio>
          <el-radio v-model="addData.statementType" :label="4">文件</el-radio>
        </el-form-item>

        <el-form-item v-if="addData.statementType === 1" label="弹窗:" prop="statementContent">
          <el-input v-if="addData.statementType === 1" v-model="addData.statementContent" type="textarea" />
        </el-form-item>
        <el-form-item v-else-if="addData.statementType === 2" label="链接:" prop="statementLink">
          <el-input v-if="addData.statementType === 2" v-model="addData.statementLink" />
        </el-form-item>
        <el-form-item v-else-if="addData.statementType === 3" label="图片:" class="no-input" prop="statementImage">
          <upload-image v-if="addData.statementType === 3" ref="uploadImageRef2" :file-list="fileList2" @success="imageUploadSuccess2" @error="imageUploadFaild2" />
          <el-input v-model="addData.statementImage" type="hidden" class="hiddenInput" />
        </el-form-item>
        <el-form-item v-else label="文件:" prop="statementFileId">
          <upload-file v-if="addData.statementType === 4" ref="uploadFileRef" :file-list="fileList3" @success="fileUploadSuccess" @error="fileUploadFaild" />
          <el-input v-model="addData.statementFileId" type="hidden" class="hiddenInput" />
        </el-form-item>

      </template>
      <el-form-item label="供应商状态:">
        <el-select v-model="addData.shopStatus" 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="save">保存</el-button>
      <el-button type="warning" @click="$_back()">返回</el-button>
    </div>
  </div>
</template>

<script>
import UploadImage from '../components/uploadImage'
import UploadFile from '../components/uploadFile'
import { mapGetters } from 'vuex'
import { isMobile } from '@/utils/validate'
import { fetchBrandList } from '@/api/brand'
import { addSupplier, getSupplierById } from '@/api/supplier'

export default {
  components: { UploadImage, UploadFile },
  data() {
    var valideMobile = (rule, value, callback) => {
      if (!isMobile(value)) {
        callback(new Error('手机号格式不正确'))
      } else {
        callback()
      }
    }
    return {
      isLoading: false,

      addData: {
        authUserId: '', // 供应商id
        brandAuthLogo: '', //	品牌授权logo
        brandId: '', // 品牌id
        countryId: 1, // 产地国家id
        createBy: '', // 创建人用户id
        linkMan: '', // 联系人
        mobile: '', // 手机号
        securityLink: '', // 官网认证链接
        shopName: '', // 供应商名称
        shopStatus: 1, // 供应商状态：0停用 1启用
        shopType: 1, //	供应商类型：1品牌方，2代理商
        statementContent: '', // 声明弹窗内容
        statementLink: '', // 声明链接
        statementFileId: 'no file', //	声明文件id
        statementImage: '', // 声明图片
        statementType: 1 // 代理声明类型：1弹窗 2链接 3图片 4文件（.doc .ppt .pdf）
      },
      selectedBrandIndex: '',
      brandList: [], // 品牌列表
      // 表单校验规则
      rules: {
        shopType: [{ required: true, message: '供应商类型不能为空', trigger: 'change' }],
        shopName: [{ required: true, message: '供应商名称不能为空', trigger: ['blur', 'change'] }],
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { validator: valideMobile, trigger: 'blur' }
        ], // 手机号格式校验
        linkMan: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
        countryId: [{ required: true, message: '产地不能为空', trigger: 'change' }],
        brandAuthLogo: [{ required: true, message: '品牌logo不能为空' }],
        brandId: [{ required: true, message: '所属品牌不能为空', trigger: 'change' }],
        statementContent: [{ required: true, message: '声明不能为空', trigger: 'blur' }],
        statementLink: [{ required: true, message: '声明链接不能为空', trigger: 'blur' }],
        statementImage: [{ required: true, message: '声明图片不能为空' }],
        statementFileId: [{ required: true, message: '声明文件不能为空' }]
      },
      fileList1: [], // 已上传的图片列表 品牌logo
      fileList2: [], // 已上传的图片列表 声明图片
      fileList3: [] // 已上传的图片列表 声明文件
      // countryList: []
    }
  },
  computed: {
    ...mapGetters(['userIdentity', 'name', 'countryList', 'authUserId'])
  },
  created() {
    // 获取供应商id
    this.addData.authUserId = this.$route.query.id
    this.getInfoById(this.addData.authUserId)
  },
  methods: {
    // 初始添加供应商时的表单数据
    initAddForm(data) {
      this.setFormData(data)
      this.getBrandList(data.type)
    },
    // 查询供应商信息
    getInfoById(id) {
      this.isLoading = true
      getSupplierById({ authUserId: id })
        .then(res => {
          if (res.code === 0) {
            this.initAddForm(res.data)
          }
        })
        .catch(err => { console.log(err) })
        .finally(() => {
          this.isLoading = false
        })
    },
    // 为表单设置数据
    setFormData(data) {
      for (const key in this.addData) {
        if (Object.hasOwnProperty.call(data, key)) {
          this.addData[key] = data[key] || ''
        }
      }
      if (this.addData.brandAuthLogo) {
        this.fileList1.push({ name: 'authLogo', url: this.addData.brandAuthLogo })
      }
      if (this.addData.statementImage) {
        this.fileList2.push({ name: '声明图片', url: this.addData.statementImage })
      }
      if (data.statementFileName) {
        // this.fileList3.push({ name: '您已上传文件，不支持预览，可删除后重新上传', url: '' })
        this.fileList3.push({ name: data.statementFileName, url: '' })
      }
    },
    // 获取品牌列表
    getBrandList(type) {
      fetchBrandList({ type }).then(res => {
        if (res.code === 0) {
          this.brandList = res.data
        }
      }).catch(err => console.log(err))
    },

    // 保存表单数据
    async save() {
      this.isLoading = true
      this.addData.createBy = this.authUserId
      // this.uploadFile()
      await this.$refs.addFormRef.validate(valide => {
        if (!valide) {
          this.isLoading = false
          return
        }
        if (this.addData.statementFileId === 'no file') {
          this.addData.statementFileId = null
        }
        addSupplier(this.addData).then(res => {
          this.$message.success('修改成功')
          // this.$refs.addFormRef.resetFields()
        }).catch(err => {
          console.log(err)
          this.$message.danger('修改失败')
        }).finally(() => {
          this.isLoading = false
          this.$refs.addFormRef.resetFields()
          this.addData.securityLink = ''
        })
      })
    },
    // 设置品牌名称
    setShopName(index) {
      const fileList = []
      if (this.addData.shopType === 1) {
        this.addData.shopName = this.brandList[index]?.name
      }
      this.addData.brandAuthLogo = this.brandList[index]?.authLogo || ''
      if (this.brandList[index]?.authLogo) {
        fileList.push({ name: this.addData.shopName, url: this.brandList[index]?.authLogo || '' })
      }
      this.fileList1 = fileList
    },
    // 文件上传成功
    fileUploadSuccess(data) {
      this.addData.statementFileId = data.data
    },
    fileUploadFaild(err, file, fileList) {
      console.log(err)
    },

    // 图片上传成功 品牌logo
    imageUploadSuccess1(data) {
      this.addData.brandAuthLogo = data.data
    },
    imageUploadFaild1(err, file, fileList) {
      console.log(err)
    },

    // 图片上传成功 声明图片
    imageUploadSuccess2(data) {
      this.addData.statementImage = data.data
    },
    imageUploadFaild2(err, file, fileList) {
      console.log(err)
    }
  }
}
</script>

<style lang="scss" scoped>
.addSupplier {
  margin-bottom: 80px;
}
.addForm {
  width: 500px;
  margin: 0 auto;
  margin-top: 80px;
}
.submit-btn {
  text-align: center;
  .el-button {
    width: 140px;
  }
}
.hiddenInput{
  display: none;
}
</style>
