<template>
  <div v-loading="isLoading" class="page-form-container">
    <el-form ref="submitForm" :model="formData" :rules="rules" label-width="140px">
      <el-form-item label="供应商名称:" prop="shopName">
        <el-input v-model="formData.shopName" placeholder="请输入供应商名称" maxlength="50" show-word-limit />
      </el-form-item>
      <el-form-item label="子账号标识:" prop="prefix">
        <el-input
          v-model="formData.prefix"
          placeholder="供应商唯一标识符（不可更改）"
          maxlength="10"
          show-word-limit
          :disabled="prefixDisabled"
        />
      </el-form-item>
      <el-form-item label="供应商类型:" prop="shopType">
        <el-select v-model="formData.shopType" placeholder="请选择供应商类型">
          <el-option label="品牌方" :value="1" />
          <el-option label="代理商" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="关联采美供应商:">
        <el-select v-model="formData.cmShopId" placeholder="请选择需要关联的供应商" clearable>
          <template v-for="shop in cmShopList">
            <el-option :key="shop.cmShopId" :label="shop.cmShopName" :value="shop.cmShopId" />
          </template>
        </el-select>
      </el-form-item>
      <el-form-item label="手机号:" prop="mobile">
        <div class="flex">
          <el-input
            v-model="formData.mobile"
            placeholder="请输入手机号"
            maxlength="11"
            show-word-limit
            @input="onMobileInput"
          />
          <div class="form-label-tip">（提示：该手机号为登录账号）</div>
        </div>
      </el-form-item>
      <el-form-item label="联系人:" prop="linkMan">
        <el-input v-model="formData.linkMan" placeholder="请输入联系人" maxlength="50" show-word-limit />
      </el-form-item>
      <el-form-item label="供应商logo:" prop="logo">
        <upload-image
          tip="建议尺寸：200px * 200px"
          :image-list="logoImageList"
          @success="onUploadLogoSuccess"
          @remove="onRemoveLogoImage"
        />
        <el-input v-show="false" v-model="formData.logo" />
      </el-form-item>
      <el-form-item label="旗下品牌:" prop="shopInfo">
        <template v-for="(item, index) in formData.shopInfo">
          <el-tag
            :key="index"
            effect="dark"
            closable
            type="success"
            @close="onRemoveBrand(index)"
            @click="onEditBrand('edit', item, index)"
          >
            <span>{{ item.brandName }}</span>
          </el-tag>
        </template>
        <el-tag type="primary" effect="dark" @click="onEditBrand('add')">添加品牌<span class="el-icon-plus" /></el-tag>
        <el-checkbox-group v-show="false" v-model="formData.shopInfo" />
      </el-form-item>
      <el-form-item label="微信公众号:" prop="wxAccountType">
        <el-select v-model="formData.wxAccountType" placeholder="请选择微信公众号类型" clearable>
          <el-option label="订阅号" :value="1" />
          <el-option label="服务号" :value="2" />
        </el-select>
      </el-form-item>
      <template v-if="formData.wxAccountType === 2">
        <el-form-item label="appID:" prop="appId">
          <el-input v-model="formData.appId" placeholder="请输入服务号appId" />
        </el-form-item>
        <el-form-item label="appSecret:" prop="appSecret">
          <el-input v-model="formData.appSecret" placeholder="请输入服务号appSecret" />
        </el-form-item>
      </template>
      <el-form-item label="供应商状态:" prop="shopStatus">
        <el-select v-model="formData.shopStatus" placeholder="请选择供应商状态">
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
    </el-form>

    <div class="control-box">
      <el-button type="warning" @click="navigateBack">返回</el-button>
      <el-button type="primary" @click="onSubmit">提交</el-button>
    </div>

    <!-- 品牌编辑dialog -->
    <el-dialog
      title="编辑品牌信息"
      width="36%"
      :visible.sync="brandEditVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <brand-edit-form v-if="brandEditVisible" ref="brandEditForm" :model="brandModel" @change="onBrandFormChange" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="onEditBrandCancel">取 消</el-button>
        <el-button type="primary" @click="onBrandSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import UploadImage from '@/components/UploadImage'
import { BrandEditForm } from '@/views/components'
import { deepClone } from '@/utils'
import { isMobile, validLowerCase } from '@/utils/validate'
import { fetchCmSupplierList, createSupplier, getSupplierById } from '@/api/supplier'
import { mapGetters } from 'vuex'

const generateBrandInfo = () => ({
  infoId: '',
  brandName: '',
  brandLogo: '',
  producePlace: '',
  manufacturer: ''
})

