<template>
  <div class="create-shop-wrapper">
    <bread-crumb :curmbFirst="curmbFirst" :curmbSecond="curmbSecond" :curmbThird="curmbThird" :jumPathThird="jumPathThird"></bread-crumb>
    <div class="create-shop-content screenSet" id="screenSet">
      <el-row class="step-content">
        <el-col :span="20">
          <p class="title">{{title}}</p>
        </el-col>
        <el-col :span="4" style="text-align: right">
          <el-button size="small" type="primary" @click="complete">完成</el-button>
        </el-col>
      </el-row>
        <el-form
            ref="formData"
            :model="formData"
            :rules="rules"
            label-width="150px"
            label-suffix="："
            class="basic-form"
        >

          <div class="basic-item-icon">
            <div class="part-tit">通用信息</div>
            <el-form-item label="商品名称" prop="goodsName">
              <el-col :span="13">
                <el-input
                    size="small"
                    v-model="formData.goodsName"
                    placeholder="请输入商品名称"
                    show-word-limit
                    maxlength="60"
                ></el-input>
                <!-- <span class="word-num">{{(formData.goodsName).replace(/\s+/g,"").length}}/60</span> -->
              </el-col>
            </el-form-item>

            <el-form-item label="商品介绍" prop="goodsDescription">
              <el-col :span="13">
                <el-input
                    type="textarea"
                    rows="4"

                    size="small"
                    v-model="formData.goodsDescription"
                    placeholder="请输入商品介绍"
                    maxlength="1000"
                    show-word-limit
                ></el-input>
                <!-- <span class="word-num">{{(formData.goodsDescription).replace(/\s+/g,"").length}}/1000</span> -->
              </el-col>
            </el-form-item>

            <el-form-item label="商品头图" class="required-label">
              <el-upload
                  :file-list="fileGoodsList"
                  class="bg-uploader"
                  :show-file-list="isShowFileList"
                  action="#"
                  :before-upload="beforeUploadPic"
              >
                <div class="file-pics" v-if="fileGoodsList.length > 0" :key="index" v-for="(item,index) in fileGoodsList">
                  <img :src="item.url" @mouseover.stop="headIndex=index" class="bg-img"/>
                   <div
                       class="img-delete"
                       v-if="headIndex==index"
                       @click.stop="deleteImg(item,fileGoodsList)"
                       @mouseout.stop="headIndex=-1"
                   >
                     <i class="el-icon-delete"></i>
                   </div>
                </div>
                <img  class="bg-img" src="../../assets/image/small.png" v-if="fileGoodsList.length <10"/>
                <div class="limit-text">
                 <!-- <p>限制大小: 200kb</p> -->
                  <p>建议尺寸：750*420</p>
                  <p>支持jpeg, png格式</p>
                </div>
              </el-upload>
              <p class="upload-message" v-if="!isgoodsImages">请上传商品头图</p>
            </el-form-item>
            <el-form-item label="商品类型" prop="goodsType">
              <el-select
                  v-model="formData.goodsType"
                  placeholder="请选择商品类型"
                  size="small"
                  @change="getGoodsTypes(formData.goodsType,2)">
                <el-option
                    v-for="(item,index) in oneLever"
                    :key="index"
                    :label="item.categoryName"
                    :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- <p class="upload-message" v-if="uploadImgMessage1">请上传商品头图</p> -->
          </div>

          <div class="basic-item-icon" v-if="isMedic">
            <div class="part-tit">药品信息</div>
            <el-form-item label="条形码" prop="barCode">
              <el-col :span="18">
                <el-input
                    size="small"
                    v-model="formData.barCode"
                    placeholder="请输入条形码"
                ></el-input>
                <span class="fast-opt" @click="fastInput">快速录入</span>
                <span class="word-num">(点击可快速录入下面的药品信息)</span>
              </el-col>
            </el-form-item>
            <el-form-item label="批准文号" prop="approvalNumber">
              <el-col :span="18">
                <el-input
                    size="small"
                    v-model="formData.approvalNumber"
                    placeholder="请输入批准文号"
                    style="width:50%;"
                ></el-input>
              </el-col>
            </el-form-item>

            <el-form-item label="药品通用名称" prop="medicCommonName">
              <el-col :span="13">
                <el-input
                    size="small"
                    v-model="formData.medicCommonName"
                    placeholder="请输入药品通用名称"
                    style="width:70%;"
                    maxlength="60"
                    show-word-limit
                ></el-input>

               <!-- <span class="word-num">{{(formData.medicCommonName).replace(/\s+/g,"").length}}/60</span> -->
              </el-col>
            </el-form-item>
            <el-form-item label="药品商品名称" prop="medicGoodsName">
              <el-col :span="13">
                <el-input
                    size="small"
                    v-model="formData.medicGoodsName"
                    placeholder="请输入药品商品名称"

                    maxlength="60"
                    show-word-limit
                ></el-input>

                <!-- <span class="word-num">{{(formData.medicGoodsName).replace(/\s+/g,"").length}}/60</span> -->
              </el-col>
            </el-form-item>
            <el-form-item label="药品规格" prop="size">
              <el-col :span="13">
                <el-input
                    size="small"
                    v-model="formData.size"
                    placeholder="请输入药品规格"
                    style="width:70%;"
                ></el-input>

                <span class="word-num">例如:0.125g*12袋/盒</span>
              </el-col>
            </el-form-item>
            <div class="inline">
              <el-form-item label="是否是处方药" prop="otc1">
                <el-col :span="24">
                  <el-radio size="mini" v-model="formData.otc1" label="1">处方药</el-radio>
                  <el-radio v-model="formData.otc1" label="0">非处方药</el-radio>
                </el-col>
              </el-form-item>
              <el-form-item label="剂型" prop="dosageId">
                <el-select
                    v-model="formData.dosageId"
                    placeholder="请选择药品剂型"
                    size="small"
                    clearable>
                  <el-option
                      v-for="(item,index) in doseAll"
                      :key="index"
                      :label="item.dosageName"
                      :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </div>
            <el-form-item label="用法用量" prop="usage">
              <el-col :span="13">
                <el-input
                    size="small"
                    v-model="formData.usage"
                    placeholder="请输入用法用量"
                    style="width:70%;"
                ></el-input>

                <span class="word-num">例如:每次一袋 每天1-2次</span>
              </el-col>
            </el-form-item>

            <el-form-item label="药品类型" prop="categoryIdLevel2">
              <el-select
                  v-model="formData.categoryIdLevel2"
                  placeholder="请选择药品类型"
                  size="small"
                  @change="getLever(formData.categoryIdLevel2,3)"
                  clearable
              >
                <el-option
                    v-for="(item,index) in twoLever"
                    :key="item.id"
                    :label="item.categoryName"
                    :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <div class="inline">
              <el-form-item label="一级类目" prop="categoryIdLevel3" >
                <el-select
                    v-model="formData.categoryIdLevel3"
                    placeholder="请选择一级类目"
                    size="small"
                    @change="getLever(formData.categoryIdLevel3,4)"
                >
                  <el-option
                      v-for="(item,index) in threeLever"
                      :key="index"
                      :label="item.categoryName"
                      :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="二级类目" prop="categoryIdLevel4" >
                <el-select
                    v-model="formData.categoryIdLevel4"
                    placeholder="请选择二级类目"
                    size="small"
                    @change="getLever(formData.categoryIdLevel4,5)"
                >
                 <el-option
                     v-for="(item,index) in fourLever"
                     :key="index"
                     :label="item.categoryName"
                     :value="item.id"
                 ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="三级级类目" prop="categoryIdLevel5">
                <el-select
                    v-model="formData.categoryIdLevel5"
                    placeholder="请选择三级类目"
                    size="small"
                >
                  <el-option
                      v-for="(item,index) in fiveLever"
                      :key="index"
                      :label="item.categoryName"
                      :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </div>
            <el-form-item label="生产厂家" prop="manufacturer">
              <el-col :span="13">
                <el-input
                    size="small"
                    v-model="formData.manufacturer"
                    placeholder="请输入生产厂家"
                    style="width:70%;"
                ></el-input>

                <span class="word-num"></span>
              </el-col>
            </el-form-item>
            <div class="inline">
              <el-form-item label="适用科室" prop="department">
                <el-input
                    size="small"
                    v-model="formData.department"
                    placeholder="请输入适用科室"

                ></el-input>
                <!-- <el-select
                    v-model="formData.department"
                    placeholder="请选择适用科室"
                    size="small"
                    clearable
                >
                  <el-option
                      v-for="(item,index) in allDeparts"
                      :key="index"
                      :label="item.name"
                      :value="item.id"
                  ></el-option>
                </el-select> -->
              </el-form-item>
              <el-form-item label="治疗疾病" prop="treatDisease">
                <el-col :span="24">
                  <el-input
                      size="small"
                      v-model="formData.treatDisease"
                      placeholder="请输入治疗疾病"

                  ></el-input>

                  <span class="word-num"></span>
                </el-col>
              </el-form-item>
            </div>

            <el-form-item label="有效期" prop="expiredTime">
              <el-col :span="13">
               <el-input
                    size="small"
                    v-model="formData.expiredTime"
                    placeholder="请输入有效期"
                    style="width:70%;"
                ></el-input>
               <!-- <el-date-picker
                  v-model="formData.expiredTime"
                  size="small"
                  format="yyyy-MM-dd HH:mm:ss"
                  type="date"
                  placeholder="选择日期">
                </el-date-picker> -->

                <span class="word-num"></span>
              </el-col>
            </el-form-item>
            <el-form-item label="药品说明书">
              <el-upload

                  class="bg-uploader"
                  action="#"
                  :show-file-list="false"
                  :before-upload="beforeUploadPic1"
              >
                <div v-if="fileIntrList.length > 0">
                  <div class="file-pics" v-if="item.url" :key="index" v-for="(item,index) in fileIntrList">
                    <img :src="item.url" @mouseover.stop="intrIndex=index" class="bg-img"/>
                     <div
                         class="img-delete"
                         v-if="intrIndex==index"
                         @click.stop="deleteImg(item,fileIntrList)"
                         @mouseout.stop="intrIndex=-1"
                     >
                       <i class="el-icon-delete"></i>
                     </div>
                  </div>
                </div>

                <img  class="bg-img" src="../../assets/image/small.png" />
                <div class="limit-text">
                  <p>限制大小: 2M</p>
                  <!-- <p>最小尺寸：750*420</p> -->
                  <p>支持jpeg, png格式</p>
                </div>
              </el-upload>
              <p class="upload-message" v-if="!isSpecification_url">请上传药品说明书</p>
            </el-form-item>
          </div>

          <div class="basic-item-icon">
            <div class="part-tit">销售信息</div>
            <div class="inline">
              <el-form-item label="零售价" prop="optPrice">
                <el-col :span="20">
                  <el-input
                      size="small"
                      v-model="formData.optPrice"
                      placeholder="请输入零售价"

                  ></el-input>
                 <!-- <span class="word-num">{{(formData.name).replace(/\s+/g,"").length}}/60</span> -->
                </el-col>
              </el-form-item>
              <!-- <el-form-item label="折扣价" prop="name">
                <el-col :span="20">
                  <el-input
                      size="small"
                      v-model="formData.name"
                      placeholder="请输入折扣价"

                  ></el-input>

                </el-col>
              </el-form-item> -->
            </div>
            <div class="inline">
              <el-form-item label="库存" prop="name" class="required-label">
                <el-col :span="20">
                  <div class="stock-com">
                    <span class="sp sp-l" @click="changeStock(1)" :class="{'opac':formData.stock == 0}"><i class="el-icon-minus"></i></span>
                    <span class="sp sp-c">{{formData.stock}}</span>
                    <span class="sp sp-r" @click="changeStock(2)"><i class="el-icon-plus"></i></span>
                  </div>
                 <p class="error-message" v-if="!isgoodStock">库存不能为0</p>
                 <!-- <el-input
                      size="small"
                      v-model="formData.name"
                      placeholder="请输入库存"

                  ></el-input> -->
                  <!-- <el-input-number   readonly size="small" v-model="formData.stock"></el-input-number> -->
                 <!-- <span class="word-num">{{(formData.name).replace(/\s+/g,"").length}}/60</span> -->
                </el-col>
              </el-form-item>
            </div>
            <div class="inline">
              <el-form-item label="第三方商品编码" prop="externalGoodsCode">
                <el-col :span="20">
                  <el-input
                      size="small"
                      v-model="formData.externalGoodsCode"
                      placeholder="请输入第三方商品编码"
                  ></el-input>
                </el-col>
              </el-form-item>
            </div>
          </div>
        </el-form>

      <el-dialog
        :title="stock.title"
        :visible.sync="stockDio"
        width="30%"
        center>
        <div class="stock-dia">
          <div class="stock-item">更新库存后，将影响买家购买，请谨慎操作</div>
          <div class="stock-item">当前库存：{{formData.goodsStock}}</div>
          <div class="demo-input-suffix">
            {{stock.type == 1 ? '减少数量' : '增加数量'}}：
           <el-input v-model="stock.num" :placeholder="stock.placeholderTxt" style="width: 180px;"></el-input>
          </div>

        </div>
        <span slot="footer" class="dialog-footer" style="text-align: right;">
          <!-- <el-button @click="centerDialogVisible = false">取 消</el-button> -->
          <el-button type="primary" @click="updateStock">完成</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
  import BreadCrumb from "@/components/breadcrumb.vue";
  let vm = null;
  import { openLoading, closeLoading } from "../../utils/utils";
  import { doUpload, getFilePath } from "../../utils/qiniu-util";
  import { updateGoods ,updateStock,dosageAll,getDeparts,getGoodsList} from '@/utils/goods';
  import Cropper from '@/components/common/cropper.vue'
  import { mapGetters } from "vuex";
  export default {
    components: {
      BreadCrumb,
      Cropper
    },
    data(){
      let checkProjectStr = (rule, value, callback) => {
        if (value.indexOf("\\") != -1) {
          //存在
          callback(new Error("请勿输入字符“ \\ ”"));
        } else if (value.indexOf(".") != -1) {
          callback(new Error("请勿输入字符“ . ”"));
        } else {
          callback();
        }
      };

      const checkBarcode = (rule, value, cb) => {
        const valedBarcode = new RegExp("[\\u4E00-\\u9FFF]+","g"); 
        if(value && valedBarcode.test(value)) cb(new Error('条形码不能输入中文'));
        cb();
      }

      return{
        stock:{
          title:'减少库存',
          type:1,
          placeholderTxt:'请输入减少的库存数量',
          num:''
        },
        doseAll:[],
        fileGoodsList:[],
        fileIntrList:[],
        intrIndex:-1,
        isShowFileList:false,
        isgoodStock:true,
        headIndex:-1,
        oneLever:[],
        twoLever:[],
        allDeparts:[],
        threeLever:[{
            categoryName: "其他",
            id:-1
          }],
        fourLever:[{
            categoryName: "其他",
            id:-1
          }],
        fiveLever:[{
            categoryName: "其他",
            id:-1
          }],
        stockDio:false,
        curmbFirst: '云鹊店铺',
        curmbSecond: '商品管理',
        curmbThird: '编辑商品',// /live-manage?id=
        jumPathThird: '',
        isgoodsImages:true,
        isSpecification_url:true,
        title:'',
        typeList: [{
          label: '药品',
          value: '1',
        }, {
          label: '药品器械',
          value: '2',
        }, {
          label: '其他',
          value: '3',
        }],
        formData: {
          medicationId: 0,
          optPrice:0,
          id:'',
          categoryId:'',
          categoryIdLevel2: '',
          categoryIdLevel3: '',
          categoryIdLevel4: '',
          categoryIdLevel5: '',
          goodsName:'',
          goodsDescription:'',
          goodsImages:[],
          goodsType:'',
          medicCommonName:'',
          medicGoodsName:'',
          size:'',
          dosageId:null,
          usage:'',
          otc:false,
          otc1:'1',
          approvalNumber:'',
          manufacturer:'',
          department:'',
          expiredTime:'',
          specification_url:'',
          treatDisease:'',
          barCode:'',
          discountPrice:'',
          stock:0,
          goodsStock:0,
          specificationImages:[],
          goodsId:'',
          costPrice:'',
          decrStock:'',//减少库存
          incrStock:'',//增加库存
          storeId: '',
          externalGoodsCode: '', 
        },
        showCropper: false,
        currentOption: {
          offset_x: 120,
          offset_y: 185,
          width: 160,
          height: 120,
          cvWidth: 1000,
          cvHeight: 800,
          uploadType: 1,
          cropDialogWidth: '900px',
          cropBoxResizable: true,
          minCropBoxWidth: 100,
          minCropBoxHeight: 100,
          aspectRatio: 16/9
        },
        slide2: {
          oriUrl: '', // 原图
        },
        rules: {
          goodsName: [
            { required: true, message: "请输入商品名称", trigger: "blur" },
            {
              // min: 2,
              // max: 14,
              //message: "输入长度为2-14的内容，可包含中英文、数字及特殊符号",
              trigger: "blur"
            },
            { validator: checkProjectStr, trigger: "blur" }
          ],
          introduce: [
            { required: true, message: "请输入圈子介绍", trigger: "blur" },
            {
              min: 2,
              max: 40,
              message: "输入长度为2-40的内容，可包含中英文、数字及特殊符号",
              trigger: "blur"
            },
            { validator: checkProjectStr, trigger: "blur" }
          ],
          goodsImages: [
            { required: true, message: "请上传商品头图", trigger: "blur" }
          ],
          goodsType:[
            { required: true, message: "请选择商品类型", trigger: "change" }
          ],
          medicCommonName:[
            { required: true, message: "请输入商品通用名称", trigger: "blur" }
          ],
          size:[
            { required: true, message: "请输入商品规格", trigger: "blur" }
          ],
          manufacturer:[
            { required: true, message: "请输入生产厂家", trigger: "blur" }
          ],
          approvalNumber:[
            { required: true, message: "请输入批准文号", trigger: "blur" }
          ],
          dosageId:[
            { required: true, message: "请选择剂型", trigger: "change" }
          ],
          categoryIdLevel2:[
            { required: true, message: "请选择药品类型", trigger: "blur" }
          ],
          categoryIdLevel3:[
            { required: true, message: "请选择一级类目", trigger: "blur" }
          ],
          categoryIdLevel4:[
            { required: true, message: "请选择二级类目", trigger: "blur" }
          ],
          categoryIdLevel5:[
            { required: true, message: "请选择三级类目", trigger: "blur" }
          ],
          otc:[
            { required: true, message: "请选择是否是处方", trigger: "blur" }
          ],
          specification_url:[
            { required: true, message: "请上传药品说明书", trigger: "blur" }
          ],
          barCode: [
            { required: false, message: "请输入条形码", trigger: "blur" },
            { validator: checkBarcode, trigger: "blur" }
          ],
          optPrice: [
            { required: true, message: "请输入零售价", trigger: "blur" },
          ],
          dynamicFlag: [
            { required: true, message: "请选择内容发布权", trigger: "blur" },
          ]
        },
        imgMouseOver1: false,
        uploadImgMessage1: false,//未上传图片，校验提示语
        isMedic:false,
      }
    },
    computed: {
      ...mapGetters(["goodsInfo"])
    },
    created() {
      vm = this;

      const {id, storeId} = this.$route.query
      this.jumPathThird = '/goods-manage?storeId='+storeId
      //this.jumPathThird = '/create-good?id=add&storeId=46'
      this.title = id == 'add' ? '新增商品' : '编辑商品'
      this.curmbThird = this.title
      this.formData.storeId = Number(storeId) || '';
      this.getLever(0,1)
      dosageAll().then((res)=>{
        this.doseAll = res.data
        this.doseAll.push({dosageName: "其他",id: -1})
      })
      getDeparts().then((res)=>{
        this.allDeparts = res.data
      })
      if(id != 'add'){
        // let goods = Object.assign(this.goodsInfo,{})
        // this.formData = {...goods}
        // console.log(goods)
        this.getDetailByEdit(id)
      }

    },
    methods: {

      //eidt状态
      getDetailByEdit(id){
        let parm = {
          goodsIdList:[id],
          goodsName	:'',
          goodsType	:'',
          pageNo:1,
          pageSize:	10,
        }
        getGoodsList(parm).then((res)=>{
          if(res.code != '000000'){
            return this.$message({
              message: res.message,
              type: 'error'
            });
          }
          closeLoading(this);
          if(res.data == null){
            return this.$message({
              message: '数据加载失败',
              type: 'error'
            });
          }
          const {goodsList} = res.data
          this.formData = Object.assign(this.formData,{...goodsList[0]})
          this.formData.optPrice = this.formData.costPrice/100;
          this.fileGoodsList = this.getImges(goodsList[0].goodsImgList,1)
          this.fileIntrList = this.getImges(goodsList[0].medicImgList,2)
          this.isMedic = this.formData.goodsType == 5 ? true : false
          this.formData.stock = this.formData.goodsStock
          console.log(this.formData.otc)
          this.formData.otc1 = this.formData.otc ? '1' : '0'
          if(this.isMedic){
            this.getLever(5,2,1)
          }
          const {categoryIdLevel2,categoryIdLevel3,categoryIdLevel4,categoryIdLevel5} = this.formData
          if(categoryIdLevel2 != -1){
             this.getLever(categoryIdLevel2,3,1)
          }
          if(categoryIdLevel3 != -1){
             this.getLever(categoryIdLevel3,4,1)
          }
          if(categoryIdLevel4 != -1){
             this.getLever(categoryIdLevel4,5,1)
          }

          console.log(this.formData)
          //this.totalRows = res.data.totalCount
        })
      },

      getImges(d,type){
        let a = [];
        if(d.length > 0){
          for(let i=0;i<d.length;i++){
            a.push({
              url:type==1 ?d[i].goodsImgUrl :d[i].imageUrl,
              imageUrl:type==1 ?d[i].goodsImgUrl :d[i].imageUrl,
              id: d[i].id,
              imageSort: d[i].imageSort,
              imageType: type == 1 ? d[i].imgType : d[i].imageType,
            })
          }
        }
        return a;
      },

      //快速录入
      fastInput(){
        ///medications/query/{approvalnumber}
        if(this.formData.barCode == ''){
          this.$refs.formData.validateField("barCode")
          return;
        }
        // this.GET("store/medications/query/"+this.formData.approvalNumber).then(res => {
        this.GET(`store/medications/query/barcode/${this.formData.barCode}`).then(res => {
            console.log(res)
            if(res.code != '000000'){
              return this.$message({
                message: res.message,
                type: 'error'
              });
            }
            if(res.data == null){
              return this.$message({
                message: '未查询到数据，请手动输入',
                type: 'warning'
              });
            }
            const {imageList,medicationInfo} = res.data
            this.formData.medicationId = medicationInfo.id;
            this.formData.approvalNumber = medicationInfo.approvalNumber;
            const {medicCommonName,
              medicGoodsName,
              dosageId,
              size,
              otc,
              usage,
              categoryIdLevel2,
              categoryIdLevel3,
              categoryIdLevel4,
              categoryIdLevel5,
              manufacturer,
              department,
              treatDisease,
              expiredTime} = medicationInfo
            let fastParm = {
              medicCommonName,
              medicGoodsName,
              dosageId,
              size,
              otc,
              usage,
              categoryIdLevel2,
              categoryIdLevel3,
              categoryIdLevel4,
              categoryIdLevel5,
              manufacturer,
              department,
              treatDisease,
              expiredTime,
            }
            if(categoryIdLevel2){
              this.getLever(categoryIdLevel2,3,1)
            }
            if(categoryIdLevel3 != -1){
               this.getLever(categoryIdLevel3,4,1)
            }
            if(categoryIdLevel4 != -1){
               this.getLever(categoryIdLevel4,5,1)
            }
            this.formData = Object.assign(this.formData,fastParm)

            this.formData.otc1 = this.formData.otc ? '1' : '0'

            this.fileIntrList = this.getImges(imageList,2)

        });
      },
      getGoodsTypes(id,type){
        if(id == 5 ){
          this.isMedic = true;
          this.getLever(id,type)
        }else{
          this.isMedic = false;
        }
      },
      defaultArr(){
        let a = [
          {
            categoryName: "其他",
            id:-1
          }
        ]
        return a
      },

      //获取分类
      getLever(id,type,parm){

        this.GET("store/category/"+id).then(res => {


            if(type == 1){
              this.oneLever = res.data

            }else if(type == 2){
              //console.log(res)
              //this.twoLever = res.data || this.defaultArr()
              res.data = res.data.length > 0 ? res.data.concat([{categoryName: "其他",id:-1}]) : this.defaultArr()
              this.twoLever = res.data
              console.log(this.twoLever)
            }else if(type == 3){
             // res.data = res.data.push({categoryName: "其他",id:-1})
              res.data = res.data.length > 0 ? res.data.concat([{categoryName: "其他",id:-1}]) : this.defaultArr()
              this.threeLever = res.data
              if(!parm){
                this.formData.categoryIdLevel3 = ''
                this.formData.categoryIdLevel4 = ''
                this.formData.categoryIdLevel5 = ''
              }

            }else if(type == 4){
              res.data = res.data.length > 0 ? res.data.concat([{categoryName: "其他",id:-1}]) : this.defaultArr()
              this.fourLever = res.data
              if(!parm){
                this.formData.categoryIdLevel4 = ''
                this.formData.categoryIdLevel5 = ''
              }
            }else if(type == 5){
              res.data = res.data.length > 0 ? res.data.concat([{categoryName: "其他",id:-1}]) : this.defaultArr()
              this.fiveLever = res.data
              if(!parm){
                this.formData.categoryIdLevel5 = ''
              }

            }
        });
      },

      updateStock(){
        let r = /^\+?[1-9][0-9]*$/;
        //造假  接口来了删掉
        if(this.stock.num <= 0){
          return  this.$message({
            message: '增加库存数量不得为0',
            type: 'warning'
          });
        }
        if(!r.test(this.stock.num)){
          return  this.$message({
            message: '库存数量必须正整数',
            type: 'warning'
          });
        }

        if(this.stock.type == 1){
          if(this.stock.num > this.formData.goodsStock){
            return  this.$message({
              message: '减少库存数量不得大于当前库存',
              type: 'warning'
            });
          }
          this.formData.stock = this.formData.goodsStock - this.stock.num
          this.formData.decrStock = Number(this.stock.num)
          this.formData.incrStock = ''
        }else if(this.stock.type == 2){
          this.formData.stock = Number(this.stock.num) + Number(this.formData.goodsStock)
          this.formData.incrStock = Number(this.stock.num)
          this.formData.decrStock = ''
        }
        //this.formData.goodsStock = this.formData.stock
        this.stockDio = false
      },


      changeStock(type){
        if(this.formData.stock == 0 && type == 1){
          return;
        }
        let str = type == 1 ? '减少' : '增加',
            txt = `请输入${str}的库存数量`,
            tit = str + '库存'
        this.stock = {
          title:tit,
          type,
          num:'',
          placeholderTxt:txt
        }
        this.stockDio = true
      },

      complete() {
        let formName = "formData";
        // let goodsImgList = this.fileGoodsList.map((item, index) => {
        //   item.imageSort = index+1;
        // })
        // console.log(this.fileGoodsList)
        // let specificationImgList = this.fileIntrList.map((item, index) => {
        //   item.imageSort = index+1;
        // })
        for(let i=0;i<this.fileGoodsList.length;i++){
          this.fileGoodsList[i].imageSort = i+1
        }
        for(let j=0;j<this.fileIntrList.length;j++){
          this.fileIntrList[j].imageSort = j+1
        }

        this.formData.goodsImages = this.fileGoodsList;
        this.formData.specificationImages = this.fileIntrList;
        this.isgoodsImages = this.formData.goodsImages.length == 0 ? false :true;
       // this.isSpecification_url = this.formData.specificationImages.length == 0 ? false : true
        this.formData.categoryId = this.formData.goodsType
        this.formData.otc = this.formData.otc1 == 1 ? true : false
        this.isgoodStock = this.formData.stock > 0 ? true : false
        console.log(this.isgoodStock)
        if(this.isMedic){
          if(!this.isgoodsImages){
            return;
          }
          // if(!this.isSpecification_url){
          //   return;
          // }
        }
        if(!this.isgoodStock){
          return;
        }

        this.$refs[formName].validate((valid) => {
          if (valid) {
            //alert('submit!');
            this.updateGoodsInfo();
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },

      //更新商品
      updateGoodsInfo(){

        //this.formData.incrStock = 1000
        this.formData.costPrice = this.formData.optPrice*100
        this.formData.hasChanged = true;
        console.log('提交值',this.formData);
        updateGoods(this.formData).then((res)=>{
          if (res.code !== '000000') {
           // return this.$message.error(res.message);
              return this.$message({
                message: res.message,
                type: 'error'
              });
          }
          vm.$message.success("操作成功");
          this.$router.push({
            path: '/goods-manage',
            query: {
              storeId: this.formData.storeId,
            }
          })
        })
      },
      //上传商品头图
      beforeUploadPic(file) {
        if(this.fileGoodsList.length > 10){
          return ;
        }
        let vm = this;
        let picTypes = ['image/jpeg','image/png']

        const isLt200k = file.size / 1024  < 200;
        if (picTypes.indexOf(file.type) == -1) {
          return this.$message.error("请上传jpeg或png格式的图片");

        }
        // if (!isLt200k) {

        //   return vm.$message.error("图片大小请控制在200kb以内");
        // }
        let _img = new FileReader();
        _img.readAsDataURL(file);

        _img.onload = function (theFile) {
          let image = new Image()
          image.src = theFile.target.result
          vm.slide2.oriUrl = theFile.target.result;
          image.onload = function () {
            let _this = this;
            console.log(_this.width,_this.height)
            // if (_this.width != fileLimit.width || _this.height != fileLimit.height) {
            //if (_this.width == 750 &&  _this.height == 420) {
              openLoading(vm);
              doUpload(vm, file, getFilePath(file, null), "preview4", "progress1", 1).then(function (path) {
                closeLoading(vm);
                console.log('上传成功后路径', path);
                // if (fileLimit.show == "uploadImgMessage1") {
                //   vm.uploadImgMessage1 = false;
                // } else if (fileLimit.show == "uploadImgMessage2") {
                //   vm.uploadImgMessage2 = false;
                // }
                let len = vm.fileGoodsList.length;
                vm.fileGoodsList.push({url:path.fullPath,imageUrl:path.fullPath,imageName:'',imageSort: len+1,imageType: 2,id: null,})
                //vm.formData.goodsImages = path.fullPath
                vm.$message.success("上传成功");
              });

            // } else {
            //   return vm.$message.error("图片尺寸不符合规范，请根据规范上传图片");

            // }
          };
        };
        // openLoading(vm);
        // doUpload(vm, file, getFilePath(file, null), "preview4", "progress1", 1).then(function (path) {
        //   closeLoading(vm);
        //   console.log('上传成功后路径', path);
        //   vm.formData.goodsImages = path.fullPath

        //   vm.$message.success("上传成功");
        // });


      },
      //上传药品说明
      beforeUploadPic1(file,type) {
        this.currentOption.aspectRatio = 1/1;
        this.currentOption.cropBoxResizable = true;
        this.currentOption.minCropBoxWidth = 160;
        this.currentOption.minCropBoxHeight = 160;
        let fileLimit = {
          width: 160,
          height: 160,
          size: 0.5,
          sizeText: "500K",
          key: "headUrl",
          more: "imgUrl1More",
          show: "uploadImgMessage1"
        };
        this.beforeUpload(file, fileLimit);
      },
      //上传图片
      beforeUpload(file, fileLimit) {
        let vm = this;
        const isJPG = file.type === "image/jpeg";
        const isPNG = file.type === "image/png";
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJPG && !isPNG) {
          vm.$message.error("图片格式不符合规范，请根据规范上传图片");
          // return;
        }
        if (!isLt2M) {
          vm.$message.error("图片大小请控制在2M以内 ");
          return;
        }
        let _img = new FileReader();
        _img.readAsDataURL(file);
        _img.onload = function (theFile) {
          let image = new Image()
          image.src = theFile.target.result
          vm.slide2.oriUrl = theFile.target.result;
          image.onload = function () {
            let _this = this;
            // if (_this.width != fileLimit.width || _this.height != fileLimit.height) {
            // if (_this.width < fileLimit.width ||  _this.height < fileLimit.height) {
            //   vm.$message.error("图片尺寸不符合规范，请根据规范上传图片");
            //   return;
            // } else if(_this.width > fileLimit.width ||  _this.height > fileLimit.height){
            //   vm.showCropper = true;
            //   vm.currentOption.cvWidth = _this.width;
            //   vm.currentOption.cvHeight = _this.height;
            //   return;
            // } else {
              openLoading(vm);
              doUpload(vm, file, getFilePath(file, null), "preview4", "progress1", 1).then(function (path) {
                closeLoading(vm);
                let len = vm.fileIntrList.length;
                vm.fileIntrList.push({url:path.fullPath,imageUrl:path.fullPath,imageSort: len+1,imageType: 1,id: null})
                vm.$message.success("上传成功");
              });
            //}
          };
        };
        return isJPG && isLt2M;
      },
      //删除图片
      deleteImg(item,d) {
        let index = ''
        for(let i=0;i<d.length;i++){
          if(item.url == d[i].url){
            index = i;
            break
          }
        }
        d.splice(index,1)
        // if (type == 1) {
        //   vm.formData.headUrl = "";
        //   vm.imgMouseOver1 = false;
        // }
      },
      // 获取裁剪的图片数据
      getCropImg(argument) {
        this.showCropper = false;
        this.cropData = argument[1]
        vm.doUploadQiNiu(argument[2])
        argument[3] && argument[3].destroy();
        // vm.slide2.oriUrl = "";
      },
      // 上传七牛
      doUploadQiNiu(file){

        doUpload(this,file, getFilePath(file,null), 'preview4', 'uploadProgress1', '').then(function (path) {

          vm.formData.headUrl = path.fullPath;

          vm.$message.success('上传成功');
        });

      },
    },
  }
</script>
<style lang="scss">
  .create-shop-wrapper{
    .create-shop-content{
      background: #fff;
      padding: 10px;
      .step-content {
        overflow: hidden;
        height: 60px;
        padding: 10px 10px 50px ;
        border-bottom: 1px solid #efefef;
        .title{
          font-size: 13px;
          color: #449284;
        }
      }
    }
    .el-button--text{
      color: #449284;
      font-size: 14px;
      &::after{
        content: '';
        position: relative;
        height: 14px;
        /*border-right: 1px solid #EBEEF5;*/
        border-right: 1px solid #aaaaaa;
        padding-right: 10px;
      }
      &:last-of-type{
        &::after{
          content: '';
          position: relative;
          width: 1px;
          height: 14px;
          border-right: none;
        }
      }
    }
  }
  .required-label .el-form-item__label::before {
    content: "*";
    color: #f56c6c;
    margin-right: 4px;
  }
  .basic-item-icon {
    position: relative;

    .require {
      position: absolute;
      left: 67px;
      top: 11px;
      color: #f56c6c;
    }
    .error-message{
      font-size: 12px;
      color: #f56c6c;
    }
    .upload-message {
      position: absolute;
      left: 0;
      top: 105px;
      font-size: 12px;
      color: #f56c6c;
    }

    .img-delete {
      position: absolute;
      left: 0px;
      top: 0px;
      width: 84px;
      height: 100px;
      background: #000;
      opacity: 0.7;
      z-index: 999;

      i {
        color: #fff;
        margin-top: 39px;
        margin-left: 0px;
      }
    }
  }

  .word-num {
    font-size: 12px;
    color: #999;
    padding-top: 5px;
  }

  .line {
    margin-left: 10px;
    width: 20px;
  }

  .bg-uploader {
    .bg-img {
      float: left;
      width: 84px;
      height: 100px;
    }

    .limit-text {
      float: left;
      margin-left: 10px;
      margin-top: -10px;

      p {
        font-size: 12px;
        color: #999;
        text-align: left;
      }
    }
  }

  .el-upload__tip {
    position: absolute;
    top: -6px;
    left: 130px;
  }
  .span-mt-10{
    .edit-img {
      width: 20px;
      margin-top: 10px;
    }
  }
  .p-tips{
    font-size: 13px;
    color: #8C8C8C;
    line-height: 26px;
  }
  .part-tit{
    font-size: 14px;
    padding:20px 0 20px 20px;
  }
  .inline{
    .el-form-item{
      display: inline-block;
      vertical-align:top;
      .el-radio__label{
        font-size: 12px;
      }
    }
  }
  .stock-com{
    width: 158px;
    height: 32px;

    border-radius: 4px;
    overflow: hidden;
    .sp{
      display: inline-block;
      float: left;
      color: #fff;
    }
    .sp-c{
      line-height: 30px;
      height: 30px;
      width:92px;
      text-align: center;
      color: #666;
      border-top:1px solid #449284;
      border-bottom:1px solid #449284;
    }
    .sp-l{
      border-right:1px solid #449284;

    }
    .sp-r{
      border-left:1px solid #449284;
      border-radius: 0 4px 4px 0;
    }
    .sp-l,.sp-r{
      width: 32px;
      text-align: center;
      line-height: 32px;
      font-size: 13px;
      background: #449284 ;
      cursor: pointer;

    }
    .opac{
      opacity: 0.5;
    }
  }
  .stock-dia{
    .stock-item{
      padding-bottom: 20px;
    }
  }
  .fast-opt{
    font-size: 12px;
    padding:0 10px;
    cursor: pointer;
    color:#449284
  }
  .file-pics{
    display: inline-block;
    width: 84px;
    height: 100px;
    float:left;
    margin-right: 15px;
    position: relative;
  }
</style>
