<template>
  <div class="m-container">
    <h2>
      <el-page-header @back="onCancel"
                      :content="(pageType == 'create' ? '添加' : '修改') + '商品'"></el-page-header>
    </h2>

    <div class="m-core">
      <el-form :model="form"
               :rules="rules"
               ref="form"
               label-width="120px"
               style="width: 500px">
        <el-form-item label="品牌"
                      prop="brand">
          <el-input v-model.trim="form.brand"></el-input>
        </el-form-item>
        <el-form-item label="商品名称"
                      prop="name">
          <el-input v-model.trim="form.name"></el-input>
        </el-form-item>
        <el-form-item label="商品类型"
                      prop="type">
          <el-select v-model.trim="form.type">
            <el-option label="乐器"
                       value="INSTRUMENT"></el-option>
            <el-option label="辅件"
                       value="ACCESSORIES"></el-option>
            <el-option label="教材"
                       value="TEACHING"></el-option>
            <el-option label="教谱"
                       value="STAFF"></el-option>
            <el-option label="其它"
                       value="OTHER"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品分类"
                      prop="goodsCategoryId">
          <el-select v-model.trim="form.goodsCategoryId"
                     filterable>
            <el-option v-for="item in categoryList"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品型号"
                      prop="specification">
          <el-input v-model.trim="form.specification"></el-input>
        </el-form-item>
        <el-form-item label="商品价格"
                      prop="marketPrice">
          <el-input type="number"
                    @mousewheel.native.prevent
                    v-model.trim="form.marketPrice"></el-input>
        </el-form-item>
        <el-form-item label="商品团购价"
                      prop="groupPurchasePrice">
          <el-input type="number"
                    @mousewheel.native.prevent
                    v-model.trim="form.groupPurchasePrice"></el-input>
        </el-form-item>
        <el-form-item label="商品采购价"
                      prop="discountPrice">
          <el-input type="number"
                    @mousewheel.native.prevent
                    v-model.trim="form.discountPrice"></el-input>
        </el-form-item>
        <el-form-item label="商品图片"
                      prop="image">
          <el-upload class="avatar-uploader"
                     action="/api-web/uploadFile"
                     accept=".jpg, .jpeg, .png"
                     :headers="headers"
                     :show-file-list="false"
                     :on-success="handleAvatarSuccess"
                     :before-upload="beforeAvatarUpload">
            <img v-if="form.image"
                 :src="form.image"
                 class="avatar">
            <i v-else
               class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品描述"
                      prop="desc">
          <el-input type="textarea"
                    v-model.trim="form.desc"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="onSubmit('form')"
                     type="primary">立即{{ pageType == "create" ? '创建' : '修改' }}</el-button>
          <el-button @click="onReSet('form')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import { categoryListTree, goodsAdd, goodsUpdate, goodsSingleQuery } from '@/api/businessManager'