export default {
  components: {
    UploadImage,
    BrandEditForm
  },
  data() {
    const validMobile = (rule, value, callback) => {
      if (!isMobile(value)) {
        return callback(new Error('手机号格式不正确'))
      }
      return callback()
    }
    const prefixValidate = (rule, value, callback) => {
      if (!validLowerCase(value)) {
        return callback(new Error('标识符只能是小写字母'))
      }
      return callback()
    }
    return {
      isLoading: false,
      type: 'add',
      brandEditVisible: false,
      brandEditType: 'add',
      brandEditIndex: 0,
      prefix: '',
      formData: {
        prefix: '', // 供应商标记
        authUserId: '',
        createBy: '',
        shopName: '', // 供应商名称
        shopType: '', // 供应商类型
        mobile: '', // 手机号
        linkMan: '', // 联系人
        logo: '', // 代理商logo
        shopInfo: [],
        wxAccountType: '',
        appId: '',
        appSecret: '',
        shopStatus: 1, // 供应商状态,
        cmShopId: ''
      },
      rules: {
        shopName: [{ required: true, message: '请输入供应商名称', trigger: ['blur'] }],
        shopType: [{ required: true, message: '请选择供应商类型', trigger: ['change'] }],
        mobile: [
          { required: true, message: '请输入手机号', trigger: ['blur'] },
          { validator: validMobile, trigger: ['blur'] }
        ],
        linkMan: [{ required: true, message: '请输入联系人', trigger: ['blur'] }],
        prefix: [
          { required: true, message: '请输入供应商标识符', trigger: ['blur'] },
          { validator: prefixValidate, trigger: ['blur'] }
        ],
        logo: [{ required: true, message: '请上传供应商logo', trigger: ['change'] }],
        shopInfo: [{ required: true, type: 'array', message: '请至少添加一个品牌', trigger: ['change'] }],
        shopStatus: [{ required: true, message: '请选择供应商状态', trigger: ['change'] }],
        appId: [{ required: true, message: '请输入服务号appId', trigger: ['blur'] }],
        appSecret: [{ required: true, message: '请输入服务号appSecret', trigger: ['blur'] }]
      },
      brandModel: generateBrandInfo(),
      logoImageList: [],
      cmShopList: []
    }
  },
  computed: {
    ...mapGetters(['authUserId']),
    prefixDisabled() {
      return this.type === 'edit' && this.prefix && this.prefix.length > 0
    }
  },
  created() {
    this.fetchCmSupplierList()
    this.type = this.$route.query.type || 'add'
    console.log(this.type)
    if (this.type === 'edit') {
      this.fetchSupplierData()
    }
  },
  methods: {
    // 获取采美供应商列表
    async fetchCmSupplierList() {
      try {
        const res = await fetchCmSupplierList()
        this.cmShopList = res.data
      } catch (error) {
        console.log(error)
      }
    },

    // 获取供应商信息
    async fetchSupplierData() {
      try {
        this.isLoading = true
        this.formData.authUserId = this.$route.query.id
        const res = await getSupplierById({ authUserId: this.formData.authUserId })
        this.initFormData(res.data)
      } catch (error) {
        console.log(error)
      }
    },

    // 初始化表单信息
    initFormData(data) {
      for (const key in data) {
        if (Object.hasOwnProperty.call(this.formData, key)) {
          if (key === 'wxAccountType') {
            this.formData[key] = data[key] === 0 ? '' : data[key]
          } else if (key === 'cmShopId') {
            this.formData[key] = data[key] ? data[key] : ''
          } else {
            this.formData[key] = data[key]
          }
        }
      }
      if (this.formData.logo) {
        this.logoImageList = [{ url: this.formData.logo, name: '供应商logo' }]
      }

      this.prefix = data.prefix
      this.$nextTick(() => (this.isLoading = false))
    },

    // 保存
    async onSave() {
      try {
        this.isLoading = true
        await createSupplier(this.formatSubmitData())
        this.$message.success(`保存成功`)
        this.$store.dispatch('tagsView/delView', this.$route)
        this.$router.replace('/supplier/list')
      } catch (error) {
        console.log(error)
      } finally {
        this.isLoading = false
      }
    },

    // 请求字段格式处理
    formatSubmitData() {
      const data = deepClone(this.formData)
      if (data.wxAccountType === '') {
        data.wxAccountType = 0
      }
      if (data.createBy === '') {
        data.createBy = this.authUserId
      }
      return data
    },

    // 提交供应商信息
    async onSubmit() {
      try {
        await this.$refs.submitForm.validate()
        this.onSave()
      } catch (error) {
        console.log(error)
      }
    },

    // 品牌信息变化
    onBrandFormChange(data) {
      console.log(data)
      this.brandModel = data
    },

    // 品牌信息确认
    async onBrandSubmit() {
      try {
        await this.$refs.brandEditForm.validate()
        if (this.brandEditType === 'add') {
          this.formData.shopInfo.push(deepClone(this.brandModel))
        } else {
          this.formData.shopInfo.splice(this.brandEditIndex, 1, deepClone(this.brandModel))
        }
        this.brandEditVisible = false
      } catch (error) {
        console.log(error)
      }
    },

    // 编辑品牌事件
    onEditBrand(type, row, index) {
      this.brandEditType = type
      this.brandEditIndex = index
      this.brandModel = type === 'add' ? generateBrandInfo() : row
      this.brandEditVisible = true
    },

    // 品牌编辑取消
    onEditBrandCancel() {
      this.$refs.brandEditForm.clearValidate()
      this.brandEditVisible = false
    },

    // 删除品牌
    onRemoveBrand(index) {
      this.formData.shopInfo.splice(index, 1)
    },

    // 供应商logo上传成功
    onUploadLogoSuccess({ response, file, fileList }) {
      this.logoImageList = fileList
      this.formData.logo = response.data
    },

    // 移除供应商logo
    onRemoveLogoImage() {
      this.logoImageList = []
      this.formData.logo = ''
    },

    // 输入手机号时
    onMobileInput() {
      this.formData.mobile = this.formData.mobile.replace(/[^\w\.\/]/gi, '')
    }
  }
}
</script>
<style lang="scss" scoped>
.el-tag {
  cursor: pointer;
  margin-right: 8px;
}
.el-select {
  width: 100%;
}

.flex {
  display: flex;
  .form-label-tip {
    white-space: nowrap;
    margin-left: 6px;
    font-size: 12px;
  }
}
</style>
