<!--
  @description: 商品管理-新增商品弹框
  @Modifier：杨胜国
  @date 2021-7-03- 14:20
-->
<template>
  <el-dialog
    v-dialogDrag
    top="3vh"
    :visible.sync="dialog"
    :close-on-click-modal="false"
    :title="titleName"
    width="1040px"
    destroy-on-close
    custom-class="el-dialog__body-p0 shop_mall_dialog"
  >
    <!--搜索-->
    <div class="p0-16">
      <el-tabs v-model="activeName" @tab-click="tabClick">
        <el-tab-pane
          v-for="(item,index) in tabList"
          :key="index"
          :label="item.name"
          :name="item.code"
        />
      </el-tabs>
    </div>
    <!--查询列表-->
    <el-form
      ref="fromData"
      :rules="rules"
      :model="formData"
      :inline-message="true"
      class="sortadd-form"
    >
      <div v-show="activeName === '01'">
        <table class="from_table">
          <tr>
            <td>
              <el-form-item ref="productCode" prop="productCode" label="商品编码" />
            </td>
            <td>
              <el-input v-model="formData.productCode" placeholder="商品编码自动生成" disabled />
            </td>
            <td>
              <el-form-item ref="productName" prop="productName" label="商品名称" />
            </td>
            <td>
              <el-input v-model="formData.productName" placeholder="请输入商品名称" />
            </td>
          </tr>
          <tr>
            <td>
              <el-form-item ref="brandName" prop="brandName" label="品牌" />
            </td>
            <td>
              <el-input v-model="formData.brandName	" placeholder="请输入品牌" />
            </td>
            <td>
              <el-form-item ref="productType" prop="productClassification" label="商品分类" />
            </td>
            <td>
              <gx-input
                v-model="formData.productClassification"
                placeholder="请选择"
                :title="formData.productClassification"
                gx-maxlength="varchar200"
                style="width:calc(100% - 135px)"
                disabled
                class="product_class"
              />
              <el-button type="purple" @click="buyersCheck">
                选择
              </el-button>
              <el-button @click="organTree('clear')">
                清空
              </el-button>
            </td>
          </tr>
          <tr>
            <td>
              <el-form-item ref="unit" prop="unit" label="商品单位" />
            </td>
            <td>
              <el-input v-model="formData.unit" placeholder="请输入商品单位" />
            </td>
            <td>
              <el-form-item ref="isAgreement" prop="isAgreement" label="协议供货" />
            </td>
            <td>
              <el-input v-model="formData.isAgreement" placeholder="" disabled />
            </td>
          </tr>
          <tr>
            <td>
              <el-form-item ref="productArea" prop="productArea" label="生产地" />
            </td>
            <td>
              <el-input v-model="formData.productArea" placeholder="请输入生产地" />
            </td>
            <td>
              <el-form-item ref="model" prop="model" label="型号" />
            </td>
            <td>
              <el-input v-model="formData.model" placeholder="请输入型号" />
            </td>
          </tr>
          <tr>
            <td>
              <el-form-item ref="protocolMiddleAgency" prop="protocolMiddleAgency" label="协议供货中间商" />
            </td>
            <td>
              <el-input v-model="formData.protocolMiddleAgency" placeholder="请输入协议供货中间商" />
            </td>
            <td>
              <el-form-item ref="inventoryQuantity" prop="inventoryQuantity" label="库存量" />
            </td>
            <td>
              <el-input v-model="formData.inventoryQuantity" type="number" placeholder="请输入库存量" />
            </td>
          </tr>
          <tr>
            <td>
              <el-form-item ref="marketPrice" prop="marketPrice" label="市场价(元)" />
            </td>
            <td>
              <el-input v-model="formData.marketPrice" type="number" placeholder="请输入市场价" />
            </td>
            <td>
              <el-form-item ref="commodityPrice" prop="commodityPrice" label="价格(元)" />
            </td>
            <td>
              <el-input v-model="formData.commodityPrice" type="number" placeholder="请输入价格" />
            </td>
          </tr>
          <!-- <tr>
            <td>
              <el-form-item ref="commissionRate" prop="commissionRate" label="佣金比例(%)" />
            </td>
            <td>
              <el-input v-model="formData.commissionRate" type="number" placeholder="请输入佣金比例" />
            </td>
            <td>
              <el-form-item ref="serviceAmount" prop="serviceAmount" label="服务费金额（元）" />
            </td>
            <td>
              <el-input v-model="formData.serviceAmount" type="number" placeholder="请输入服务费金额" />
            </td>
          </tr> -->
          <tr>
            <td>
              <el-form-item ref="type" label="商品类型" prop="type" />
            </td>
            <td>
              <el-radio-group v-model="formData.productType">
                <el-radio v-for="(item,index) in typeList" :key="index" :label="item.typecode">
                  {{ item.typename }}
                </el-radio>
              </el-radio-group>
            </td>
            <td>
              <el-form-item ref="discountRange" label="有无折扣范围" prop="discountRange" />
            </td>
            <td>
              <el-radio-group v-model="formData.discountRange" @change="discountChange">
                <el-radio v-for="(item,index) in discountRangeList" :key="index" :label="item.typecode">
                  {{ item.typename }}
                </el-radio>
              </el-radio-group>
            </td>
          </tr>
          <!-- 折扣范围 -->
          <tr v-if="discountFlag" class="smwidth">
            <td>
              <el-form-item ref="productCode" prop="productCode" label="折扣范围" />
            </td>
            <td colspan="3">
              <div v-for="(item, ind) in formData.protocolDiscount" :key="ind" class="fl discount-con">
                <span>折扣单位：</span>
                <el-input v-model="item.discountUnit" />
                <span>折扣范围：</span>
                <el-input v-model="item.discountStartRange" type="number" />--
                <el-input v-model="item.discountEndRange" type="number" />
                <span>折扣率：</span>
                <el-input v-model="item.discountRate" type="number" />
                <el-button v-if="formData.protocolDiscount.length>1 && ind>0" type="danger" plain size="mini" @click="deleteDiscount(item,ind)">
                  删除
                </el-button>
              </div>
              <div class="fl addDiscount">
                <el-button
                  type="purple"
                  @click="addDiscount"
                >
                  添加
                </el-button>
              </div>
            </td>
          </tr>
          <tr>
            <td>
              <el-form-item ref="type" label="商品详情" prop="type" />
            </td>
            <td colspan="3">
              <editor v-model="formData.productDescription" :edit-height="260" style="margin: 12px 0" />
            </td>
          </tr>
        </table>
      </div>
      <div v-show="activeName === '02'">
        <table class="from_table">
          <!--添加主图--->
          <tr>
            <td style="width:6.5%;">
              <el-form-item label="主图 " prop="mainFile" />
            </td>
            <!-- :key="new Date()*1" -->
            <!--  -->
            <td colspan="3">
              <upload
                ref="upload"
                list-type="picture"
                :limit="1"
                :on-change="mainFileChange"
                :data="mainFileType"
                :file-list="fileList"
                :auto-delete="true"
                :auto-upload="true"
                file-ref="fileRef"
                but-text="图片上传"
                :title="''"
                accept="image/jpg,image/jpeg,image/png"
                tip-text="图片尺寸：400px*400px，最多1张图片，JPG/JPEG/EMP/PNG，最大15M，GIF最大3M"
              />
            </td>
          </tr>
          <tr>
            <td style="width:6.5%;">
              <!-- :on-change="thumbnailFileChange" prop="thumbnailFile"  -->
              <el-form-item label="缩略图 " />
            </td>
            <td colspan="3">
              <upload
                ref="upload"
                list-type="picture"
                :data="thumbnailFileType"
                :limit="3"
                :auto-delete="true"
                :auto-upload="true"
                file-ref="fileRef"
                but-text="图片上传"
                :title="''"
                accept="image/jpg,image/jpeg,image/png"
                tip-text="图片尺寸：200px*200px，最多3张图片，JPG/JPEG/EMP/PNG，最大15M，GIF最大3M"
              />
            </td>
          </tr>
        </table>
      </div>
    </el-form>
    <!--底部操作按钮-->
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" :loading="confirmFlag" @click="signatureConfirm">确 定</el-button>
      <el-button @click="dialog = false">取 消</el-button>
    </span>
    <!-- 所属机构弹框 -->
    <organTree-dialog ref="organTree" :dialog-data="selectVisibleDialog" @call-back="organTree" />
  </el-dialog>
