<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      top="3vh"
      height="80%"
      width="40%"
      :visible.sync="dialogVisible"
      center
      @close="handleCancel"
    >
      <div class="el-dialog-div">
      <el-form
        :rules="rules"
        ref="dataForm"
        :model="temp"
        label-position="right"
        label-width="120px"
        style="height: 90%;"
      >
        <el-form-item label="分类" prop="categoryId"  class="is-required">
          <category-select v-model="temp.categoryId" @changeSelect="getCategory"/>
        </el-form-item>

        <el-form-item label="商品名" prop="productName"  class="is-required">
          <el-input v-model="temp.productName" placeholder="商品名" />
        </el-form-item>

        <el-form-item label="商品金额" prop="productAmount"  class="is-required">
          <el-input v-model="temp.productAmount" placeholder="商品金额" />
        </el-form-item>

        <el-form-item label="商品会员金额" prop="productMemberAmount"  class="is-required">
          <el-input v-model="temp.productMemberAmount" placeholder="商品会员金额" />
        </el-form-item>

        <el-form-item label="商品图片" prop="productImage"  class="is-required">
          <el-upload
            class="avatar-uploader"
            :action="''"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" style="width: 140px;height: 140px;">
            <div style="width: 140px;height: 140px;display: flex;justify-content: center;align-items: center;border: 1px solid #eee;"  v-else>
              <i class="el-icon-plus avatar-uploader-icon" ></i>
            </div>
          </el-upload>
          <x-cropper ref="iscropper"/>
        </el-form-item>

        <el-form-item label="库存管理" prop="stockControl"  class="is-required">
          <el-radio-group v-model="temp.stockControl" size="small">
            <el-radio-button label="0">关闭</el-radio-button>
            <el-radio-button label="1">开启</el-radio-button>
          </el-radio-group>
        </el-form-item>


        <el-form-item v-if="temp.stockControl==1" label="库存数量" prop="productCount"  class="is-required">
          <el-input v-model="temp.productCount" readonly placeholder="库存数量" />
        </el-form-item>

        <el-form-item label="提成方式" prop="pushType"  class="is-required">
          <el-radio-group v-model="temp.pushType" size="small">
            <el-radio-button label="0">固定金额</el-radio-button>
            <el-radio-button label="1">比例</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="提成金额" v-if="temp.pushType==0" prop="pushAmount"  class="is-required">
          <el-input v-model="temp.pushAmount" placeholder="提成金额" />
        </el-form-item>

        <el-form-item label="提成比例" v-if="temp.pushType==1" prop="pushPercent"  class="is-required">
          <el-input v-model="temp.pushPercent" placeholder="提成比例" />
        </el-form-item>

        <el-form-item label="状态" prop="productStatus"  class="is-required">
          <el-radio-group v-model="temp.productStatus" size="small">
            <el-radio-button label="0">正常</el-radio-button>
            <el-radio-button label="1">禁用</el-radio-button>
          </el-radio-group>
        </el-form-item>

<!--        <el-form-item label="所属门店" prop="shopId"  class="is-required">-->
<!--          <dept-select v-model="temp.shopId" @changeSelect="getDept"  style="width: 100%;"/>-->
<!--        </el-form-item>-->

      </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import { editProduct } from "@/api/business/product/product";
import {setRequiredFields} from "@/utils";
import CategorySelect from "@/views/common/business/categorySelect";
import XCropper from "@/views/common/XCropper";
import DeptSelect from "@/views/common/system/deptSelect";
const requiredFields = []

export default {
  name: "editForm",
  components: {DeptSelect, XCropper, CategorySelect},
  data() {
    return {
      rules: setRequiredFields(requiredFields),
      dialogVisible: false,
      temp: {
        productId:'',
        categoryId:'',
        categoryName:'',
        productName:'',
        productAmount:'',
        productMemberAmount:'',
        productImage:'',
        productCount:'',
        pushAmount:'',
        pushPercent:'',
        productStatus:0,
        shopId:'',
        shopName:'',
        pushType:0
      },
      imageUrl:''
    }
  },
  methods: {
    open(row) {
      this.temp = this.$options.data().temp
      this.temp = row
      if(this.temp.productImageUrl){
        this.imageUrl = this.baseUrl + this.temp.productImageUrl
      }
      this.dialogVisible = true
    },
    beforeAvatarUpload(file){
      console.log("进入了文件上传")
      let _this = this
      return new Promise((resolve, reject) => {
        let types = ['image/jpeg', 'image/jpg', 'image/png'];
        // let width = 140;
        // let height = 140;
        const isJPG = types.includes(file.type)
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isJPG) {
          _this.$message.error('上传图片只能是 JPG 或 png格式!')
          reject()
        }
        if (!isLt2M) {
          _this.$message.error('上传图片大小不能超过 2MB!')
          reject()
        }


        let _URL = window.URL || window.webkitURL;

        console.log( _this.$refs.iscropper)
        //上传前对图片进行裁剪
        _this.$refs.iscropper.showModal({
          img: _URL.createObjectURL(file) , // 裁剪图片的地址
          autoCropWidth: 140, // 默认生成截图框宽度
          autoCropHeight: 140, // 默认生成截图框高度
          fixedBox:true,
          success: res => {
            //拿到裁剪后图片没有name 属性
            //file的name属性为只读 不能手动设置
            //创建一个新的图片对象 设置原始文件名
            const cloneFile = new File([res.img], file.name);

            const formData = new FormData()
            //   console.log(param.file)
            //通过 append 函数往formdata对象里传参，这里传的是后端需求的接口信息
            formData.append('file', cloneFile)
            formData.append('fileSavePath', "productImage")

            //执行上传操作
            request({
              method: "post",
              url: "/upload",
              data: formData,
              headers: { "Content-Type": "multipart/form-data" },

            }).then(response => {
              //请求成功
              _this.handleAvatarSuccess(response,cloneFile)
            })

            resolve()
          }
        })
      })
    },
    handleAvatarSuccess(res,file) {

      if(res.code == 200){
        this.imageUrl = URL.createObjectURL(file);
        this.temp.productImage = res.data.fileId
      }else{
        this.imageUrl = '';
        this.temp.productImg	 = ''
      }
    },
    submit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          editProduct(this.temp).then(response => {
            this.handleCancel()
            this.$emit('ok', response.data)
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    handleCancel() {
      //初始化
      this.temp = this.$options.data().temp
      this.dialogVisible = false
      this.$refs['dataForm'].resetFields()
    },
    getCategory(e){
      console.log(e)
      this.temp.categoryName = e.categoryName
    },
    getDept(e){
      this.temp.shopName = e.deptName
    }
  },
}
</script>

<style scoped>

</style>
