<template>
  <div class="app-container goods-add">
    <el-divider content-position="left">商品信息</el-divider>
    <el-form ref="addItem" :rules="rules" :model="addData" label-width="120px">
      <el-row :gutter="40" style="width: 600px">
        <el-col :span="23">
          <el-form-item label="商品名称:" prop="title">
            <el-input v-model="addData.title" placeholder="请输入商品名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="23">
          <el-form-item label="商品主图:" prop="picUrl">
            <Upload v-model="mainPicUrl" :limit="10" />
            <br>
            <div class="tip">第一张图片将作为商品列表图片,最多上传10张,多张图片之间可随意调整位置，支持jpg、png格式上传，建议使用尺寸800x800像素以上、大小不超过1M的正方形图片；</div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="40" style="width: 500px">
        <el-col :span="23">
          <el-form-item label="支持盲豆兑换:" prop="exchangeShow">
            <el-switch
              v-model="addData.exchangeShow"
              :active-value="1"
              :inactive-value="0"
            />
            <div class="tip">关闭则不再兑换大厅显示，不支持盲豆兑换。</div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="40" style="width: 500px">
        <el-col :span="23">
          <el-form-item label="商品分类" prop="categoryId">
            <el-select
              v-model="addData.categoryId"
              placeholder="请选择商品分类"
              clearable
            >
              <el-option :label="item.name" :value="item.categoryId" v-for="(item, index) in goodsCategoryItemsList" :key="index" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
       <el-row :gutter="40" style="width: 500px">
        <el-col :span="23">
          <el-form-item label="商品标签">
            <el-select
              v-model="addData.tagIds"
              placeholder="请选择商品标签"
              multiple 
              clearable
            >
              <el-option :label="item.name" :value="item.tagId" v-for="(item, index) in goodsTagItemsList" :key="index" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left">价格库存</el-divider>
      <el-row>
        <el-col :span="23">
          <el-form-item label="启用多SKU:" prop="multiSku">
            <el-switch
              v-model="addData.multiSku"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="22">
          <el-form-item prop="skuList">
            <Spec ref="spec" @valid="update" :multiSku="addData.multiSku" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row v-if="addData.multiSku === 0" :gutter="40" style="width: 600px">
        <el-col :span="23">
          <el-form-item label="价格:" prop="value">
            <el-input v-model="addData.value" type="number" placeholder="请输入商品价格">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="23">
          <el-form-item label="兑换盲豆数量:" prop="value">
            <el-input :value="(addData.value * 10).toFixed(0)" type="number" readonly disabled>
              <template slot="append">盲豆</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="23">
          <el-form-item label="采购价格:" prop="cost">
            <el-input v-model="addData.cost" type="number" placeholder="请输入商品采购价格">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="23">
          <el-form-item label="库存:" prop="quantity">
            <el-input v-model="addData.quantity" type="number" placeholder="请输入商品库存">
              <template slot="append">件</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-divider content-position="left">商品详情</el-divider> -->
      <el-row>
        <el-col :span="22">
          <el-form-item label="商品详情" prop="description">
            <TinyEditor v-model="addData.description" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <br>
    <el-row>
      <el-col :span="24" style="text-align: center">
        <el-button type="info" @click="$router.replace('/goods/list')">取消</el-button>
        <el-button type="primary" @click="updateItem()">保存</el-button>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import Upload from '@/components/DragImageUpload'
