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

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

      <el-form-item v-if="formData1.shopType === 1" clearable label="供应商名称:" prop="brandId">
        <el-select
          v-model="formData1.brandId"
          placeholder="请选择品牌"
          style="width: 100%"
          filterable
          @change="handleBrandChange"
        >
          <el-option v-for="item in brandList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <!-- 供应商名称END -->

      <el-form-item label="手机号:" prop="mobile">
        <el-input v-model="formData1.mobile" placeholder="请输入手机号" maxlength="11" show-word-limit @input="handleInput" />
      </el-form-item>

      <el-form-item label="联系人:" prop="linkMan">
        <el-input v-model="formData1.linkMan" placeholder="请输入联系人" />
      </el-form-item>

      <transition name="fade">
        <el-form-item v-if="formData1.shopType === 2" label="代理品牌:" prop="shopInfo" class="brand-list">
          <template v-if="supplierBrands !== []">
            <el-tag v-for="(brand , index) in supplierBrands" :key="index" closable type="success" @close="handleRemove(index)" @click="handleShowInfo(index)">{{ brand.brandName }}</el-tag>
          </template>
          <el-tag type="primary" @click="handleShowDialog">添加品牌<span class="el-icon-plus" /></el-tag>
          <!-- <el-input v-model="formData1.shopInfo" class="hiddenInput" /> -->
        </el-form-item>
      </transition>

      <template v-if="formData1.shopType === 1">
        <el-form-item label="产地:" prop="countryId">
          <el-select v-model="formData1.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"
            @remove="imageRemove1"
          />
          <el-input v-model="formData1.brandAuthLogo" type="hidden" class="hiddenInput" />
        </el-form-item>

        <el-form-item label="官网认证链接:">
          <el-input v-model="formData1.securityLink" placeholder="请输入官网认证链接" />
        </el-form-item>
      </template>

      <!-- 公众号信息 -->
      <el-form-item label="微信公众号:">
        <el-select v-model="formData1.appType" placeholder="请选择微信公众号类型" style="width: 100%">
          <el-option label="服务号" :value="1" />
          <el-option label="订阅号" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="appID:">
        <el-input v-model="formData1.appId" placeholder="微信公众号appID，没有就不填" />
      </el-form-item>
      <el-form-item label="appSecret:">
        <el-input v-model="formData1.appSecret" placeholder="微信公众号appsecret，没有就不填" />
      </el-form-item>
      <el-form-item label="公众号二维码:" prop="qrCodeImage">
        <upload-image
          ref="uploadImageRef1"
          :file-list="ewmUrl"
          tip-title="128px*128px"
          @success="wxImageUploadSuccess"
          @error="wxImageUploadFaild"
          @remove="wxImageUploadRemove"
        />
        <el-input v-model="formData1.qrCodeImage" type="hidden" class="hiddenInput" />
      </el-form-item>
      <!-- 公众号信息END -->
      <el-form-item label="供应商状态:">
        <el-select v-model="formData1.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="submit">保存</el-button>
      <el-button type="warning" @click="$_back()">返回</el-button>
    </div>

    <!-- 供应商添加品牌的对话框 -->
    <el-dialog :title="dialogTitleText" :visible.sync="showDialog" width="width" @closed="dialogClosed">
      <el-form ref="formData2Ref" :model="formData2" label-width="120px" :rules="formDataRules">

        <el-form-item label="选择品牌:" prop="brandId">
          <el-select
            v-model="formData2.brandId"
            placeholder="请选择品牌"
            style="width: 100%"
            filterable
            @change="handleBrandChange"
          >
            <el-option v-for="item in brandListCopy" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="产地:" prop="countryId">
          <el-select v-model="formData2.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="uploadImageRef2"
            :file-list="fileList2"
            @success="imageUploadSuccess2"
            @error="imageUploadFaild2"
            @remove="imageRemove2"
          />
          <el-input v-model="formData2.brandAuthLogo" type="hidden" class="hiddenInput" />
        </el-form-item>

        <el-form-item label="代理声明:">
          <el-radio-group v-model="formData2.statementType" @change="handleStatementChange">
            <el-radio :label="1">弹窗</el-radio>
            <el-radio :label="2">链接</el-radio>
            <el-radio :label="3">图片</el-radio>
            <el-radio :label="4">文件</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="formData2.statementType === 1" ref="statement1" label="弹窗:" prop="statementContent">
          <el-input
            v-if="formData2.statementType === 1"
            v-model="formData2.statementContent"
            type="textarea"
          />
        </el-form-item>

        <el-form-item v-else-if="formData2.statementType === 2" ref="statement2" label="链接:" prop="statementLink">
          <el-input v-if="formData2.statementType === 2" v-model="formData2.statementLink" />
        </el-form-item>

        <el-form-item
          v-else-if="formData2.statementType === 3"
          ref="statement3"
          label="图片:"
          class="no-input"
          prop="statementImage"
        >
          <upload-image
            v-if="formData2.statementType === 3"
            ref="uploadImageRef3"
            :file-list="fileList3"
            tip-title="宽：760px"
            @success="imageUploadSuccess3"
            @error="imageUploadFaild3"
            @remove="imageRemove3"
          />
          <el-input v-model="formData2.statementImage" type="hidden" class="hiddenInput" />
        </el-form-item>

        <el-form-item v-else ref="statementFileRef" label="文件:" prop="statementFileId">
          <upload-file
            v-if="formData2.statementType === 4"
            ref="uploadFileRef"
            :auth-user-id="formData2.authUserId"
            :brand-id="formData2.brandId"
            :file-list="fileList4"
            @success="fileUploadSuccess"
            @error="fileUploadFaild"
            @remove="fileRemove"
            @change="fileChange"
          />
          <el-input v-model="formData2.statementFileId" type="hidden" class="hiddenInput" />
        </el-form-item>

        <el-form-item label="官网认证链接:">
          <el-input v-model="formData2.securityLink" placeholder="请输入官网认证链接" />
        </el-form-item>

      </el-form>

      <div slot="footer">
        <el-button @click="showDialog = false">取 消</el-button>
        <el-button type="primary" :loading="dialogLoading" @click="handleAddBrand">确 定</el-button>
      </div>
    </el-dialog>

  </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 } from '@/api/supplier'