</template>

<script>
/* api接口*/
import { addOrUpdateProductsInfo, getProductDetails } from '@/api/shoppingmall/products'
/* 公共组件*/
import upload from '@comp/common/updownload/upload'// 文件上传组件
import editor from '@comp/common/editor/editor' // 富文本编辑器组件
import organTreeDialog from './organTree-dialog' // 组织机构选择

/* 公用方法*/
// restoreInitialValue
import { filterObj } from '@/assets/js/utils'// 过滤空的key
import { characters1_auto, checkNum } from '@/assets/js/validate'// 校验输入内容
import { randomData } from '@assets/js/utils'// 清空value值

/* 组件*/
export default {
  name: 'CommodityManageDialog',
  components: {
    upload,
    editor,
    'organTree-dialog': organTreeDialog // 组织机构选择
  },
  props: {},
  data() {
    return {
      confirmFlag: false,
      loading: false,
      dialog: false, // 弹框是否打开
      activeName: '01', // tab name
      clickName: '',
      tabList: [
        { name: '商品信息', code: '01' },
        { name: '商品图片', code: '02' }
      ],
      typeList: [ // 暂时自定义
        { typename: '标准化商品', typecode: '00' },
        { typename: '非标准化商品', typecode: '01' }
      ],
      discountRangeList: [ // 暂时自定义 有无折扣范围
        { typename: '有折扣范围', typecode: '00' },
        { typename: '无折扣范围', typecode: '01' }
      ],
      titleName: '',
      formData: {
        productCode: '',
        productName: '',
        marketPrice: '', // 场价（含税)
        brandName: '', // 品牌
        isAgreement: '电商直采', // 固定值
        productArea: '', // 生产地
        model: '', // 型号
        unit: '', // 单位
        inventoryQuantity: '', // 库存
        commodityPrice: '', // 商品价格
        mainFile: '',
        // commissionRate: '', // 佣金比率
        // serviceAmount: null, // 服务费金额
        productType: '00', // 商品类型
        discountRange: '01', // 有无折扣范围
        productDescription: '',
        productClassification: '', // 产品分类名称
        productClassificationId: '', // 产品分类编码
        protocolDiscount: [{ // 折扣范围
          discountUnit: '', // 折扣单位
          discountStartRange: '', // 折扣开始范围
          discountEndRange: '', // 折扣结束范围
          discountRate: '' // 折扣率
        }]
      },
      selectVisibleDialog: {
        dialog: false
      },
      // 主图
      mainFileType: {
        bizId: '', // 业务主键Id
        fileType: 'ds_product_main_picture' // 文件类型
      },
      // 缩略图
      thumbnailFileType: {
        bizId: '', // 业务主键Id
        fileType: 'ds_product_auxiliary_picture' // 文件类型
      },
      discountFlag: false, // 折扣范围开关
      // 校验
      rules: {
        // productCode: [{ required: false, validator: characters1_auto, trigger: 'blur' }], // 商品编码
        productName: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 商品名称
        marketPrice: [{ required: true, validator: checkNum, trigger: 'blur' }], // 场价（含税)
        brandName: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 品牌
        isAgreement: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 是否使用协议
        productArea: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 生产地
        model: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 型号
        unit: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 单位
        inventoryQuantity: [{ required: true, validator: checkNum, trigger: 'blur' }], // 库存
        commodityPrice: [{ required: true, validator: checkNum, trigger: 'blur' }], // 商品价格
        // commissionRate: [{ required: true, validator: checkNum, trigger: 'blur' }], // 佣金比率
        // serviceAmount: [{ required: true, validator: checkNum, trigger: 'blur' }], // 服务费金额
        productClassification: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 商品分类
        productDescription: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 产品分类名称
        productType: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 商品类型
        discountRange: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 有无折扣范围
        mainFile: [{ required: true, message: '请上传', trigger: 'change' }] // 主图
      },
      tableData: [],
      // 分页
      paginationData: {
        pageNo: 1, // 当前页
        pageSize: 10, // 每页显示的个数
        total: 0 // 总记录条数
      },
      // tree默认选中的节点
      defaultCheckedKeys: [],
      fileList: []
    }
  },
  watch: {
    dialog(val) {
      // 关闭弹框重置表单
      if (!val) {
        this.resetFormVal()
      }
    }
  },
  methods: {
    // 加载数据
    openDialog(id) {
      this.loading = true
      this.initData(id)
    },
    initData(id) {
      this.dialog = true
      this.activeName = '01'
      if (id !== '') {
        getProductDetails(id).then(res => {
          this.formData = res.data
          this.formData.isAgreement = '电商直采'
          // 有无折扣范围
          if (this.formData.discountRange === '00') {
            this.discountFlag = true
          } else {
            this.discountFlag = false
          }
        })
        // 项目采购邀请函
        this.mainFileType.bizId = id
        // 项目采购文件
        this.thumbnailFileType.bizId = id
        this.titleName = '编辑'
      } else {
      /* 如果是新增商品 图片的id新生成 */
        // this.$nextTick(function() {
        //   restoreInitialValue(this.formData)
        // })
        this.dialog = true
        this.titleName = '新增'
        const randId = randomData()// 主键id
        this.formData.id = randId
        this.mainFileType.bizId = this.formData.id // 主图
        this.thumbnailFileType.bizId = this.formData.id // 缩略图
        this.formData.protocolDiscount = [{ // 折扣范围
          discountUnit: '', // 折扣单位
          discountStartRange: '', // 折扣开始范围
          discountEndRange: '', // 折扣结束范围
          discountRate: '' // 折扣率
        }]
      }
    },
    // 查询条件
    getParams() {
      const param = {}
      param.pageNo = this.paginationData.pageNo
      param.pageSize = this.paginationData.pageSize
      return filterObj(param)// 过滤空的key
    },
    // 搜索重置
    resetForm(formName) {
      // restoreInitialValue(this.searchForm)// 重置参数
      this.search()// 搜索
    },
    // 搜索
    search() {
      this.paginationData.pageNo = 1
      this.paginationData.pageSize = 10
      this.loadData()
    },
    // 确定
    signatureConfirm() {
      this.$refs['fromData'].validate((valid) => {
        if (valid) {
          this.$confirm('是否确定提交？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            confirmButtonClass: 'confirmBtn',
            cancelButtonClass: 'cancelBtn',
            type: 'warning'
          }).then(() => {
            // 商品管理添加或编辑商品信息
            const data = {
              ...this.formData
            }
            addOrUpdateProductsInfo(data).then(res => {
              this.$message.success('提交成功')
              this.dialog = false
              this.$emit('saveSuccess', true)
            })
          }).catch(() => {
          })
        } else {
          // 附件
          if (this.formData.mainFile === '') {
            this.$message.warning('请上传商品主图！')
          } else {
            this.$message.warning('请确保商品信息已填写！')
          }
        }
      })
    },
    // 显示选择分类dialog
    buyersCheck(index) {
      this.selectVisibleDialog.dialog = true
    },
    // 选择/清空采购人
    organTree(data) {
      // 清空
      if (data === 'clear') {
        this.formData.productClassification = ''
        this.formData.productClassificationId = ''
        // this.formData.buyersCode = ''
      } else {
        // 选择
        this.$set(this.formData, 'productClassification', data.labels)
        this.$set(this.formData, 'productClassificationId', data.classifyNo)
      }
    },
    //  主图
    mainFileChange(file, fileList) {
      this.confirmFlag = true
      if (fileList.length > 0) {
        // 因为附件赋值比初始化的先执行 所以值被替换没了 现在让他延迟赋值
        setTimeout(() => {
          this.$set(this.formData, 'mainFile', 'true')// 上传了
          this.confirmFlag = false
        }, 1000)
      } else {
        setTimeout(() => {
          this.$set(this.formData, 'mainFile', '')// 未上传
          this.confirmFlag = false
        }, 1000)
      }
    },
    //  缩略图
    thumbnailFileChange(file, fileList) {
      if (fileList.length > 0) {
        this.$set(this.formData, 'thumbnailFile', 'true')// 上传了
      } else {
        this.$set(this.formData, 'thumbnailFile', '')// 未上传
      }
    },
    // 有无折扣范围
    discountChange(val) {
      if (val === '00') {
        this.discountFlag = true
      } else {
        this.discountFlag = false
      }
    },
    // 添加折扣
    addDiscount(index) {
      this.formData.protocolDiscount.push({ // 折扣范围
        discountUnit: '', // 折扣单位
        discountStartRange: '', // 折扣开始范围
        discountEndRange: '', // 折扣结束范围
        discountRate: '' // 折扣率
      })
    },
    // 删除折扣
    deleteDiscount(item, index) {
      this.formData.protocolDiscount.splice(index, 1)
    },
    // tab点击
    tabClick(tab) {
    // tabData tabs 的当前选项
      this.clickName = tab.name
    // this.loadData()
    },
    // 重置表单
    resetFormVal() {
      this.formData = {
        productCode: '',
        productName: '',
        marketPrice: '', // 场价（含税)
        brandName: '', // 品牌
        isAgreement: '电商直采', // 是否使用协议
        productArea: '', // 生产地
        model: '', // 型号
        unit: '', // 单位
        inventoryQuantity: '', // 库存
        commodityPrice: '', // 商品价格
        mainFile: '',
        // commissionRate: '', // 佣金比率
        // serviceAmount: null, // 服务费金额
        productType: '00', // 商品类型
        discountRange: '01', // 有无折扣范围
        productDescription: '',
        productClassification: '', // 产品分类名称
        productClassificationId: '', // 产品分类编码
        protocolDiscount: [{ // 折扣范围
          discountUnit: '', // 折扣单位
          discountStartRange: '', // 折扣开始范围
          discountEndRange: '', // 折扣结束范围
          discountRate: '' // 折扣率
        }]
      }
      this.mainFileType.bizId = '' // 主图
      this.thumbnailFileType.bizId = '' // 缩略图
    }
  }
}
</script>

<style scoped lang="less">
/deep/ .smwidth{
  .el-input{
   width: 14%;
  }
}
.discount-con{
  width: 86%;
  margin-bottom: 10px;
}
.addDiscount{
  position: absolute;
  right: 20px;
}
/deep/.product_class .show-word-limit-padding .el-input__inner {
  padding-right: 15px;
}
</style>
