<template>
  <div class="m-container">
    <h2>
      <el-page-header @back="onCancel"
                      :content="(pageTitle[pageType]) + '商品'"></el-page-header>
    </h2>

    <div class="m-core">
      <el-form :model="form"
               :rules="rules"
               ref="form"
               label-width="120px">
        <el-form-item label="货号"
                      prop="sn">
          <el-input v-model.trim="form.sn"
                    :disabled="pageDisabled"
                    placeholder="请输入货号"
                    style="width: 400px"></el-input>
        </el-form-item>
        <el-form-item label="品牌"
                      prop="brand">
          <el-input v-model.trim="form.brand"
                    :disabled="pageDisabled"
                    placeholder="请输入品牌"
                    style="width: 400px"></el-input>
        </el-form-item>
        <!-- <el-form-item label="备查货号" prop="supplyChannel" v-if="pageType == 'create'">
          <el-input v-model.trim="form.supplyChannel" placeholder="请输入备查货号" style="width: 400px"></el-input>
        </el-form-item> -->
        <el-form-item label="商品名称"
                      prop="name">
          <el-input v-model.trim="form.name"
                    placeholder="请输入商品名称"
                    :disabled="pageDisabled"
                    style="width: 400px"></el-input>
        </el-form-item>
        <el-form-item label="商品类型"
                      prop="type">
          <el-select v-model.trim="form.type"
                     placeholder="请选择商品类型"
                     :disabled="pageDisabled"
                     style="width: 400px !important;">
            <el-option v-for="(item, index) in goodsType"
                       :key="index"
                       :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品分类"
                      prop="goodsCategoryId">
          <el-select v-model.trim="form.goodsCategoryId"
                     placeholder="请选择商品分类"
                     :disabled="pageDisabled"
                     style="width: 400px !important;"
                     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"
                    placeholder="请输入商品型号"
                    :disabled="pageDisabled"
                    style="width: 400px"></el-input>
        </el-form-item>
        <!-- <el-form-item label="内部库存" prop="stockCount">
          <el-input type="number" :disabled="pageType != 'create'" v-model.trim="form.stockCount" placeholder="请输入内部库存" style="width: 400px"></el-input>
        </el-form-item>
        <el-form-item label="税务库存" prop="taxStockCount">
          <el-input type="number" :disabled="pageType != 'create'" v-model.trim="form.taxStockCount" placeholder="请输入税务库存" style="width: 400px"></el-input>
        </el-form-item> -->
        <el-form-item label="库存类型"
                      prop="stockType">
          <el-select v-model="form.stockType"
                     placeholder="请选择库存类型"
                     :disabled="pageDisabled"
                     style="width: 400px !important;">
            <el-option v-for="(item, index) in stockType"
                       :key="index"
                       :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="市场价"
                      prop="marketPrice">
          <el-input type="number"
                    placeholder="请输入市场价"
                    :disabled="pageDisabled"
                    @mousewheel.native.prevent
                    v-model.trim="form.marketPrice"
                    style="width: 400px"></el-input>
        </el-form-item>
        <el-form-item label="零售价"
                      prop="discountPrice">
          <el-input type="number"
                    placeholder="请输入零售价"
                    @mousewheel.native.prevent
                    :disabled="pageDisabled"
                    v-model.trim="form.discountPrice"
                    style="width: 400px"></el-input>
        </el-form-item>
        <el-form-item label="商品团购价"
                      prop="groupPurchasePrice">
          <el-input type="number"
                    placeholder="请输入商品团购价"
                    @mousewheel.native.prevent
                    :disabled="pageDisabled"
                    v-model.trim="form.groupPurchasePrice"
                    style="width: 400px"></el-input>
        </el-form-item>
        <el-form-item label="学员是否展示"
                      prop="clientShow">
          <el-select v-model="form.clientShow"
                     placeholder="请选择学员是否展示"
                     style="width: 400px !important;">
            <el-option label="是"
                       :value="1"></el-option>
            <el-option label="否"
                       :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="教务端是否展示"
                      prop="educationalShow">
          <el-select v-model="form.educationalShow"
                     placeholder="请选择教务端是否展示"
                     style="width: 400px !important;">
            <el-option label="是"
                       :value="1"></el-option>
            <el-option label="否"
                       :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="乐团是否展示"
                      prop="musicGroupShow">
          <el-select v-model="form.musicGroupShow"
                     placeholder="请选择乐团是否展示"
                     style="width: 400px !important;">
            <el-option label="是"
                       :value="1"></el-option>
            <el-option label="否"
                       :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否库存预警"
                      prop="stockWarning">
          <el-select v-model="form.stockWarning"
                     placeholder="请选择库存预警"
                     :disabled="pageDisabled"
                     style="width: 400px !important;">
            <el-option label="是"
                       :value="1"></el-option>
            <el-option label="否"
                       :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品图片"
                      prop="image">
          <el-upload class="avatar-uploader"
                     action="/api-web/uploadFile"
                     accept=".jpg, .jpeg, .png"
                     :headers="headers"
                     :disabled="pageDisabled"
                     :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="brief">
          <el-input type="textarea"
                    v-model.trim="form.brief"
                    :disabled="pageDisabled"
                    style="width: 400px"></el-input>
        </el-form-item>
        <el-form-item label="商品详情"
                      prop="desc">
          <el-input type="textarea"
                    v-model.trim="form.desc"
                    :disabled="pageDisabled"
                    style="width: 400px"></el-input>
        </el-form-item>
        <el-form-item v-if="!pageDisabled">
          <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 {
  getToken
} from '@/utils/auth'
import { goodsType, stockType } from '@/utils/searchArray'
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()
  }
}
let validStock = (rule, value, callback) => {
  if (value == '' && typeof value == 'string' || value == null) {
    callback(new Error('请输入库存'))
  } else if (value < 0) {
    callback(new Error('库存数量必须大于或等于0'))
  } else {
    callback()
  }
}
export default {
  name: 'shopOperation',
  data () {
    return {
      goodsType: goodsType,
      stockType: stockType,
      categoryList: [],
      pageType: null,
      pageTitle: {
        'create': '添加',
        'update': '修改',
        'look': '查看',
      },
      pageDisabled: false,
      headers: {
        Authorization: getToken()
      },
      form: {
        sn: null,
        brand: null,
        supplyChannel: null,
        name: null,
        type: null,
        goodsCategoryId: null,
        specification: null,
        stockCount: null,
        taxStockCount: null,
        stockType: null,
        marketPrice: null,
        discountPrice: null,
        groupPurchasePrice: null,
        clientShow: null,
        educationalShow: null,
        musicGroupShow: null,
        stockWarning: null,
        image: null,
        brief: null,
        desc: null
      },
      rules: {
        sn: [{ required: true, message: '请输入商品货号', trigger: 'blur' }],
        brand: [{
          required: true,
          message: '请输入品牌',
          trigger: 'blur'
        },
        {
          min: 2,
          max: 30,
          message: '长度在 2 到 30 个字符',
          trigger: 'blur'
        }
        ],
        supplyChannel: [
          { required: true, message: '请输入备查货号', 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'
        }
        ],
        stockCount: [
          { required: true, validator: validStock, trigger: 'blur' }
        ],
        taxStockCount: [
          { required: true, validator: validStock, trigger: 'blur' }
        ],
        stockType: [
          { required: true, message: '请选择库存类型', trigger: 'change' }
        ],
        marketPrice: [{
          required: true,
          validator: validPrice,
          trigger: 'blur'
        }],
        discountPrice: [{
          required: true,
          validator: validPrice,
          trigger: 'blur'
        }],
        groupPurchasePrice: [{
          required: true,
          validator: validPrice,
          trigger: 'blur'
        }],
        clientShow: [
          { required: true, message: '请选择学员是否展示', trigger: 'change' }
        ],
        educationalShow: [
          { required: true, message: '请选择教务端是否展示', trigger: 'change' }
        ],
        musicGroupShow: [
          { required: true, message: '请选择乐团是否展示', trigger: 'change' }
        ],
        stockWarning: [
          { required: true, message: '请选择是否库存预警', trigger: 'change' }
        ],
        image: [{
          required: true,
          message: '请选择图片',
          trigger: 'blur'
        }],
        brief: [{
          required: true,
          message: '请输入商品描述',
          trigger: 'blur'
        }],
        desc: [{
          required: true,
          message: '请输入商品详情',
          trigger: 'blur'
        }]
      },
      Fsearch: null,
      Frules: null,
      imageWidthM: 400,
      imageHeightM: 400
    }
  },
  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
      }
      this.pageDisabled = this.pageType == 'look' ? true : false
      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 = 'NO' // 默认上架
            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 = {
          sn: null,
          brand: null,
          supplyChannel: null,
          name: null,
          type: null,
          goodsCategoryId: null,
          specification: null,
          stockCount: null,
          taxStockCount: null,
          stockType: null,
          marketPrice: null,
          discountPrice: null,
          groupPurchasePrice: null,
          clientShow: null,
          educationalShow: null,
          musicGroupShow: null,
          stockWarning: null,
          image: null,
          brief: null,
          desc: null
        }
        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,
              sn: result.sn,
              brand: result.brand,
              supplyChannel: result.supplyChannel,
              name: result.name,
              type: result.type,
              goodsCategoryId: result.goodsCategoryId,
              specification: result.specification,
              stockCount: result.stockCount,
              taxStockCount: result.taxStockCount,
              stockType: result.stockType,
              marketPrice: result.marketPrice,
              discountPrice: result.discountPrice,
              groupPurchasePrice: result.groupPurchasePrice,
              clientShow: result.clientShow,
              educationalShow: result.educationalShow,
              musicGroupShow: result.musicGroupShow,
              stockWarning: result.stockWarning,
              image: result.image,
              brief: result.brief,
              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
      const imageWidth = this.imageWidthM
      const imageHeigh = this.imageHeightM
      const _URL = window.URL || window.webkitURL
      const isSize = new Promise((resolve, reject) => {
        const img = new Image()
        img.onload = function () {

          if (imageWidth && imageHeigh) {
            this.width === imageWidth && this.height === imageHeigh ? resolve() : reject(`请上传${imageWidth}x${imageHeigh}尺寸图片`)
          } else if (imageWidth && !imageHeigh) {
            this.width === imageWidth ? resolve() : reject(`请上传宽为${imageWidth}的图片`)
          } else if (!imageWidth && imageHeigh) {
            this.height === imageHeigh ? resolve() : reject(`请上传高为${imageHeigh}的图片`)
          }
          else {
            resolve()
          }

        }
        img.src = _URL.createObjectURL(file)
      }).then(
        () => {
          return file
        },
        (src) => {
          this.$message.error(src);
          this.uploadImgLoading = false
          return Promise.reject()
        }
      )
      console.log(isSize)
      if (!isImage) {
        this.$message.error('只能上传图片格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isImage && isLt2M && isSize;
    },
  }
}
</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>