export default {
  components: { UploadImage, UploadFile },
  data() {
    const validMobile = (rule, value, callback) => {
      if (!isMobile(value)) {
        return callback(new Error('手机号格式不正确'))
      }
      return callback()
    }
    return {
      isCheckout: true,
      isLoading: false,
      dialogLoading: false,
      showDialog: false,
      excludeBrandList: [], // 已经选择的品牌，需要被排除在外的
      selectedShopType: 1,
      currentIndex: '',
      prevBrandId: '',
      dialogTitle: '添加',
      // 表单1
      formData1: {
        shopType: 1, // 供应商类型
        shopName: '', // 供应商名称
        brandId: '', // 品牌id
        mobile: '', // 手机号
        linkMan: '', // 联系人
        countryId: 1, // 产地id
        brandAuthLogo: '', // 品牌logo
        securityLink: '', // 官网认证链接
        shopStatus: 1, // 供应商状态,
        shopInfo: '',
        appType: '',
        appId: '',
        appSecret: '',
        qrCodeImage: '' // 微信公众号二维码
      },
      // 表单2
      formData2: {
        index: '',
        isNew: true,
        brandName: '',
        brandId: '', // 品牌id
        countryId: 1, // 产地id
        brandAuthLogo: '', // 品牌logo
        securityLink: '', // 官网认证链接
        statementType: 1, // 代理声明类型
        statementContent: '', // 声明内容
        statementFileId: null, // 声明文件id
        statementImage: '', // 声明图片
        statementLink: '', // 声明链接
        statementFileName: '' // 上传图片的名称
      },
      supplierBrands: [],
      brandList: [],
      // 表单数据校验
      formDataRules: {
        shopType: { required: true, message: '供应商类型不能为空', tigger: 'change', type: 'number' },
        shopName: { required: true, message: '供应名称不能为空', tigger: 'change' },
        mobile: [{ required: true, message: '手机号不能为空', tigger: 'change' }, { validator: validMobile, tigger: 'change' }],
        linkMan: { required: true, message: '联系人不能为空', tigger: 'blur' },
        countryId: { required: true, message: '产地不能为空', tigger: 'change', type: 'number' },
        brandAuthLogo: { required: true, message: '品牌logo不能为空', tigger: 'change' },
        shopInfo: { required: true, message: '代理品牌不能为空', tigger: 'change', type: 'string' },
        brandId: { required: true, message: '品牌不能为空', tigger: 'change', type: 'number' },
        statementContent: { required: true, message: '声明内容不能为空', tigger: 'change' }, // 声明内容
        statementFileId: { required: true, message: '声明文件不能为空', tigger: 'change', type: 'number' }, // 声明文件id
        statementImage: { required: true, message: '声明图片不能为空', tigger: 'change' }, // 声明图片
        statementLink: { required: true, message: '声明链接不能为空', tigger: 'change' } // 声明链接
        // ewmUrl: { required: true, message: '微信公众号二维码不能为空', tigger: 'change' }
      },
      // 上传的文件列表
      fileList1: [],
      fileList2: [],
      fileList3: [],
      fileList4: [], // 文件
      ewmUrl: []
    }
  },
  computed: {
    ...mapGetters(['countryList', 'authUserId']),
    brandListCopy() {
      return this.brandList.filter(item => {
        return !this.excludeBrandList.includes(item.id)
      })
    },
    dialogTitleText() {
      return `${this.dialogTitle}代理品牌`
    }
  },
  watch: {
    supplierBrands() {
      if (this.supplierBrands.length > 0) {
        this.formData1.shopInfo = '1'
      } else {
        this.formData1.shopInfo = ''
      }
    }
  },
  created() {
    this.getBrandList(1)
  },
  methods: {
    // 提交保存
    submit() {
      this.$refs.formData1Ref.validate(valid => {
        if (!valid) return
        this.isLoading = true
        addSupplier(this.setAddParams()).then(res => {
          if (res.code !== 0) {
            return
          }
          const h = this.$createElement
          this.$notify.success({
            title: '添加供应商',
            message: h('i', { style: 'color: #333' }, `已添加供应商："${this.formData1.shopName}"`),
            duration: 3000
          })
          this.$store.dispatch('tagsView/delView', this.$route)
          this.$router.push('/supplier')
        }).finally(() => {
          this.isLoading = false
        })
      })
    },
    // 封装请求参数
    setAddParams() {
      // 品牌方的参数列表
      const result = {
        authUserId: '',
        createBy: '',
        linkMan: '',
        mobile: '',
        shopName: '',
        shopStatus: '',
        shopType: '',
        shopInfo: [],
        qrCodeImage: '',
        appId: '',
        appSecret: ''
      }
      // 品牌方
      if (this.selectedShopType === 1) {
        for (const key in result) {
          if (Object.hasOwnProperty.call(result, key)) {
            if (key !== 'shopInfo') {
              result[key] = this.formData1[key]
            }
          }
        }
        result.shopInfo.push({
          brandId: this.formData1.brandId,
          countryId: this.formData1.countryId,
          brandAuthLogo: this.formData1.brandAuthLogo,
          securityLink: this.formData1.securityLink,
          statementType: 1,
          statementContent: '',
          statementFileId: null,
          statementImage: '',
          statementLink: ''
        })
      }

      // 代理商
      if (this.selectedShopType === 2) {
        for (const key in result) {
          if (Object.hasOwnProperty.call(result, key)) {
            if (key !== 'shopInfo') {
              result[key] = this.formData1[key]
            }
          }
        }
        result.shopInfo = this.supplierBrands
      }
      result.createBy = this.authUserId
      console.log(result)
      return result
    },

    // 获取品牌列表
    getBrandList(type) {
      fetchBrandList({ type }).then(res => {
        if (res.code !== 0) {
          return
        }
        this.brandList = res.data
      })
    },
    // 品牌改变事件
    handleBrandChange(id) {
      const selectBrand = this.brandList.filter(item => item.id === id)[0]
      // 选择品牌方
      if (this.formData1.shopType === 1) {
        this.fileList1 = []
        this.formData1.shopName = selectBrand.name
        this.formData1.brandAuthLogo = selectBrand.authLogo
        this.formData1.brandId = selectBrand.id
        if (selectBrand.authLogo) {
          this.fileList1 = [{ name: selectBrand.name, url: selectBrand.authLogo }]
        }
      }
      // 如果选择代理应商
      if (this.formData1.shopType === 2) {
        this.formData2.brandAuthLogo = selectBrand.authLogo
        this.formData2.brandName = selectBrand.name
        this.formData2.brandId = selectBrand.id
        if (selectBrand.authLogo) {
          this.fileList2 = [{ name: selectBrand.name, url: selectBrand.authLogo }]
        }
      }
    },
    // 添加品牌对话框
    handleShowDialog() {
      this.dialogTitle = '新增'
      this.showDialog = true
      this.resetFormData2()
    },
    // 添加品牌
    handleAddBrand() {
      this.dialogLoading = true
      // 如果声明类型为4，并且文件id为空或null，则需要先上传文件再保存
      if (this.formData2.statementType === 4 && (this.formData2.statementFileId === '' || this.formData2.statementFileId === null)) {
        this.$refs.uploadFileRef.$refs.upload.submit()
      } else {
        this.saveShopInfo()
      }
    },
    saveShopInfo() {
      this.dialogLoading = false
      this.$refs.formData2Ref.validate(valid => {
        if (!valid) {
          return
        }
        // 如果是新增的
        const shopInfo = this.clone(this.formData2)
        if (shopInfo.isNew) {
          this.supplierBrands.push(shopInfo)
        } else {
        // 修改的
          this.supplierBrands.splice(this.currentIndex, 1, shopInfo)
        }
        this.addExcludeBrand(shopInfo.brandId)
        shopInfo.isNew = false
        this.prevBrandId = ''
        this.showDialog = false
        const h = this.$createElement
        this.$notify.success({
          title: `${this.dialogTitle}品牌`,
          message: h('i', { style: 'color: #333' }, `${this.dialogTitle}品牌："${shopInfo.brandName}"`),
          duration: 2000
        })
      })
    },
    // 移除品牌
    handleRemove(index) {
      const pop = this.supplierBrands.splice(index, 1)[0]
      this.removeExcludeBrand(pop.brandId)
      const h = this.$createElement
      this.$notify.success({
        title: '移除品牌',
        message: h('i', { style: 'color: #333' }, `已移除品牌："${pop.brandName}"`),
        duration: 2000
      })
    },
    // 修改品牌
    handleShowInfo(index) {
      this.dialogTitle = '修改'
      this.currentIndex = index
      this.formData2 = this.clone(this.supplierBrands[index])
      this.prevBrandId = this.supplierBrands[index].brandId // 保存当前的品牌id
      this.fileList2 = [{ name: '', url: this.formData2.brandAuthLogo }]
      this.fileList3 = [{ name: '', url: this.formData2.statementImage }]
      this.fileList4 = [{ name: this.formData2.statementFileName, url: '' }]
      this.removeExcludeBrand(this.supplierBrands[index].brandId)
      this.showDialog = true
    },
    // 添加品牌对话框关闭
    dialogClosed() {
      if (this.prevBrandId) {
        this.addExcludeBrand(this.prevBrandId)
        this.prevBrandId = ''
      }
      this.resetFormData2()
    },
    // 声明类型切换
    handleStatementChange() {},
    // 供应商类型改变事件
    handleTypeChange(shopType) {
      this.selectedShopType = shopType
      this.getBrandList(shopType)
      this.resetFormData1(shopType)
    },
    // 添加排除品牌
    addExcludeBrand(id) {
      this.excludeBrandList.push(id)
    },
    // 移除排除品牌
    removeExcludeBrand(id) {
      const index = this.excludeBrandList.indexOf(id)
      this.excludeBrandList.splice(index, 1)
    },
    // 输入框输入时
    handleInput() {
      this.formData1.mobile = this.formData1.mobile.replace(/[^\w\.\/]/ig, '')
    },

    // 文件上传成功
    fileUploadSuccess(data) {
      this.formData2.statementFileName = data.data.fileName
      this.formData2.statementFileId = data.data.fileId
      if (data.code === 0) {
        this.saveShopInfo()
      }
    },
    fileUploadFaild(err, file, fileList) {
      this.$message.error('文件上传失败')
      console.log(err)
    },
    fileRemove() {
      this.formData2.statementFileId = null
      console.log('删除文件')
    },
    fileChange() {
      console.log('文件改变')
      this.$refs.statementFileRef.clearValidate()
    },

    // 图片上传成功 品牌logo  1
    imageUploadSuccess1(data) {
      this.formData1.brandAuthLogo = data.data
    },
    imageUploadFaild1(err, file, fileList) {
      this.$message.error('图片上传失败')
      console.log(err)
    },
    imageRemove1() {
      this.formData1.brandAuthLogo = ''
      console.log('删除图片')
    },
    // 图片上传成功 品牌logo 2
    imageUploadSuccess2(data) {
      this.formData2.brandAuthLogo = data.data
    },
    imageUploadFaild2(err, file, fileList) {
      this.$message.error('图片上传失败')
      console.log(err)
    },
    imageRemove2() {
      this.formData2.brandAuthLogo = ''
      console.log('删除图片')
    },
    // 图片上传成功 声明图片  3
    imageUploadSuccess3(data) {
      this.formData2.statementImage = data.data
    },
    imageUploadFaild3(err, file, fileList) {
      this.$message.error('图片上传失败')
      console.log(err)
    },
    imageRemove3() {
      this.formData2.statementImage = ''
      console.log('删除图片')
    },
    // 微信二维码上传
    wxImageUploadSuccess(data) {
      this.formData1.qrCodeImage = data.data
    },
    wxImageUploadFaild(err) {
      this.$message.error('图片上传失败')
      console.log(err)
    },
    wxImageUploadRemove() {
      this.formData1.qrCodeImage = ''
    },
    // 重置表单1
    resetFormData1(shopType) {
      this.formData1 = {
        shopType: shopType, // 供应商类型
        shopName: '', // 供应商名称
        brandId: '', // 品牌id
        mobile: '', // 手机号
        linkMan: '', // 联系人
        countryId: '', // 产地id
        brandAuthLogo: '', // 品牌logo
        securityLink: '', // 官网认证链接
        shopStatus: 1, // 供应商状态,
        shopInfo: [],
        qrCodeImage: ''
      }
      this.fileList1 = []
      this.fileList2 = []
      this.fileList3 = []
      this.fileList4 = []
      this.ewmUrl = []
      this.$refs.formData1Ref.clearValidate()
    },
    // 重置表单2
    resetFormData2() {
      this.formData2 = {
        index: '',
        isNew: true,
        brandName: '',
        brandId: '', // 品牌id
        countryId: 1, // 产地id
        brandAuthLogo: '', // 品牌logo
        securityLink: '', // 官网认证链接
        statementType: 1, // 代理声明类型
        statementContent: '', // 声明内容
        statementFileId: null, // 声明文件id
        statementImage: '', // 声明图片
        statementLink: '', // 声明链接
        statementFileName: ''
      }
      this.fileList1 = []
      this.fileList2 = []
      this.fileList3 = []
      this.fileList4 = []
      setTimeout(() => {
        this.$refs.formData2Ref.clearValidate()
      }, 200)
    },
    // 克隆
    clone(data) {
      const result = {}
      for (const key in data) {
        if (Object.hasOwnProperty.call(data, key)) {
          result[key] = data[key]
        }
      }
      return result
    }
  }
}
</script>

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