<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: 500px">
        <el-col :span="23">
          <el-form-item label="商品类型:" prop="type">
            <el-radio-group v-model="addData.type" :disabled="addData.goodsId">
              <el-radio :label="1">实物商品</el-radio>
              <el-radio :label="2">卡密商品</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <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"/>
            <div class="tip">第一张图片将作为商品列表图片，最多上传10张，多张图片之间可随意调整位置，支持jpg、png格式，推荐750*750px；</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-radio-group v-model="addData.exchangeShow">
              <el-radio :label="0">不支持</el-radio>
              <el-radio :label="1">支持</el-radio>
              <el-radio :label="2">盲票商品</el-radio>
            </el-radio-group>
          </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-cascader
              v-model="addData.categoryId" clearable
              :options="goodsCategoryItemsList"
              :props="{ expandTrigger: 'hover', value: 'categoryId',label: 'name', children: 'goodsCategoryList', }"></el-cascader>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="40" style="width: 500px">
        <el-col :span="23">
          <el-form-item label="供应商:" prop="supplierId">
            <el-select
              v-model="addData.supplierId"
              placeholder="请选择供应商"
              filterable
              clearable
            >
              <el-option :label="item.name" :value="item.id" v-for="(item, index) in SupplierList" :key="index"/>
            </el-select>
            <a style="margin-left: 20px;color: #1890FF;" @click="handleAdd">添加供应商</a>
          </el-form-item>

        </el-col>
      </el-row>
      <el-row :gutter="40" style="width: 500px">
        <el-col :span="23">
          <el-form-item label="商品采购链接:">
            <el-input v-model="addData.shoppingLink" placeholder="请输入商品采购链接"/>
          </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-col :span="23">
          <el-form-item label="商家信息:">
            <Upload v-model="MerchantInformation" :limit="10"/>
            <div class="tip">上传商家营业执照</div>
          </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:" v-if="addData.type == '1'">
            <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="exchangePrice">
            <el-input v-model="addData.exchangePrice" type="number" placeholder="请输入盲豆数量">
              <template slot="append">盲豆</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="23">
          <el-form-item label="回收折扣:" prop="discountRate">
            <el-input v-model="addData.discountRate" type="number" placeholder="请输入回收折扣">
              <template slot="append">%</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="23">
          <el-form-item label="盲豆划线价:">
            <el-input v-model="addData.originPrice" type="number" placeholder="请输入盲豆数量">
              <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="goodsCode">
            <el-input v-model="addData.goodsCode" type="text" placeholder="请输入商品编码">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="23">
          <el-form-item label="库存:" prop="quantity" v-if="addData.type == '1'">
            <el-input v-model="addData.quantity" type="number" placeholder="请输入商品库存">
              <template slot="append">件</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="23">
          <el-form-item label="卡密使用链接:" v-if="addData.type == '2'">
            <el-input v-model="addData.useLink" placeholder="请输入商品采购链接"/>
          </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">
            <wang-editor ref="editor" 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>
    <add-supplier
      v-if="createShow"
      :dialog-show="createShow"
      @close="close"
    />
  </div>
</template>
<script>
import Upload from '@/components/DragImageUpload'
import WangEditor from '@/components/WangEditor'
import Spec from './components/spec'
import TinyEditor from '@/components/TinyEditor'
import {getGoodsDetail, addGoods} from '@/api/business/goods'
import {goodsCategoryListTree} from '@/api/business/category'
import {getSupplierList} from '@/api/business/supplier'
import {goodsTagItems} from '@/api/business/tag'
import {publicFileGetUrl} from "@/api/common"
import {accDiv, accMul} from '@/utils/util'
import AddSupplier from "../supplier/components/addSupplier";
export default {
  name: 'GoodsAdd',
  components: {
    TinyEditor,
    WangEditor,
    Upload,
    Spec,
    AddSupplier,
  },
  data() {
    return {
      IMG_URL: publicFileGetUrl,
      id: this.$route.query.id,
      goodsCategoryItemsList: [],
      SupplierList: [],
      goodsTagItemsList: [],
      addData: {
        type: 1,
        multiSku: 0,
        description: '',
        originPrice: 0,
        exchangeShow: 0,
      },
      createShow: false,
      rules: {
        title: [{required: true, message: '请输入商品名称', trigger: 'blur'}],
        picUrl: [{required: true, message: '请上传商品图片', trigger: 'change'}],
        categoryId: [{required: true, message: '请选择商品分类', trigger: 'change'}],
        supplierId: [{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, message: '请输入盲豆数量', trigger: 'blur'},
          {pattern: /^([1-9]\d*)$/, message: "请输入正确盲豆数量", trigger: ["blur", "change"]}
        ],
        discountRate: [
          {required: true, message: '请输入回收折扣', trigger: 'blur'},
          {
            pattern:
              /^([0-9]\d*(\.\d{1,2})?|([0](\.([0][1-9]|[1-9]\d{0,1}))))$/,
            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())
      }
    },
    MerchantInformation: {
      get() {
        return this.addData.merchantInfo ? this.addData.merchantInfo.split(',').map(item => {
          return {
            fileName: item
          }
        }) : []
      },
      set(val) {
        this.$set(this.addData, 'merchantInfo', val.map(item => {
          return item.fileName
        }).toString())
      }
    }
  },
  created() {
    this.getGoodsCategoryItems()
    this.getSupplierItems()
    this.getGoodsTagItems()
    if (this.id) {
      getGoodsDetail(this.id).then(res => {
        const {
          goodsId,
          title,
          type,
          goodsCode,
          picUrl,
          merchantInfo,
          exchangeShow,
          multiSku,
          value,
          exchangePrice,
          originPrice,
          discountRate,
          cost,
          quantity,
          description,
          skuList,
          categoryId,
          supplierId,
          shoppingLink,
          tagIds,
          useLink
        } = res.data
        this.addData = {
          value: accDiv(value, 100),
          cost: cost == '' || cost == null ? '' : accDiv(cost, 100),
          goodsId,
          title,
          type,
          goodsCode,
          picUrl,
          merchantInfo,
          exchangeShow,
          multiSku,
          exchangePrice,
          discountRate,
          originPrice,
          quantity,
          description,
          skuList,
          categoryId,
          supplierId,
          shoppingLink,
          tagIds,
          useLink
        }
        if (description) {
          this.$refs.editor.setContent(description)
        }
        if (multiSku && skuList instanceof Array && skuList.length > 0) {
          this.$nextTick(() => {
            this.$refs.spec.setSkuList(skuList)
          })
        }
      })
    }
  },
  methods: {
    getGoodsCategoryItems() {
      goodsCategoryListTree("", {}).then(res => {
        this.goodsCategoryItemsList = res && res.rows
      })
    },
    //获取供应商
    getSupplierItems() {
      getSupplierList('', {name: ""}).then(res => {
        this.SupplierList = res && res.rows
      })
    },
    handleAdd() {
      this.createShow = true;
    },
    close() {
      this.createShow = false;
      this.getSupplierItems()
    },

    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, categoryId, cost, exchangePrice, description, ...rest} = this.addData
          addGoods({
            ...rest, ...{
              value: accMul(value, 100),
              cost: cost == '' || cost == null ? '' : accMul(cost, 100),
              exchangePrice: accMul(exchangePrice, 1),
              description: encodeURI(description),
              categoryId: categoryId[1],
            }
          }).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>
