<template>
  <div class="Box">
    <el-dialog
      v-if="modals"
      :visible.sync="modals"
      width="80%"
      title="价格编辑"
      custom-class="dialog-scustom"
    > 
      <el-form
        ref="formValidate"
        class="formValidate mt20"
        :model="formValidate"
        :rules="ruleInline"
        label-width="120px"
        label-position="right"
        @submit.native.prevent
      >
        <div>
          <div>
            <!-- <el-form-item label="商户商品分类：" >
              <el-cascader
                v-model="formValidate.mer_cate_id"
                class="selWidth"
                :options="merCateList"
                :props="{multiple:true,checkStrictly:true,emitPath:false }"
                clearable
              />
            </el-form-item> -->
            <el-form-item v-if="formValidate.spec_type === 1 && ManyAttrValue.length > 1" label="批量设置：" class="labeltop">
              <el-table :data="oneFormBatch" size="mini">
                <el-table-column label="图片" min-width="150" align="center">
                  <template slot-scope="scope">
                    <div
                      class="acea-row row-middle row-center-wrapper"
                    >
                      <div v-if="oneFormBatch[0].image" class="pictrue pictrueTab">
                        <img v-lazy="oneFormBatch[0].image">
                      </div>
                      <div v-else class="upLoad pictrueTab acea-row row-center-wrapper">
                        <i class="el-icon-camera cameraIconfont" />
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="售价" min-width="100" align="center">
                  <template slot-scope="scope">
                    <el-input @input="handleOnform('price')" v-model="oneFormBatch[0].price" class="priceBox" controls-position="right"/>
                  </template>
                </el-table-column>
                <el-table-column label="成本价" min-width="100" align="center">
                  <template slot-scope="scope">
                    <el-input @input="handleOnform('cost')" v-model="oneFormBatch[0].cost" class="priceBox" controls-position="right"/>
                  </template>
                </el-table-column>
                <el-table-column label="市场价" min-width="100" align="center">
                  <template slot-scope="scope">
                    <el-input @input="handleOnform('ot_price')" v-model="oneFormBatch[0].ot_price" class="priceBox" controls-position="right"/>
                  </template>
                </el-table-column>
                <el-table-column label="占比" min-width="100" align="center">
                  <template slot-scope="scope">
                    <!-- <el-select @change="BatchProportionChange" v-model="oneFormBatch[0].proportion" placeholder="请选择">
                        <el-option
                          v-for="item in proportionList"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                      </el-select> -->
                    <el-input @input="handleOnform('proportion')" v-model="oneFormBatch[0].proportion" :min="0" class="priceBox" controls-position="right"/>
                  </template>
                </el-table-column>
                <el-table-column label="折扣" min-width="100" align="center">
                  <template slot-scope="scope">
                    <el-input @input="batchInput" v-model="oneFormBatch[0].coupon" class="priceBox" controls-position="right"/>
                  </template>
                </el-table-column>
                <el-table-column label="库存" min-width="100" align="center">
                  <template slot-scope="scope">
                    <el-input-number v-model="oneFormBatch[0].stock" :min="0" class="priceBox" controls-position="right"/>
                  </template>
                </el-table-column>
                <!-- <el-table-column label="成长值" min-width="100" align="center">
                  <template slot-scope="scope">
                    <el-input-number v-model="oneFormBatch[0].growth" :min="0" class="priceBox" controls-position="right"/>
                  </template>
                </el-table-column> -->
                <el-table-column label="商品编号" min-width="100" align="center">
                  <template slot-scope="scope">
                    <el-input v-model="oneFormBatch[0].bar_code" />
                  </template>
                </el-table-column>
                <el-table-column label="重量(KG)" min-width="100" align="center">
                  <template slot-scope="scope">
                    <el-input-number v-model="oneFormBatch[0].weight" :min="0" class="priceBox" controls-position="right"/>
                  </template>
                </el-table-column>
                <el-table-column label="体积(m²)" min-width="100" align="center">
                  <template slot-scope="scope">
                    <el-input-number v-model="oneFormBatch[0].volume" :min="0" class="priceBox" controls-position="right"/>
                  </template>
                </el-table-column>
                <el-table-column label="操作" min-width="150">
                  <template slot-scope="scope">
                    <a href="javascript: void(0);" class="ela-btn" @click="batchAdd">添加</a>
                    <a href="javascript: void(0);" class="ela-btn" @click="batchDel">清空</a>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
            <el-form-item v-if="formValidate.spec_type === 0" class="labeltop" label="规格列表：">
              <el-table :data="OneattrValue" border class="tabNumWidth" size="mini">
                <el-table-column align="center" label="图片" min-width="80">
                  <template slot-scope="scope">
                    <div class="upLoadPicBox">
                      <div v-if="scope.row.image" class="pictrue tabPic"><img :src="scope.row.image"></div>
                      <div v-else class="upLoad tabPic">
                        <i class="el-icon-camera cameraIconfont" />
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column v-for="(item,iii) in attrValue" :key="iii" :label="formThead[iii].title" align="center" min-width="120">
                  <template slot-scope="scope">
                    <!-- <el-select @change="proportionChange(scope.row,iii,$event)" v-if="formThead[iii].title === '占比'" v-model="scope.row[iii]" placeholder="请选择">
                        <el-option
                          v-for="item in proportionList"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                      </el-select> -->
                    <el-input @input="handleCost(scope.row,iii)" v-model="scope.row[iii]" type="text" class="priceBox" />
                    <!-- <el-input v-else  @input="handleCost(scope.row,iii)" :disabled="formThead[iii].title === '占比'" v-model="scope.row[iii]" class="priceBox" controls-position="right"/> -->
                  </template>
                </el-table-column>
                <template v-if="formValidate.extension_type === 1">
                  <el-table-column align="center" label="一级返佣(元)" min-width="100">
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.extension_one" :min="0" class="priceBox" controls-position="right"/>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="二级返佣(元)" min-width="100">
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.extension_two" :min="0" class="priceBox" controls-position="right"/>
                    </template>
                  </el-table-column>
                </template>
              </el-table>
            </el-form-item>
            <el-form-item v-if="formValidate.spec_type === 1" class="labeltop" label="规格列表：">
              <el-table :data="ManyAttrValue" border class="tabNumWidth" size="mini">
                <template v-if="manyTabDate">
                  <el-table-column v-for="(item,iii) in manyTabDate" :key="iii" align="center" :label="manyTabTit[iii].title" min-width="80">
                    <template slot-scope="scope">
                      <el-input @input="handleMany(scope.row,iii,manyTabTit[iii].title)" v-model="scope.row[iii]" type="text" />
                    </template>
                  </el-table-column>
                </template>
                <el-table-column align="center" label="图片" min-width="80">
                  <template slot-scope="scope">
                    <div class="upLoadPicBox" title="750*750px">
                      <div v-if="scope.row.image" class="pictrue tabPic"><img :src="scope.row.image"></div>
                      <div v-else class="upLoad tabPic">
                        <i class="el-icon-camera cameraIconfont" />
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column v-for="(item,iii) in attrValue" :key="iii" :label="formThead[iii].title" align="center" min-width="120">
                  <template slot-scope="scope">
                    <el-input @input="handleCost(scope.row,iii)" v-model="scope.row[iii]" type="text" class="priceBox" />
                    <!-- <el-select @change="proportionChange(scope.row,iii,$event)" v-if="formThead[iii].title === '占比'" v-model="scope.row[iii]" placeholder="请选择">
                        <el-option
                          v-for="item in proportionList"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                      </el-select> -->
                    <!-- <el-input v-if="formThead[iii].title==='商品编号'" v-model="scope.row[iii]" type="text" class="priceBox" /> -->
                    <!-- <el-input v-else  @input="handleCost(scope.row,iii)" :disabled="formThead[iii].title === '占比'" v-model="scope.row[iii]" class="priceBox" controls-position="right"/> -->
                  </template>
                </el-table-column>
                <template v-if="formValidate.extension_type === 1">
                  <el-table-column align="center" label="一级返佣(元)" min-width="100">
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.extension_one" :min="0" class="priceBox" controls-position="right"/>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="二级返佣(元)" min-width="100">
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.extension_two" :min="0" class="priceBox" controls-position="right"/>
                    </template>
                  </el-table-column>
                </template>
              </el-table>
            </el-form-item> 
            <!-- <el-table
              :data="attrList"
              style="width: 100%">
              <el-table-column
                prop="title"
                label="规格名称"
                width="180">
              </el-table-column>
              <el-table-column
                prop="detail"
                label="规格值"
                width="180">
                <template slot-scope="scope">
                  <el-input @input="handleModet(item)" v-for="item in scope.row.detail" v-model="item.value"></el-input>
                </template>
              </el-table-column>
            </el-table> -->
            <el-form-item>
              <el-button :loading="loading1" type="primary" class="submission" @click="handleSubmit('formValidate')">提交</el-button>
            </el-form-item>
          </div>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>

