<template>
  <div class="app-container">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-row>
        <el-col :span="12">

          <el-form-item label="商品名称" prop="goodsName">
            <el-input v-model="ruleForm.goodsName" style="width:400px;"></el-input>
            <el-popover
              placement="top-start" width="300" trigger="hover" content="最多允许输入30个汉字（60字符），建议标题内包含与商品相关的关键词">
              <i style="color: #e3c300;font-size:16px" class="el-icon-question" slot="reference"></i>
            </el-popover>
          </el-form-item>

          <el-form-item label="商品分类" prop="categoryId">
            <el-cascader v-model="ruleForm.categoryId" :props='propsaddress' :options="options1" @change="handleChange"
                         style="width:400px;"></el-cascader>
          </el-form-item>

          <el-form-item label="市场原价" prop="scPrice">
            <el-input v-model="ruleForm.scPrice" style="width:400px;"></el-input>
            元
            <el-popover
              placement="top-start" width="300" trigger="hover" content="市场原价起到参考的作用">
              <i style="color: #e3c300;font-size:16px" class="el-icon-question" slot="reference"></i>
            </el-popover>
          </el-form-item>

          <el-form-item label="指导售价" prop="price">
            <el-input v-model="ruleForm.price" style="width:400px;"></el-input>
            元
            <el-popover
              placement="top-start" width="300" trigger="hover" content="您建议下游商家售卖的价格">
              <i style="color: #e3c300;font-size:16px" class="el-icon-question" slot="reference"></i>
            </el-popover>
          </el-form-item>

          <el-form-item label="结算价格" prop="jsPrice">
            <el-input v-model="ruleForm.jsPrice" style="width:400px;"></el-input>
            元
            <el-popover
              placement="top-start" width="300" trigger="hover" content="您与云仓平台最终结算的价格">
              <i style="color: #e3c300;font-size:16px" class="el-icon-question" slot="reference"></i>
            </el-popover>
          </el-form-item>

          <el-form-item label="运费模板" prop="freightId">
            <el-radio-group v-model="ruleForm.resource" @change="freightIdTypeChange">
              <el-radio label='1'>运费模板</el-radio>
              <el-radio label='0'>单独运费</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="统一运费" v-if="ruleForm.resource==0" prop="wlPrice">
            <el-input v-model="ruleForm.wlPrice" style="width:400px;"></el-input>
          </el-form-item>

          <el-form-item label="运费模板" v-if="ruleForm.resource==1">
            <el-select v-model="ruleForm.freightId" placeholder="请选择运费模板" style="width:400px;" @change="selectTm">
              <el-option v-for="item in freightList" :key="item.Id" :label="item.Name" :value="item.Id"
                         style="text-align:center;"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="发货时效" prop="Delayompensate">
            <el-select v-model="ruleForm.Delayompensate" style="width:400px;" 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="aftersaleTime">
            <el-select v-model="ruleForm.aftersaleTime" style="width:400px;" placeholder="请选择售后时长">
              <el-option label="7天" value="7" style="text-align:center;"></el-option>
              <el-option label="15天" value="15" style="text-align:center;"></el-option>
              <el-option label="30天" value="30" style="text-align:center;"></el-option>
            </el-select>
          </el-form-item>

        </el-col>
        <!-- right -->
        <el-col :span="12">
          <el-form-item label="商品库存" prop="goodsNowStock">
            <el-input v-model.number="ruleForm.goodsNowStock" style="width:400px;"></el-input>
          </el-form-item>

          <el-form-item label="商品产地" prop="producingArea">
            <el-input v-model="ruleForm.producingArea	" style="width:400px;"></el-input>
          </el-form-item>

          <el-form-item label="商品重量" prop="weight">
            <el-input v-model="ruleForm.weight" style="width:400px;"></el-input>
            克（g）
          </el-form-item>
          <el-form-item label="商品单位" prop="unit">
            <el-input v-model="ruleForm.unit" style="width:400px;"></el-input>
          </el-form-item>

          <el-form-item label="商品品牌" prop="goodsBrand">
            <el-select v-model="ruleForm.goodsBrand" style="width:400px;" filterable @change="goodsBrandChange" placeholder="请选择品牌">
              <el-option
                v-for="item in brandOtions"
                :key="item.id"
                :label="item.brand_cn"
                :value="item.id">
              </el-option>
            </el-select>
            <el-link type="primary" @click="toBrand" :underline="false">添加品牌</el-link>
          </el-form-item>

          <el-form-item label="三方编号" prop="outGoodsId">
            <el-input v-model="ruleForm.outGoodsId" style="width:400px;"></el-input>
          </el-form-item>

          <el-form-item label="附加运费" prop="pywlPrice" v-if="ruleForm.resource==0">
            <el-input v-model="ruleForm.pywlPrice" style="width:400px;" placeholder="偏远地区六省"></el-input>
            元
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="商品备注" prop="mark">
        <el-input type="textarea" v-model="ruleForm.mark"></el-input>
      </el-form-item>
      <el-form-item label="服务标签" prop="serviceagsTags">
        <el-checkbox-group v-model="serviceagsTags">
          <el-checkbox v-for="item in tags" :label="item.id" true-label :key="item.id" :disabled="item.isdc" @change="serviceSingleChange(item.id)">{{item.tag}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="详情描述" style="height:600px; margin-bottom: 0;" prop="description">
        <quill-editor ref="myTextEditor" v-model="content" :options="editorOption" @change="onEditorChange" style="height:500px;"></quill-editor>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetGoodsInfForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import {
    GetCategory,
    GetFreight
  } from '@/api/module/goods'
  import {getBrandsInf} from '@/api/module/brand/brand'

  export default {
    name: 'goods',
    props: {
      infomationdatas: {
        type: Object,
        required: true
      }
    },
    data() {
      let categoryIdCheck = (rule, value, callback) => {
        if (this.ruleForm.categoryId == 0 || !this.ruleForm.categoryId) {
          callback(new Error("请选择商品分类"));
        } else {
          callback();
        }
      };
      return {
        tags: [
          {id: 2, tag: "假一赔十", isdc: false},
          {id: 3, tag: "7天退换", isdc: false},
          {id: 4, tag: "不可退还", isdc: false},
          {id: 5, tag: "厂家直供", isdc: false},
          {id: 6, tag: "售后无忧", isdc: false}
        ],
        propsaddress: {
          label: 'label',
          value: 'id',
        },
        content: '',
        editorOption: {
          placeholder: '编辑内容'
        },
        brandOtions: [],
        serviceagsTags: [],
        ruleForm: {
          outGoodsId: '',
          value: [],
          goodsId: 0,
          goodsName: '',
          scPrice: '',
          price: "", //市场价 单位分
          goodsNowStock: "",
          producingArea: '',
          weight: '',
          unit: '', //单位
          goodsBrand: '', //品牌
          resource: '1',
          categoryId: 0,
          freightId: 310, //运费模板ID
          wlPrice: '',
          pywlPrice: '',
          jsPrice: '', //协议价
          Delayompensate: "",
          aftersaleTime: '7',
          mark: '',
          serviceagsTags: [],
          description: ''
        },
        rules: {
          goodsName: [
            {required: true, message: '请输入商品名称', trigger: 'blur'},
            {min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur'}
          ],
          categoryId: [{required: true, message: '请选择商品分类', validator: categoryIdCheck}],
          price: [{required: true, message: '请填写指导售价', trigger: 'blur'}],
          jsPrice: [{required: true, message: '请填写结算售价', trigger: 'blur'}],
          scPrice: [{required: true, message: '请填写市场原价', trigger: 'blur'}],
          goodsNowStock: [
            {required: true, message: '商品库存不能为空', trigger: 'blur'},
            {type: 'number', message: '商品库存要填写数字'},
          ],
          unit: [{required: true, message: '商品单位不能为空', trigger: 'blur'}],
          goodsBrand: [{required: true, message: '商品品牌不能为空', trigger: 'change'}]
        },
        // 运费模板列表
        freightList: [],
        options1: []
      }
    },
    components: {},
    watch: {
      serviceagsTags: {
        handler(val, oldVal) {
          this.$set(this.ruleForm, 'serviceagsTags', val)
        },
        deep: true
      },
      content: {
        handler(val, oldVal) {
          this.$set(this.ruleForm, 'description', val)
        },
        deep: true
      },
      ruleForm: {
        handler(val, oldVal) {
          val.description = this.content;
          val.serviceagsTags = this.serviceagsTags;
          this.$emit('infomationclick', val);
        },
        deep: true
      },
      infomationdatas(curVal, oldVal) {
        console.log("商品信息子组件：",curVal);
        if (curVal) {
          this.ruleForm = curVal;
          if(curVal.freightId == 0) {
            this.ruleForm.resource = '0';
          }else {
            this.ruleForm.resource = '1';
          }

          this.content = this.ruleForm.description;

          // 初始化
          this.serviceagsTags = [];
          this.ruleForm.serviceagsTags.forEach((val) => {
            if (val) {
              let nid = parseInt(val);
              this.serviceagsTags.push(nid);
            }
          })
        }
      }
    },
    created() {

    },
    mounted() {
      this.getCategory();
      this.getFreight();
      this.getBrands();
    },
    methods: {
      // 服务标签 中，7天退换和不可退换只能2选一
      serviceSingleChange(id) {
        let index4 = this.serviceagsTags.indexOf(4);
        let index3 = this.serviceagsTags.indexOf(3);
        if(id == 3) {
          if( index4 > -1) {
            this.serviceagsTags.splice(index4,1)
          }
        }
        if(id == 4) {
          if( index3 > -1) {
            this.serviceagsTags.splice(index3,1)
          }
        }

        console.log(307,this.ruleForm);
      },
      // 运费模板类型，change事件
      freightIdTypeChange(val) {
        // 0  单独运费   1  是运费模板
        if(val === '1') {
          if(this.ruleForm.freightId == 0) {
            this.ruleForm.freightId = "全国包邮通用模板";
          }
        }
      },
      // 获取品牌信息
      getBrands() {
        getBrandsInf().then(res => {
          if (res.data.data) {
            this.brandOtions = res.data.data;
          }
        });
      },
      // 获取 商品分类 信息
      getCategory() {
        GetCategory({}).then(response => {
          this.options1 = response.data.data;
        });
      },
      // 运费模板
      getFreight() {
        GetFreight(this.queryParams).then(response => {
          this.freightList = response.data
        });
      },
      handleChange(value) {
        this.ruleForm.categoryId = value[value.length - 1]
      },
      setTreeData(arr) {
        //  删除所有 children,以防止多次调用
        arr.forEach(function (item) {
          delete item.children;
        });
        let map = {}; // 构建map
        arr.forEach(i => {
          map[i.third_id] = i; // 构建以third_id为键 当前数据为值
        });
        let treeData = [];
        arr.forEach(child => {
          const mapItem = map[child.parent_id]; // 判断当前数据的parent_id是否存在map中
          if (mapItem) { // 存在则表示当前数据不是最顶层数据
            // 注意: 这里的map中的数据是引用了arr的它的指向还是arr，当mapItem改变时arr也会改变,踩坑点
            (mapItem.children || (mapItem.children = [])).push(child); // 这里判断mapItem中是否存在children, 存在则插入当前数据, 不存在则赋值children为[]然后再插入当前数据
          } else { // 不存在则是组顶层数据
            treeData.push(child);
          }
        });
        return treeData;
      },
      onEditorChange({editor, html, text}) {
        this.content = html;
        //console.log(315,this.content);
      },
      // 商品品牌 向后台传入 name
      goodsBrandChange(indexId) {
        let obj = {};
        obj = this.brandOtions.find((item)=>{//这里的userList就是上面遍历的数据源
          return item.id === indexId;//筛选出匹配数据
        });
        this.ruleForm.goodsBrand = obj.brand_cn;
      },
      // 维护品牌
      toBrand() {
        this.$router.push({path: '/system/shop/brand'});
      },

      resetGoodsInfForm(formName) {
        this.$refs[formName].resetFields();
        // 详情描述，重置
        this.content = '';
        // 服务标签
        this.serviceagsTags = [];
        //console.log("重置后的数据：",this.ruleForm);
      },
      // 商品信息 子组件 form表单校验
      validateGoodsInfForm () {
        let flag = null
        this.$refs['ruleForm'].validate(valid => {
          if (valid) {
            flag = true
          } else {
            flag = false
          }
        })
        return flag
      },


      selectTm(indexId) {

      },

    }
  }
</script>
<style scoped>
  ul,
  li {
    list-style: none;
    /*margin: 0;*/
    /*padding: 0;*/
  }

  /*.ullist {*/
  /*  border: 1px solid #e7eaec;*/
  /*  padding: 10px;*/
  /*  margin-bottom: 10px;*/
  /*}*/

  .el-input-group {
    width: calc(100% - 60px);
  }
</style>