import Spec from './components/spec'
import TinyEditor from '@/components/TinyEditor'
import { getGoodsDetail, addGoods } from '@/api/business/goods'
import { goodsCategoryItems } from '@/api/business/category'
import { goodsTagItems } from '@/api/business/tag'
import { publicFileGetUrl } from "@/api/common"
import { accDiv, accMul } from '@/utils/util'
export default {
  components: {
    TinyEditor,
    Upload,
    Spec
  },
  data() {
    return {
      IMG_URL: publicFileGetUrl,
      id: this.$route.query.id,
      goodsCategoryItemsList: [],
      goodsTagItemsList: [],
      addData: {
        multiSku: 0,
        description: ''
      },
      rules: {
        title: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        picUrl: [{ required: true, message: '请上传商品图片', trigger: 'change' }],
        categoryId: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
        exchangeShow: [{ required: true, message: '请选择是否支持盲豆兑换', trigger: 'change' }],
        multiSku: [{ required: true, message: '请选择SKU类型', trigger: 'change' }],
        value: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
          { pattern: /^([1-9]\d*(\.\d{1,2})?|([0](\.([0][1-9]|[1-9]\d{0,1}))))$/, message: "请输入正确的金额，最多两位小数", trigger: ["blur", "change"] }
        ],
        exchangePrice: [
          { required: true },
          // { pattern: /^([1-9]\d*)$/, message: "请输入正确的数字", trigger: ["blur", "change"] }
        ],
        cost: [
          { required: false, message: '请输入采购价格', trigger: 'blur' },
          { pattern: /^([1-9]\d*(\.\d{1,2})?|([0](\.([0][1-9]|[1-9]\d{0,1}))))$/, message: "请输入正确的金额，最多两位小数", trigger: ["blur", "change"] }
        ],
        quantity: [
          { required: true, message: '请输入库存', trigger: 'blur' },
          { pattern: /^([1-9]\d*)$/, message: "请输入正确的数字", trigger: ["blur", "change"] }
        ],
        description: [{ required: true, message: '请输入商品详情', trigger: 'blur' }]
      }
    }
  },
  computed: {
    mainPicUrl: {
      get() {
        return this.addData.picUrl ? this.addData.picUrl.split(',').map(item => {
          return {
            fileName: item
          }
        }) : []
      },
      set(val) {
        this.$set(this.addData, 'picUrl', val.map(item => { return item.fileName }).toString())
      }
    }
  },
  created() {
    this.getGoodsCategoryItems()
    this.getGoodsTagItems()
    if (this.id) {
      getGoodsDetail(this.id).then(res => {
        const { goodsId, title, picUrl, exchangeShow, multiSku, value, exchangePrice, cost, quantity, description, skuList, categoryId, tagIds } = res.data
        this.addData = {
          value: accDiv(value, 100),
          cost: cost == '' || cost == null ? '' : accDiv(cost, 100),
          goodsId, title, picUrl, exchangeShow, multiSku, exchangePrice, quantity, description, skuList, categoryId, tagIds
        }
        if (multiSku && skuList instanceof Array && skuList.length > 0) {
          this.$nextTick(() => {
            this.$refs.spec.setSkuList(skuList)
          })
        }
      })
    }
  },
  methods: {
    getGoodsCategoryItems(){
      goodsCategoryItems({}).then(res => {
        this.goodsCategoryItemsList = res && res.data
      })
    },
    getGoodsTagItems(){
      goodsTagItems({}).then(res => {
        this.goodsTagItemsList = res && res.data
      })
    },
    updateItem() {
      if (this.addData.multiSku == 1) {
        this.$refs.spec.getSkuList()
      } else {
        this.update()
      }
    },
    update(skuList) {
      this.$refs.addItem.validate((valid, items) => {
        if (valid) {
          this.addData.skuList = skuList
          const { value, cost, description, ...rest } = this.addData
          addGoods({...rest, ...{
            value: accMul(value, 100),
            cost: cost == '' || cost == null ? '' : accMul(cost, 100),
            exchangePrice: accMul(value, 10),
            description: encodeURI(description)
          }}).then(res => {
            if (res.code === 0) {
              this.$message({
                message: this.addData.goodsId ? '修改成功!' : '添加成功!',
                type: 'success'
              })
              this.$store.dispatch('tagsView/delView', this.$route)
              this.$router.go(-1)
            }
          })
        } else {
          if (items && Object.keys(items).length>0) {
            this.$message({
              message: items[Object.keys(items)[0]][0].message,
              type: 'warning'
            })
          }
        }
      })
    }
  }
}
</script>
<style lang="scss">
.goods-add {
  .tip {
    font-size: 12px;
    color: #999;
  }
  .el-divider {
    .is-left {
      color: #409EFF;
      font-size: 20px;
      font-weight: bolder;
      left: 10px;
    }
  }
}
</style>