import {
  // categorySelectApi,
  productDetailApi,
  freeTrialApi
} from '@/api/product'
import { roterPre } from "@/settings";
import { toFixedNoRounding } from '@/utils/util'
const defaultObj = {
  store_name: '',
  cate_id: '',
  temp_id: '',
  type: 0,
  guarantee_template_id: '',
  keyword: '',
  unit_name: '',
  store_info: '',
  image: '',
  slider_image: [],
  content: '',
  ficti: 0,
  once_count: 0,
  give_integral: 0,
  is_show: 0,
  price: 0,
  cost: 0,
  ot_price: 0,
  stock: 0,
  attrs: [],
  items: [],
  delivery_way: [],
  mer_labels: [],
  delivery_free: 0,
  spec_type: 0,
  is_copoy: 1,
  attrValue: [{
    image: '',
    price: 0,
    cost: 0,
    ot_price: 0,
    proportion:0.6,
    coupon:0,
    stock: 0,
    // growth:0,
    bar_code: '',
    weight: 0,
    volume: 0
  }]
}
const objTitle = {
  price: {
    title: '售价'
  },
  cost: {
    title: '成本价'
  },
  ot_price: {
    title: '市场价'
  },
  proportion: {
    title: '占比'
  },
  coupon:{
    title:'折扣'
  },
  stock: {
    title: '库存'
  },
  growth: {
    title: '成长值'
  },
  bar_code: {
    title: '商品编号'
  },
  weight: {
    title: '重量（KG）'
  },
  volume: {
    title: '体积(m³)'
  }
}
export default {
  name: 'editAttr',
  components: {},
  data() {
    return {
      proportionList:[
      {
          value: '0.80',
          label: '0.80',
          coupon:0.1,
          growth:0.3
        }, 
        {
          value: '0.75',
          label: '0.75',
          coupon:0.15,
          growth:0.35
        }, 
        {
          value: '0.70',
          label: '0.70',
          coupon:0.2,
          growth:0.4
        }, 
        {
          value: '0.65',
          label: '0.65',
          coupon:0.25,
          growth:0.45
        },
        {
          value: '0.60',
          label: '0.60',
          coupon:0.3,
          growth:0.5
        }, 
        {
          value: '0.55',
          label: '0.55',
          coupon:0.35,
          growth:0.55
        }, 
        {
          value: '0.50',
          label: '0.50',
          coupon:0.4,
          growth:0.6
        },
        {
          value: '0.45',
          label: '0.45',
          coupon:0.45,
          growth:0.65
        }, 
        {
          value: '0.40',
          label: '0.40',
          coupon:0.5,
          growth:0.7
        },
        {
          value: '0.35',
          label: '0.35',
          coupon:0.55,
          growth:0.75
        },
        {
          value: '0.30',
          label: '0.30',
          coupon:0.6,
          growth:0.8
        },
        {
          value: '0.25',
          label: '0.25',
          coupon:0.65,
          growth:0.85
        },
        {
          value: '0.20',
          label: '0.20',
          coupon:0.7,
          growth:0.9
        },
        // {
        //   value: '0.15',
        //   label: '0.15',
        //   coupon:0.75,
        //   growth:0.95
        // },
        // {
        //   value: '0.1',
        //   label: '0.10',
        //   coupon:0.8,
        //   growth:1
        // },
      ],
      product_id: '',
      roterPre: roterPre,
      modals: false,
      loading: false,
      loading1: false,
      OneattrValue: [Object.assign({}, defaultObj.attrValue[0])], // 单规格
      ManyAttrValue: [Object.assign({}, defaultObj.attrValue[0])], // 多规格
      manyTabDate: {},
      count: 0,
      modal_loading: false,
      images: '',
      modalPic: false,
      isChoice: '',
      columns: [],
      merCateList: [], // 商户
      ruleInline: {
        mer_cate_id: [
          {
            required: true,
            message: '请选择商户分类',
            trigger: 'change',
            type: 'array',
            min: '1'
          }
        ]
      },
      formThead: Object.assign({}, objTitle),
      formValidate: Object.assign({}, defaultObj),
      items: [
        {
          image: '',
          price: 0,
          cost: 0,
          proportion:0.6,
          coupon:0,
          growth:0,
          ot_price: 0,
          stock: 0,
          bar_code: '',
          weight: 0,
          volume: 0
        }
      ],
      tableIndex: 0,
      attrInfo: {},
      detailStatus:true,
      attrList:[],
      attrInfos:{},
      oneFormBatch:  [
        {
          image: '',
          price: 0,
          proportion:0.6,
          coupon:0,
          growth:0,
          cost: 0,
          ot_price: 0,
          stock: 0,
          bar_code: '',
          weight: 0,
          volume: 0
        }
      ]
    }
  },
  computed: {
    attrValue() {
      const obj = Object.assign({}, defaultObj.attrValue[0])
      delete obj.image
      return obj
    },
  },
  watch: {
    'formValidate.attr': {
      handler: function(val) {
        if (this.formValidate.spec_type === 1 && this.detailStatus) this.watCh(val)
      },
      immediate: false,
      deep: true
    }
  },
  created() {
    // this.getCategorySelect()
  },
  mounted() {

  },
  methods: {
    handleModet(row){
      // 生成
      let arr = this.attrFormat(this.attrList.map(res=>{
          return{
            value:res.title,
            detail:res.detail.map(res=>res.value)
          }
      }))
      // this.attrInfos = {}
      // //存储
      // this.ManyAttrValue.forEach((val) => {
      //   if (val.detail !== 'undefined' && val.detail !== null) {
      //     this.attrInfos[val.unique] = val
      //   }
      // })
      // //赋值
      // arr.forEach((val, index) => {
      //   const key = val.unique
      //   if (this.attrInfos[key]) arr[index] = this.attrInfos[key]
      //   val.image = this.formValidate.image
      // })
      // console.log(arr)
    },
    handleMany(row,i,val){
      if(row[i]){
        this.detailStatus = false
        this.ManyAttrValue.map((res,key)=>{
          if(row.detail[val] == res.detail[val] && res.unique!==row.unique){
            //值
            res[i] = row[i]
            // detail的值
            res.detail[val] = row[i]
            //sku
            let skuValue = ''
            Object.keys(this.manyTabTit).map((res,i)=>{
              skuValue = skuValue?`${skuValue},${row[res]}`:`${skuValue}${row[res]}`
            })
            res['sku'] = skuValue
          }
        })
          row.detail[val] = row[i]
          row.detail[val] = row[i]
          let skuValue = ''
          Object.keys(this.manyTabTit).map((res,i)=>{
              skuValue = skuValue?`${skuValue},${row[res]}`:`${skuValue}${row[res]}`
          })
          row['sku'] = skuValue
        //处理attr
          let arrMode = []
          this.ManyAttrValue.forEach((res)=>{
              if(!arrMode.includes(res.detail[val])){
                arrMode.push(res.detail[val])
              }
          })
          this.formValidate.attr.find(res=>res.value == this.manyTabTit[i].title).detail = arrMode
      }

    },
        // 占比值变化处理
    proportionChange(val,i,e){
      val.cost = toFixedNoRounding(val.price * e)
      let obj = this.proportionList.find(item=>item.value==e)
      val.coupon = Math.floor(val.price*obj.coupon)
      val.growth = Math.floor(val.price*obj.growth)
    },
    BatchProportionChange(){
      this.oneFormBatch[0].cost = toFixedNoRounding(this.oneFormBatch[0].price * this.oneFormBatch[0].proportion)
      let obj = this.proportionList.find(item=>item.value==this.oneFormBatch[0].proportion)
      this.oneFormBatch[0].coupon = Math.floor(this.oneFormBatch[0].price*obj.coupon)
      this.oneFormBatch[0].growth = Math.floor(this.oneFormBatch[0].price*obj.growth)
    },
    handleOnform(type){
      switch (type) {
        case 'ot_price':
          this.oneFormBatch[0].ot_price = this.oneFormBatch[0].ot_price.replace(/^([0-9-]\d*\.?\d{0,2})?.*$/,'$1')
          break;
        case 'cost':
          this.oneFormBatch[0].proportion = toFixedNoRounding(this.oneFormBatch[0].cost/this.oneFormBatch[0].price)
          this.oneFormBatch[0].cost = this.oneFormBatch[0].cost.replace(/^([0-9-]\d*\.?\d{0,2})?.*$/,'$1')
          break;
        case 'price':
          this.oneFormBatch[0].price = this.oneFormBatch[0].price.replace(/^([0-9-]\d*\.?\d{0,2})?.*$/,'$1')
          this.oneFormBatch[0].cost = toFixedNoRounding(this.oneFormBatch[0].price * this.oneFormBatch[0].proportion)
          break;
        case 'proportion':
          this.oneFormBatch[0].proportion = this.oneFormBatch[0].proportion.replace(/^([0-9-]\d*\.?\d{0,2})?.*$/,'$1')
          this.oneFormBatch[0].cost = toFixedNoRounding(this.oneFormBatch[0].price * this.oneFormBatch[0].proportion)
          break;
      }
        // this.oneFormBatch[0].growth = parseInt( this.oneFormBatch[0].price*(0.9-( this.oneFormBatch[0].cost/ this.oneFormBatch[0].price)))
        // this.oneFormBatch[0].proportion = (this.oneFormBatch[0].cost/this.oneFormBatch[0].price).toFixed(2)
        // let obj = this.proportionList.find(item=>item.value==this.oneFormBatch[0].proportion)
        // this.oneFormBatch[0].coupon = Math.floor(this.oneFormBatch[0].price*obj.coupon)
        // this.oneFormBatch[0].growth = Math.floor(this.oneFormBatch[0].price*obj.growth)
        // this.oneFormBatch[0].growth = parseInt( this.oneFormBatch[0].price*(0.9-( this.oneFormBatch[0].cost/ this.oneFormBatch[0].price)))
        // this.oneFormBatch[0].proportion = (this.oneFormBatch[0].cost/this.oneFormBatch[0].price).toFixed(2)
     
      
    },
    calculatePercentage(number) {
    // 假设输入的是0.6，50%
    // 首先计算百分比
    var percentage = 100 - (number - 0.1) * 100;
    // 确保百分比在0到100之间
    percentage = Math.min(Math.max(percentage, 0), 100);
    // 返回百分比
    return percentage + "%";
    },
    handleCost(val,i){
      switch(i){
        case 'cost':
          val.cost=val.cost.replace(/^([0-9-]\d*\.?\d{0,2})?.*$/,'$1')
          val.proportion = toFixedNoRounding(val.cost/val.price)
          // val.proportion = (val.cost/val.price).toFixed(2)
          // val.growth = parseInt(val.price*(0.9-(val.cost/val.price)))
          break;
        case 'ot_price':
          val.ot_price=val.ot_price.replace(/^([0-9-]\d*\.?\d{0,2})?.*$/,'$1')
          if(!val.price){
            this.$message.error('成本价低于0')
          }
          break;
        case 'price':
          val.price=val.price.replace(/^([0-9-]\d*\.?\d{0,2})?.*$/,'$1')
          // let obj = this.proportionList.find(item=>item.value==val.proportion)
          val.cost = toFixedNoRounding(val.price * val.proportion)
          // val.coupon = Math.floor(val.price*obj.coupon)
          // val.growth = Math.floor(val.price*obj.growth)
          break;
        case 'growth':
          val.growth=val.growth.replace(/[^\d]/g,'')
          break;
        case 'proportion':
          val.proportion=val.proportion.replace(/^([0-9-]\d*\.?\d{0,2})?.*$/,'$1')
          val.cost = toFixedNoRounding(val.price * val.proportion)
          break;
        case 'bar_code':
          val.bar_code = val.bar_code.replace(/[\W]/g,'')
          break;
        case 'coupon':
          val.coupon = val.coupon.replace(/[\W]/g,'')
          break;
      }
    },
    batchInput(e){
      this.oneFormBatch[0].coupon = e.replace(/[\W]/g,'')
    },
    batchDel() {
      this.oneFormBatch = [
        {
          image: '',
          price: 0,
          proportion:0.6,
          coupon:0,
          growth:0,
          cost: 0,
          ot_price: 0,
          stock: 0,
          bar_code: '',
          weight: 0,
          volume: 0
        }
      ]
    },
    batchAdd() {
      for (const val of this.ManyAttrValue) {
        this.$set(val, 'image', this.oneFormBatch[0].image)
        this.$set(val, 'price', this.oneFormBatch[0].price)
        this.$set(val, 'cost', this.oneFormBatch[0].cost)
        this.$set(val, 'ot_price', this.oneFormBatch[0].ot_price)
        this.$set(val, 'stock', this.oneFormBatch[0].stock)
        this.$set(val, 'bar_code', this.oneFormBatch[0].bar_code)
        this.$set(val, 'weight', this.oneFormBatch[0].weight)
        this.$set(val, 'volume', this.oneFormBatch[0].volume)
        this.$set(val, 'growth', this.oneFormBatch[0].growth)
        this.$set(val, 'proportion', this.oneFormBatch[0].proportion)
        this.$set(val, 'coupon', this.oneFormBatch[0].coupon)
        this.$set(val, 'extension_one', this.oneFormBatch[0].extension_one)
        this.$set(val, 'extension_two', this.oneFormBatch[0].extension_two)
      }
    },
    // 商户分类；
    // getCategorySelect() {
    //   categorySelectApi()
    //     .then((res) => {
    //       this.merCateList = res.data
    //     })
    //     .catch((res) => {
    //       this.$message.error(res.message)
    //     })
    // },
    watCh(val) {
      const tmp = {}
      const tmpTab = {}
      const temAttr = []
      this.formValidate.attr.forEach((o, i) => {
        tmp['value' + i] = { title: o.value }
        tmpTab['value' + i] = ''
        temAttr.push({title:o.value,detail:o.detail.map((v, g) => {
          return { value: v }
        })}) 
      })
      this.attrList = temAttr
      this.ManyAttrValue = this.attrFormat(val)
      this.ManyAttrValue.forEach((val, index) => {
        const key = Object.values(val.detail).sort().join('/')
        if (this.attrInfo[key]) this.ManyAttrValue[index] = this.attrInfo[key]
        val.image = this.formValidate.image
      })
      this.attrInfo = {}
      this.ManyAttrValue.forEach((val) => {
        if (val.detail !== 'undefined' && val.detail !== null) {
          this.attrInfo[Object.values(val.detail).sort().join('/')] = val
        }
      })
      this.manyTabTit = tmp
      this.manyTabDate = tmpTab
      console.log(this.manyTabTit);
      this.formThead = Object.assign({}, this.formThead, tmp)
    },
    attrFormat(arr) {
      let data = []
      const res = []
      return format(arr)
      function format(arr) {
        if (arr.length > 1) {
          arr.forEach((v, i) => {
            if (i === 0) data = arr[i]['detail']
            const tmp = []
            data.forEach(function(vv) {
              arr[i + 1] && arr[i + 1]['detail'] && arr[i + 1]['detail'].forEach(g => {
                const rep2 = (i !== 0 ? '' : arr[i]['value'] + '_$_') + vv + '-$-' + arr[i + 1]['value'] + '_$_' + g
                tmp.push(rep2)
                if (i === (arr.length - 2)) {
                  const rep4 = {
                    image: '',
                    price: 0,
                    cost: 0,
                    ot_price: 0,
                    proportion:0.6,
                    coupon:'',
                    stock: 0,
                    growth:0,
                    bar_code: '',
                    weight: 0,
                    volume: 0,
                    brokerage: 0,
                    brokerage_two: 0
                  }
                  rep2.split('-$-').forEach((h, k) => {
                    const rep3 = h.split('_$_')
                    if (!rep4['detail']) rep4['detail'] = {}
                    rep4['detail'][rep3[0]] = rep3.length > 1 ? rep3[1] : ''
                  })
                  Object.values(rep4.detail).forEach((v, i) => {
                    rep4['value' + i] = v
                  })
                  res.push(rep4)
                }
              })
            })
            data = tmp.length ? tmp : []
          })
        } else {
          const dataArr = []
          arr.forEach((v, k) => {
            v['detail'].forEach((vv, kk) => {
              dataArr[kk] = v['value'] + '_' + vv
              res[kk] = {
                image: '',
                price: 0,
                cost: 0,
                ot_price: 0,
                proportion:0.6,
                coupon:'',
                stock: 0,
                growth:0,
                bar_code: '',
                weight: 0,
                volume: 0,
                brokerage: 0,
                brokerage_two: 0,
                detail: { [v['value']]: vv }
              }
              Object.values(res[kk].detail).forEach((v, i) => {
                res[kk]['value' + i] = v
              })
            })
          })
          data.push(dataArr.join('$&'))
        }
        return res
      }
    },
    // 获取规格数据
    getAttrDetail(id) {
      this.product_id = id
      this.loading = true
      this.modals = true
      productDetailApi(id)
        .then((res) => {
          const info = res.data
          this.formValidate = {
            attr: info.attr || [],
            attrValue: info.attrValue,
            mer_cate_id: info.mer_cate_id,
            spec_type: info.spec_type,
            slider_image: info.slider_image,
            content: info.content,
            store_info: info.store_info
           }
           let oneFormBatch= [
            {
              image: '',
              price: 0,
              proportion:0.6,
              coupon:'',
              growth:0,
              cost: 0,
              ot_price: 0,
              stock: 0,
              bar_code: '',
              weight: 0,
              volume: 0
            }
          ]
          this.oneFormBatch = oneFormBatch
          if (this.formValidate.spec_type === 0) {
            this.OneattrValue = info.attrValue
          } else {
            this.ManyAttrValue = info.attrValue
            this.ManyAttrValue.forEach(val => {
              if (val.detail !== 'undefined' && val.detail !== null) {
                console.log(val)
                this.attrInfo[
                  Object.values(val.detail)
                    .sort()
                    .join('/')
                  ] = val
              }
            })
            this.$watch('formValidate.attr', this.watCh)
          }
          this.loading = false
        })
        .catch((res) => {
          this.$message.error(res.message)
          this.loading = false
        })
    },
    // 提交
    handleSubmit(name) {
      let that = this;
      that.$refs[name].validate((valid) => {
        if (valid) {
          if (this.formValidate.spec_type === 1) {
            let mode = this.ManyAttrValue.every(item=>{
              return !(+item.ot_price<item.price)
            })
            if(!mode) return this.$message.error("市场价格限定等于或大于售价"); 
            // let url = this.ManyAttrValue.every(item=>{
            //   return item.gist_url
            // })
            // if(!url) return this.$message.error("规格设置-多规格依据链接必选填写"); 
            this.formValidate.attrValue = this.ManyAttrValue;
          } else {
            let attr = this.OneattrValue[0]
            if(+attr.ot_price<attr.price) return this.$message.error("市场价格限定等于或大于售价"); 
            // if(!attr.gist_url) return this.$message.error("规格设置-依据链接必须填写");
            this.formValidate.attrValue = this.OneattrValue;
            this.formValidate.attr = [];
        }
          that.loading1 = true
          freeTrialApi(that.product_id,that.formValidate)
            .then((res) => {
              that.loading1 = false
              that.$message.success(res.message)
              setTimeout(() => {
                that.modals = false
              }, 500)
            })
            .catch((res) => {
              that.$message.error(res.message)
              that.loading1 = false
            })
        } else {
          if (!that.formValidate.mer_cate_id) {
            that.$message.warning('请选择商户商品分类！')
          }
        }
      })
    },
  }
}
</script>

<style scoped lang="scss">
::v-deep .el-cascader {
  display: block;
}
.ela-btn {
  color: var(--prev-color-primary);
}
.priceBox {
  width: 80px;
}
.btndel {
  position: absolute;
  z-index: 1;
  width: 20px !important;
  height: 20px !important;
  left: 46px;
  top: -4px;
}
.pictrue {
  width: 60px;
  height: 60px;
  border: 1px dotted rgba(0, 0, 0, 0.1);
  margin-right: 10px;
  position: relative;
  cursor: pointer;
  img {
    width: 100%;
    height: 100%;
  }
}
::v-deep .el-input-number__decrease,::v-deep .el-input-number__increase{
  display: none;
}
::v-deep .el-input-number.is-controls-right .el-input__inner{
  padding: 0 5px;
}
::v-deep .el-input__inner{
  padding: 0 5px;
}
.pictrueTab {
  width: 40px !important;
  height: 40px !important;
}
.upLoad {
  width: 40px;
  height: 40px;
  border: 1px dotted rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  background: rgba(0, 0, 0, 0.02);
  cursor: pointer;
}
</style>