// import store from '@/store'
import { getToken } from '@/utils/auth'
let validPrice = (rule, value, callback) => {
  if (value == '' && typeof value == 'string' || value == null) {
    callback(new Error('请输入金额'))
  } else if (value < 0) {
    callback(new Error('输入金额必须大于或等于0'))
  } else if (value >= 100000) {
    callback(new Error('输入金额必须小于100000'))
  } else {
    callback()
  }
}
export default {
  name: 'shopOperation',
  data () {
    return {
      categoryList: [],
      pageType: null,
      headers: {
        Authorization: getToken()
      },
      form: {
        // brand: 'xxxl',
        // name: '长号',
        // type: 'INSTRUMENT',
        // goodsCategoryId: 7,
        // specification: 'xxxeed',
        // marketPrice: 10000,
        // groupPurchasePrice: 9000,
        // discountPrice: 8000,
        // image: null,
        // desc: 'C调、法式键、曲列、E键、白铜按键、台湾镍白'
        brand: null,
        name: null,
        type: null,
        goodsCategoryId: null,
        specification: null,
        marketPrice: null,
        groupPurchasePrice: null,
        discountPrice: null,
        image: null,
        desc: null
      },
      rules: {
        brand: [{ required: true, message: '请输入品牌', trigger: 'blur' },
        { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }],
        name: [{ required: true, message: '请输入商品名称', trigger: 'blur' },
        { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }],
        type: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
        goodsCategoryId: [{ required: true, message: '请选择商品类型', trigger: 'change' }],
        specification: [{ required: true, message: '请输入商品型号', trigger: 'blur' },
        { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }],
        marketPrice: [{ required: true, validator: validPrice, trigger: 'blur' }],
        groupPurchasePrice: [{ required: true, validator: validPrice, trigger: 'blur' }],
        discountPrice: [{ required: true, validator: validPrice, trigger: 'blur' }],
        // marketPrice: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        // groupPurchasePrice: [{ required: true, message: '请输入商品团购价', trigger: 'blur' }],
        // discountPrice: [{ required: true, message: '请输入商品采购价', trigger: 'blur' }],
        image: [{ required: true, message: '请选择图片', trigger: 'blur' }],
        desc: [{ required: true, message: '请输入商品描述', trigger: 'blur' }]
      },
      Fsearch: null,
      Frules: null
    }
  },
  created () {
    this.init()
  },
  activated () {
    this.init()
  },
  mounted () {

  },
  methods: {
    init () {
      let query = this.$route.query
      if (query.paramInfo) {
        let paramInfo = JSON.parse(query.paramInfo)
        this.pageType = paramInfo.type
        this.id = paramInfo.id
      }
      if (query.search) {
        this.Fsearch = query.search;
      }
      if (query.pageInfo) {
        this.Frules = query.pageInfo
      }
      this.getList()
      this.getCatagory()
    },
    onSubmit (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.pageType == 'create') {
            if (this.form.id) { // 判断有没有Id，如果有则删除
              delete this.form.id
            }
            this.form.status = 'YES' // 默认上架
            goodsAdd(this.form).then(res => {
              this.messageTips('添加', res)
            })
          } else if (this.pageType == 'update') {
            goodsUpdate(this.form).then(res => {
              this.messageTips('修改', res)
            })
          }
        } else {
          return false
        }
      })
    },
    messageTips (title, res) {
      if (res.code == 200) {
        this.$message.success(title + '成功')
        this.$router.push({ path: '/shopManager/shopManager', query: { pageInfo: this.Frules, searchForm: this.Fsearch } })
      } else {
        this.$message.error(res.msg)
      }
    },
    onCancel () {
      this.$router.push({ path: '/shopManager/shopManager', query: { pageInfo: this.Frules, searchForm: this.Fsearch } })
    },
    onReSet (formName) {
      this.$refs[formName].resetFields()
    },
    getList () {
      if (this.pageType == 'create') {
        this.form = {
          // brand: 'xxxl',
          // name: '长号',
          // type: 'INSTRUMENT',
          // goodsCategoryId: 7,
          // specification: 'xxxeed',
          // marketPrice: 10000,
          // groupPurchasePrice: 9000,
          // discountPrice: 8000,
          // image: null,
          // desc: 'C调、法式键、曲列、E键、白铜按键、台湾镍白'
          brand: null,
          name: null,
          type: null,
          goodsCategoryId: null,
          specification: null,
          marketPrice: null,
          groupPurchasePrice: null,
          discountPrice: null,
          image: null,
          desc: null
        }
        // console.log(this.$refs['form'])
        if (this.$refs['form']) {
          this.$refs['form'].resetFields();
        }

      } else {
        goodsSingleQuery(this.id).then(res => {
          if (res.code == 200) {
            let result = res.data
            this.form = {
              id: result.id,
              brand: result.brand,
              name: result.name,
              type: result.type,
              goodsCategoryId: result.goodsCategoryId,
              specification: result.specification,
              marketPrice: result.marketPrice,
              groupPurchasePrice: result.groupPurchasePrice,
              discountPrice: result.discountPrice,
              image: result.image,
              desc: result.desc
            }
          }
        })
      }

    },
    getCatagory () {
      categoryListTree({
        delFlag: 0,
        rows: 9999
      }).then(res => {
        let result = res.data
        if (res.code == 200) {
          let tempArray = []
          result.rows.forEach(row => {
            tempArray.push({
              label: row.name,
              value: row.id
            })
          })
          this.categoryList = tempArray
        }
      })
    },
    handleAvatarSuccess (res, file) {
      this.form.image = res.data.url

    },
    beforeAvatarUpload (file) {
      const imageType = {
        'image/png': true,
        'image/jpeg': true
      }
      const isImage = imageType[file.type]
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('只能上传图片格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isImage && isLt2M;
    },
  }
}
</script>
<style lang="scss" scoped>
.el-button--primary {
  background: #14928a;
  border-color: #14928a;
  color: #fff;
  &:hover,
  &:active,
  &:focus {
    background: #14928a;
    border-color: #14928a;
    color: #fff;
  }
}
.el-row {
  margin-top: 40px;
}
.el-col {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  justify-content: flex-end;
  margin-right: 50%;
}
.el-input-group {
  width: 200px;
  margin: 0 20px;
}
/deep/.el-tree-node__content {
  height: 40px !important;
}
/deep/.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: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>