<template>
  <div class="goods-after-sale">
    <el-form ref="goodsAfterSaleForm" :model="goodsAfterSaleForm" :rules="goodsAfterSaleRules" label-width="150px" size="small">
    <el-card class="box-card" ref="paramsvalue">
      <div slot="header" class="clearfix">
        <span>商品属性</span>  <span style="font-size:13px;padding-left:20px;font-weight: 400;">属性名称/属性值</span>
      </div>
     
      <el-form-item label="所属品牌：" prop="brand_id">
        <el-select v-model.trim="goodsAfterSaleForm.brand_id" :loading="loading" :filter-method="searchbtn" filterable  placeholder="请选择商品品牌" style="width: 420px;">
          <el-option v-for="(item,index) in brandOptions" :key="index" :label="item.brand_cn" :value="item.id"></el-option>
        </el-select>
        <el-link class="edit-type-span el-icon-plus" type="primary" :underline="false" @click="toPage('brand')">新增品牌</el-link>
      </el-form-item>
      <el-form-item label="商品产地：" prop="producing_area_id_list">
        <el-cascader ref="producing_area" filterable v-model.trim="goodsAfterSaleForm.producing_area_id_list" :options="areaOptions"  :props="areaProps" placeholder="请选择"
                     style="width:420px;" size="mini" @change="matchIdName('producing_area')">
        </el-cascader>
      </el-form-item>

      <el-form-item label="商品发货地：" prop="deliver_area_id_list">
        <el-cascader ref="deliver_area" filterable v-model.trim="goodsAfterSaleForm.deliver_area_id_list" filterable :options="areaOptions"  :props="areaProps" placeholder="请选择"
                     style="width:420px;" size="mini" @change="matchIdName('deliver_area')">
        </el-cascader>
      </el-form-item>
      
      <draggable  :list="goodsAfterSaleForm.params" group="article" class="dragArea">
        <div v-for="(element,index) in goodsAfterSaleForm.params" :key="index" class="list-complete-item">
          <el-row :gutter="24" style="padding-left:50px;">
            <el-col :span="8" style="height:50px;">
              <el-input
                  type="text"
                  placeholder="属性名称"
                  v-model="element.title"
                  maxlength="15"
                  @input="updatelist"
                  show-word-limit
                  size="small"
                ></el-input>
            </el-col>
            <el-col :span="12" style="height:50px;">
              <el-input
              type="text"
              placeholder="属性值"
              @input="updatelist"
              v-model="element.value"
              maxlength="60"
              show-word-limit
              size="small"
            ></el-input>
            </el-col>
            <el-col :span="4" style="height:50px;">
              <span v-show="index!=0"  style="height:50px;line-height: 40px;" @click="deleteparameter(index)">
                <i style="color:#ff4949" class="el-icon-delete curspor" />
              </span>
              <span  style="height:50px;line-height: 40px;">
              <i style="color:#ff4949" class="el-icon-rank curspor" />
            </span>
            </el-col>
          </el-row>
        </div>
      </draggable>

      <el-button style="margin-left:50px;margin-bottom:30px;" type="primary" size="small" @click="addparameter">添加属性</el-button>
    </el-card>
   
    <el-card class="box-card"  ref="salesvalue">
    <div slot="header" class="clearfix">
      <span>售后及服务</span>
    </div>
      <el-form-item label="服务标签：" prop="stags">
        <el-checkbox-group v-model="goodsAfterSaleForm.stags">
          <el-checkbox v-for="(item,index) in tagOptions" :label="item.id" true-label :key="index" @change="serviceTagsChange(item.id)">{{item.tag}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="邮费模板：" prop="freight_id">
        <el-select v-model="goodsAfterSaleForm.freight_id" filterable placeholder="请选择邮费模板" @change="diupfont" style="width:400px;">
          <el-option v-for="(item,index) in freightOptions" :key="index" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="发货时效：" prop="delay_compensate">
        <el-select v-model="goodsAfterSaleForm.delay_compensate" style="width:400px;" @change="diupfont1" placeholder="请选择发货时效">
          <el-option label="24小时" :value="24"></el-option>
          <el-option label="48小时" :value="48"></el-option>
          <!-- <el-option label="72小时" :value="72"></el-option> -->
        </el-select>
      </el-form-item>

      <el-form-item label="售后时长：" prop="aftersale_time">
        <el-select v-model="goodsAfterSaleForm.aftersale_time" style="width:400px;"  @change="diupfont2" placeholder="请选择售后时长">
          <el-option label="7天" :value="7"></el-option>
          <el-option label="15天" :value="15"></el-option>
          <!-- <el-option label="30天" :value="30"></el-option> -->
        </el-select>
      </el-form-item>


  </el-card>

<!--  <el-card class="box-card" ref="outhervalue">-->
<!--    <div slot="header" class="clearfix" >-->
<!--      <span>其他设置</span>-->
<!--    </div>-->

<!--&lt;!&ndash;        <el-form-item label='商品关键词：' prop="goods_des">&ndash;&gt;-->
<!--&lt;!&ndash;          <el-input v-model.trim="goodsAfterSaleForm.goods_des" placeholder="请输入商品关键词" style="width:420px;"></el-input>&ndash;&gt;-->
<!--&lt;!&ndash;          <span class="tip-span ml20">关键词之间用 <strong>英文逗号</strong> 分开，最多可以添加5个</span>&ndash;&gt;-->
<!--&lt;!&ndash;        </el-form-item>&ndash;&gt;-->

<!--        <el-form-item label="商品产地：" prop="producing_area">-->
<!--          <el-select v-model.trim="goodsAfterSaleForm.producing_area" placeholder="请选择商品产地" style="width: 420px;">-->
<!--            <el-option-->
<!--              v-for="item in areaOptions"-->
<!--              :key="item.id"-->
<!--              :label="item.name"-->
<!--              :value="item.id"-->
<!--            ></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->

<!--        <el-form-item label="商品发货地：" prop="deliver_area">-->
<!--          <el-select v-model.trim="goodsAfterSaleForm.deliver_area" placeholder="请选择商品发货地" style="width: 420px;">-->
<!--            <el-option-->
<!--              v-for="item in areaOptions"-->
<!--              :key="item.id"-->
<!--              :label="item.name"-->
<!--              :value="item.id"-->
<!--            ></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->

<!--        <el-form-item label='商品单位：' prop="unit">-->
<!--          <el-input v-model.trim="goodsAfterSaleForm.unit" placeholder="请输入商品单位" style="width:420px;"></el-input>-->
<!--  &lt;!&ndash;        <span class="tip-span ml20">关键词之间用逗号分开，最多可以添加5个</span>&ndash;&gt;-->
<!--        </el-form-item>-->

<!--&lt;!&ndash;        <el-form-item label='市场参考价链接：' prop="web_url">&ndash;&gt;-->
<!--&lt;!&ndash;          <el-input v-model.trim="goodsAfterSaleForm.web_url" placeholder="请输入京东或者淘宝的商品链接" style="width:420px;"></el-input>&ndash;&gt;-->
<!--&lt;!&ndash;        </el-form-item>&ndash;&gt;-->
<!--        <el-form-item label='商品编码：' prop="out_goods_id">-->
<!--          <el-input v-model.trim="goodsAfterSaleForm.out_goods_id" placeholder="请输入商品编码（非必须）" style="width:420px;"></el-input>-->
<!--        </el-form-item>-->


<!--    </el-card>-->
  </el-form>
  </div>
</template>

<script>
  import { GetFreight } from '@/api/module/goods'
  import { getBrandsInf } from '@/api/module/brand/brand'
  import { getnewAreaList } from '@/api/module/retreat/address'
  import draggable from 'vuedraggable'
  export default {
    name: "goodsaftersale",
    props: {
      goodsaftersale: {
        type: Object,
        required: true
      },
      option: {
        type: Number,
        required: true
      }
    },
    data() {
      let checkStags = (rule, value, callback) => {
        if (this.goodsAfterSaleForm.stags.length === 0) {
          callback(new Error("请选择服务类型"));
        } else {
          callback();
        }
      };
      return {        
        loading: false,
        brandOptions: [], // 商品品牌
        oldbrandOptions: [], // 初始化品牌
        goodssxRules: {
          categoryStr: [{ required: true, message: '商品分类不能为空', trigger: 'blur' }],
          goods_name: [
            { required: true, message: '请输入商品名称', trigger: 'blur' },
            { min: 3, max: 50, message: '商品标题限制在3字符以上，50个字符以下', trigger: 'blur' }
          ],
          brand_id: [{ required: true, message: '请选择商品品牌', trigger: 'change' }],
          // ssfl: [{ required: true, message: '请选择商品税收分类', trigger: 'change' }],
          // goods_des: [{required: true, validator: goodsDecCheck, trigger: 'blur'}],
          producing_area_id_list:[{required: true, message: '请选择商品产地', trigger: 'change'}],
          deliver_area_id_list: [{ required: true, message: '请选择商品发货地', trigger: 'change' }],
          metering_unit: [{ required: true, message: '计量单位不能为空', trigger: 'change' }],
          goods_brand: [{ required: true, message: '请选择商品品牌', trigger: 'change' }],
         
        },
        areaOptions: [], // 地址 省
        list:[
          {
            key:'1',
            value:''
          },{
            key:'2',
            value:''
          },
          {
            key:'3',
            value:''
          },
          {
            key:'4',
            value:''
          },
          {
            key:'5',
            value:''
          }
        ],
        areaProps: {
          checkStrictly: false,
          expandTrigger: 'click',
          emitPath: true,
          // lazy: true,
          // lazyLoad: this.areaLazyLoad,
          value: "id",
          label: "name",
          leaf: "leaf"
        },
        goodsAfterSaleForm: {
          producing_area_id_list: '',   // 产地id
          producing_area: '',   // 产地name
          deliver_area_id_list: '',     // 发货地id
          deliver_area: '',     // 发货地name
          goods_brand: '',      // 品牌
          brand_id: '',          // 品牌id
          stags: [],
          freight_id: '',
          delay_compensate: 24,
          aftersale_time: 7,
          // 参数
          params:[
            {
              'title':'',
              'value':''
            }
          ],
        },
        goodsAfterSaleRules: {
          brand_id: [{ required: true, message: '请选择商品品牌', trigger: 'change' }],
          producing_area_id_list:[{required: true, message: '请选择商品产地', trigger: 'change'}],
          deliver_area_id_list: [{ required: true, message: '请选择商品发货地', trigger: 'change' }],
          stags: [{ type: 'array', required: true, message: '请选择至少一个服务标签', trigger: 'change' }],
          freight_id: [{required: true, message: '请选择邮费模板', trigger: 'change'}],
          delay_compensate: [{required: true, message: '请选择发货时效', trigger: 'change'}],
          aftersale_time: [{required: true, message: '请选择售后时长', trigger: 'change'}],
        },
        tagOptions: [
          {id: 2, tag: "假一赔十"},
          {id: 3, tag: "7天退换"},
          {id: 4, tag: "不可退换"},
          {id: 5, tag: "厂家直供"},
          {id: 6, tag: "售后无忧"}
        ],
        freightOptions: []
      } // return end
    },
    components: { draggable },
    mounted() {
      this.getnewaddress()
      this.getFreightData();
      // debugger
      // console.log('售后数据：',this.goodsaftersale);
      if(this.goodsaftersale) {
        this.goodsAfterSaleForm = this.goodsaftersale;
        this.goodsAfterSaleForm.brand_id = this.goodsaftersale.brand_id?this.goodsaftersale.brand_id.toString():''
        debugger
      }
    },
    created() {
      // 获取 省
      // this.getArea();
      this.getBrands();
    },
    methods: {
        // 跳转到对应页面
        toPage(name) {
        switch (name) {
          case 'brand' : {
            // this.$router.push({ path: '/system/shop/brand' });
            this.$router.push({ path: '/system/goods/brand' });
            break;
          }
          case 'metering_unit' : {
            this.$router.push({ path: '/system/goods/commodityUnit' });
            break;
          }
          case 'group' : {
            // this.$router.push({ path: '/system/settings/commodityGroup' });
            this.$router.push({ path: '/system/goods/commodityGroup' });
            break;
          }
          case 'supplier' : {
            this.$router.push({ path: '/system/supplier/supplier' });
            break;
          }
          case 'warehouse' : {
            this.$router.push({ path: '/system/warehouse/wareHouse' });
            break;
          }
        }
      },
      searchbtn(query){//品牌搜索
        if (query !== '') {
          this.brandOptions = []
          this.loading = true;
          setTimeout(() => {
            this.loading = false;
            let data = {
                brand_name:query,
                status: 1,
                page:1,
                limit:100
              }
        getBrandsInf(data).then(res => {
          if (res.data) {
            this.brandOptions =  res.data.data
          }
        });
          }, 2000);
        } else {
          this.brandOptions = this.oldbrandOptions
        }
      },
      // 获取 商品品牌
      seachid(datelist,brand_id){//查找初始化数组是否存在回显的品牌
        datelist.some(item=>{
                if(item.id==brand_id){
                  return true
                }
              })
      },
      getBrands() {
        // 增加入参
        let data = {
          status: 1,
          page:1,
          limit:100
        }
        getBrandsInf(data).then(res => {
          if (res.data) {
            let datelist = res.data.data ? res.data.data : []
            if(this.goodsaftersale&&this.goodsaftersale.brand_id){
              if(this.seachid(datelist,this.goodsaftersale.brand_id)){

              }else{
                datelist.push({
                  id:this.goodsaftersale.brand_id,
                  brand_cn:this.goodsaftersale.goods_brand
                  // brand_cn:'大傻逼'
                })
              }
          }
            this.brandOptions = datelist
            this.oldbrandOptions = datelist
           
          }
        });
      },
      getnewaddress(){
        let data = {
          type:2
        }
        getnewAreaList(data).then(res=>{
          if(res.code==1){
            let datelist= this.removeEmptyChildren(res.data)
            this.areaOptions =datelist
            debugger
          }
        })
      },
   removeEmptyChildren (node) {
            node.forEach(item => {
              if ('children' in item && item.children.length === 0) {
                delete item.children
              } else if ('children' in item && item.children.length) {
                this.removeEmptyChildren(item.children)
              }
            })
            return node
          },
        // 产地
        areaLazyLoad(node, resolve) {
        this.getArea(node, resolve);
      },
      // 商品产地
      getArea(node, resolve) {
        const level = node.level
        let date = {}
        if (level === 0) {
          date = { pid: 0 }
        }else {
          date = { pid: node.value }
        }
        getAreaList(date).then(res => {
          let result = {}
          result = res.data
          if (level === 0) {
            result.forEach(item => {
              item.value = item.id;
              item.label = item.name
              item.children=[]
              item.leaf = level
            })
          }
          if (level === 1) {
            result.forEach(item => {
              item.value = item.id;
              item.label = item.name
              // item.children=[]
              //这句代码表示当点击最后一级的时候 label后面不会转圈圈 并把相关值赋值到选择器上
              item.leaf = level >= 1
            })
          }
          // if (level === 2) {
          //   result.forEach(item => {
          //     item.value = item.id;
          //     item.label = item.name
          //     //这句代码表示当点击最后一级的时候 label后面不会转圈圈 并把相关值赋值到选择器上
          //     item.leaf = 1
          //   })
          // }
          resolve(result)
        })
      },
      // 产地查处id对应的中文地址
      matchIdName(typeName) {
        if(this.$refs[typeName].getCheckedNodes()[0]){

        }else{
          return 
        }
        let areaLabelList = this.$refs[typeName].getCheckedNodes()[0].pathLabels;
        let areaLastName = 0;
        if (areaLabelList.length > 0) {
          areaLastName = areaLabelList.length - 1
          // 产地
          if (typeName === "producing_area") {
            this.goodsAfterSaleForm.producing_area = areaLabelList[areaLastName]
          }
          // 发货地
          if (typeName === "deliver_area") {
            this.goodsAfterSaleForm.deliver_area = areaLabelList[areaLastName]
          }
        }
      },
      diupfont(){
        this.$forceUpdate()
        
      },
      diupfont1(){
        this.$forceUpdate()
        
      },
      diupfont2(){
        this.$forceUpdate()
        
      },
      updatelist(){
        this.$forceUpdate()
      },
      // 添加参数
     // 添加参数
     addparameter(){
        let obj = {
          title:'',
          value:''
        }
          this.goodsAfterSaleForm.params.push(obj)
          this.$forceUpdate()//点编辑过来的时候，因为多层嵌套组件，照成视图没有更新，调用这个方法，（分析的应该是这样）
      },
      
      deleteparameter(index){
        this.goodsAfterSaleForm.params.splice(index, 1)
        this.$forceUpdate()
      },
      /** 售后服务数据 初始化 */
      initInfo() {
        this.$refs.goodsAfterSaleForm.resetFields();
      },
      // 运费模板
      getFreightData() {
        let params = {
          is_status: 1
        }
        GetFreight(params).then(res => {
          if(res.data) {
            this.freightOptions = res.data;

            if (this.option == 0) {
              for (let i = 0; i < res.data.length; i++) {
                if (res.data[i].is_default == 1) {
                  // this.goodsAfterSaleForm.freight_id = res.data[i].id
                }
              }
            }
          }else {
            this.freightOptions = ''
          }
        });
      },
      // 服务标签，7天退换、不可退换互斥
      serviceTagsChange(id) {
        debugger
        let index4 = this.goodsAfterSaleForm.stags.indexOf(4);
        let index3 = this.goodsAfterSaleForm.stags.indexOf(3);
        if(id == 3) {
          if( index4 > -1) {
            this.goodsAfterSaleForm.stags.splice(index4,1)
          }
        }
        if(id == 4) {
          if( index3 > -1) {
            this.goodsAfterSaleForm.stags.splice(index3,1)
          }
        }
      },
      // 商品信息 子组件 form表单校验, 在父组件中被调用
      validateGoodsAfterSaleForm () {
        let flag = null
        this.$refs['goodsAfterSaleForm'].validate(valid => {
          if (valid) {
            flag = true
          } else {
            flag = false
            // if(this.goodsAfterSaleForm.producing_area==''||this.goodsAfterSaleForm.deliver_area==''||this.goodsAfterSaleForm.unit==''){
            //   sessionStorage.setItem('clickbtm',1)
            // }else{
            //   sessionStorage.setItem('clickbtm',2)
            // }
          }
        })
        return flag
      },

    } // methods end
  }
</script>

<style lang="scss" type="text/stylus" scoped>
.goods-after-sale {
  padding: 20px;
  margin-bottom:20px;
  box-shadow:none;
}
.box-card{
  margin-bottom: 20px;
  //padding: 10px;
}
::v-deep .box-card .el-card__header{
  border-bottom: none;
  font-size: 18px;
  font-weight: 500;
  padding-left: 20px;
}
.curspor{
  font-size: 16px;
}
.curspor:hover{
  cursor: pointer;
}
</style>
