<template>
  <div class="app-container">
    <el-row class="m-t-0">
      <el-col :span="24">
        <el-container>
          <el-header height="42px" class="l-h-42 p-l-10 p-r-10 border border-b-n">
            <div class="l">
              <i v-if="pageState === 'add'" class="el-icon-plus f-s-20"></i>
              <i v-else class="el-icon-edit f-s-20"></i>
              <font class="m-l-10 f-s-18 fb">{{ $route.meta.title }}</font>
            </div>
          </el-header>
          <el-main class="border p-20 m-b-20">
            <el-form ref="form" :model="form" label-width="120px" :label-position="$store.state.app.isWideScreen?'top':'right'">
              <el-form-item v-if="pageState === 'add'" label="所属商铺">
                <SelectionShopId v-model="form.shop_id" />
              </el-form-item>
              <el-form-item label="所属分类">
                <SelectionPath v-model="form.path" :shop_id="form.shop_id" :defaultPath="form.path" />
              </el-form-item>
              <el-form-item label="商品名称">
                <el-input v-model="form.name" placeholder="商品名称" />
              </el-form-item>
              <el-form-item label="商品编号">
                <el-input v-model="form.spu_number" placeholder="商品编号，方便统筹" />
              </el-form-item>
              <el-form-item label="排序">
                <el-input v-model="form.sort" placeholder="数值大排在前面,缺省值为0" />
              </el-form-item>
              <el-form-item label="热销底数">
                <el-input v-model="form.hot" placeholder="用与前台显示虚假销量，虚假销量=热销底数+真实销量" />
              </el-form-item>
              <el-form-item :label="form.recommend === true ? '前台首页推荐' : '前台首页推荐'">
                <el-switch v-model="form.recommend" />
              </el-form-item>
              <el-form-item :label="form.show === true ? '前台显示' : '前台隐藏'">
                <el-switch v-model="form.show" />
              </el-form-item>
              <!-- 搜索标签 -->
              <el-form-item label="搜索标签">
                <el-tag :key="index" v-for="(tag, index) in form.pro_tag" closable :disable-transitions="false"
                  @close="handleCloseTag(tag)">
                  {{ tag }}
                </el-tag>
                <span class="" v-if="inputTagVisible">
                  <el-input class="input-new-tag" v-model="inputTagValue" ref="saveTagInput">
                  </el-input>
                  <el-button type="primary" @click="handleInputConfirm" icon="el-icon-plus">添加</el-button>
                </span>
                <el-button v-else @click="showTagInput" icon="el-icon-plus">点击添加</el-button>
              </el-form-item>
              <!-- 商品图片 -->
              <el-form-item label="商品图片">
                <el-upload class="avatar-uploader" drag name="file" :action="action" :headers="myheader"
                  :show-file-list="false" :on-success="handleUpSuccess" :on-error="handleUpErr"
                  :before-upload="beforeAvatarUpload">
                  <img v-if="form.upFile != ''"
                    :src="$store.state.settings.host + '/Data/UploadFiles/temp/' + form.upFile" class="avatar" />
                  <img v-else-if="form.oldFile != [] && form.upFile == ''"
                    :src="form.oldFile[0]" class="avatar" />
                  <template v-else>
                    <i class="el-icon-plus f-s-30 m-t-70 seatFontColor"></i>
                    <div class="el-upload__text"><em>建议288*216像素 <br> jpg png </em></div>
                  </template>
                </el-upload>
              </el-form-item>
              <!-- sku组 穿梭框 -->
              <el-form-item label="SKU组">
                <span class="" v-if="inputSkuVisible">
                  <el-input class="input-new-tag" v-model="inputSkuValue" ref="saveSkuInput">
                  </el-input>
                  <el-button type="primary" @click="addSkuTransfer" icon="el-icon-plus">添加</el-button>
                </span>
                <el-button v-else @click="showSkuInput" icon="el-icon-plus">添加规格</el-button>
                <div class="m-t-10 relative-container" v-for="(t, index) in form.bind_sku" :key="index">
                  <SkuTransfer :tit="t.tit" :val="t.value" :shop_id="shop_id" @input="handleTransferInput(index, $event)" />
                  <el-button type="danger" icon="el-icon-delete" class="absolute-center-button" @click="delBind_skuArr" />
                </div>
              </el-form-item>
              <!-- 表单提交 -->
              <el-form-item v-if="pageState == 'add' ? true : false">
                <el-button type="primary" icon="el-icon-plus" @click="addSpu">创建</el-button>
                <el-button @click="setForm({ shop_id: form.shop_id, path: form.path })" class="iconfont icon-qingchu">
                  <font class="m-l-5">重填</font>
                </el-button>
              </el-form-item>
              <el-form-item v-else>
                <el-button type="primary" icon="el-icon-edit" @click="saveSpu">更新</el-button>
              </el-form-item>
            </el-form>
          </el-main>
        </el-container>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import SelectionShopId from '@/components/SelectionShopId'
import SelectionPath from '@/components/SelectionPath'
import SkuTransfer from '@/components/SkuTransfer'

export default {
  name: 'SpuAdd',
  data () {
    return {
      action: this.$store.state.settings.baseURL + this.$store.state.settings.apiAdminPath + 'upImgFile',
      myheader: { token: this.$store.state.user.token },
      form: {
        shop_id: '',
        path: 'none',
        name: '',
        spu_number: '',
        sort: '',
        hot: '',
        recommend: false,
        show: false,
        pro_tag: [],
        bind_sku: [],
        upFile: '',
        oldFile: ''
      },
      spuId: this.$route.params.id, // get参数 获取商品id 没有为添加页面
      pageState: 'add', // 页面状态
      spu: null,
      inputTagVisible: false, // 搜索标签 添加按钮 输入框反向显示
      inputTagValue: '', // 搜索标签 输入框值
      inputSkuVisible: false, // sku组 添加按钮 输入框反向显示
      inputSkuValue: ''// sku组 输入框值
    }
  },
  components: {
    SelectionShopId,
    SelectionPath,
    SkuTransfer
  },
  computed: {
    // 获取商品spu列表
    spuList () {
      return this.$store.state.spuList
    },
    // 用来监听 用户选择selection控件的变化
    shop_id () {
      return this.form.shop_id
    }
  },
  methods: {
    /* sku组 规格 穿梭框 */
    addSkuTransfer () { // 添加穿梭框
      if (this.inputSkuValue !== '') {
        this.form.bind_sku.push({ tit: this.inputSkuValue, value: [] })// 叠加穿梭框组件
        this.inputSkuVisible = false// 隐藏输入框 显示添加按钮
        this.inputSkuValue = ''
      } else {
        this.$message.warning('请填写规格的名称，不可空置')
      }
    },
    showSkuInput () { // 显示输入框
      this.inputSkuVisible = true
      this.$nextTick(_ => {
        this.$refs.saveSkuInput.$refs.input.focus()
      })
    },
    handleTransferInput (index, val) { // input事件接收 组件变化的value值
      this.form.bind_sku[index].value = val
    },
    delBind_skuArr (index) {
      this.form.bind_sku.splice(index, 1)
    },
    // 搜索标签相关函数
    handleCloseTag (tag) { // 删除标签
      this.form.pro_tag.splice(this.form.pro_tag.indexOf(tag), 1)
    },
    showTagInput () { // 显示输入框
      this.inputTagVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm () { // 添加新的标签
      const inputValue = this.inputTagValue
      if (inputValue) {
        this.form.pro_tag.push(inputValue)
      }
      this.inputTagVisible = false// 隐藏输入框 显示添加按钮
      this.inputTagValue = ''
    },
    /* 文件上传表单 */
    handleUpSuccess (res) {
      if (res.status === 0) {
        this.$message.error(res.msg)
      } else {
        this.form.upFile = res.data
        this.$message.success(res.msg)
      }
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
      if (!isJPG) {
        this.$message.error('上传图片只能是JPG|PNG|GIF格式!')
      }
      return isJPG
    },
    handleUpErr () {
      this.$message.error('接口访问失败')
    },
    // 设置表单
    setForm (data) {
      this.form.shop_id = data.shop_id
      this.form.path = data.path
      this.form.name = data.name || ''
      this.form.spu_number = data.spu_number || ''
      this.form.sort = data.sort || ''
      this.form.hot = data.hot || ''
      this.form.recommend = data.recommend || false
      this.form.show = data.show || false
      this.form.pro_tag = data.pro_tag || []
      this.form.bind_sku = data.bind_sku || []
      this.form.upFile = data.upFile || ''
      this.form.oldFile = data.oldFile || ''
      if (Object.keys(data).length === 0) {
        this.$message.warning('清空表单')
      }
    },
    // 初始化页面 添加or编辑
    initPage () {
      if (this.spuId === undefined) {
        this.pageState = 'add'
      } else {
        this.pageState = 'edit'
        this.spu = this.spuList.find((item) => item.id === this.spuId)
        if (this.spu) {
          const data = {
            shop_id: this.spu.shop_id,
            path: this.spu.path,
            name: this.spu.name,
            spu_number: this.spu.spu_number,
            sort: this.spu.sort,
            hot: this.spu.hot,
            recommend: this.spu.recommend === '1',
            show: this.spu.show === '1',
            pro_tag: this.spu.pro_tag,
            bind_sku: this.spu.bind_sku,
            oldFile: this.spu.photo
          }
          this.setForm(data)
        }
      }
    },
    /**
     * @description: 创建新商品spu
     */
    async addSpu () {
      const res = await this.$store.dispatch('fetchAddSpu', this.form)
      if (res.data.status === 1) {
        this.$router.push('/spu/index')
      }
    },
    /**
     * @description: 更新商品spu
     */
    async saveSpu () {
      this.form.id = this.spuId
      const res = await this.$store.dispatch('fetchSaveSpu', this.form)
      if (res.data.status === 1) {
        this.$router.push('/spu/index')
      }
    }
  },
  watch: {
    spuList () {
      this.initPage()// 初始化页面
    },
    shop_id (newval, oldval) {
      if (oldval === '') { // shop_id从空值到得到值 既为刷新页面 此时初始化 编辑页面的表单
        this.initPage()// 初始化页面
      } else { // shop_id不是从空值得到值而是从一个值 变化成另外一个值 既为selection控件变动 此时给path一个未分类"none"
        this.form.path = 'none'// 所属商铺selection 更新时 所属分类改成未分类“none”
      }
    }
  },
  created () {
    if (this.spuList.length > 0) {
      this.initPage()// 初始化页面
    }
  }
}
</script>

<style scoped>
.line {
  text-align: center;
}

.el-tag {
  margin-right: 10px;
}

.input-new-tag {
  margin-right: 10px;
  width: 20%;
  vertical-align: bottom;
}

.relative-container {
  position: relative;
  width: 585px;
}

.absolute-center-button {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  margin-top: -130px;
  /* 根据按钮高度调整上边距，使按钮垂直居中 */
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-upload__text {
  line-height: 1.2em !important;
}
</style>
