<template>
  <div class="app-container goods" v-loading="loading">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span style="font-size: 18px; float:left;margin-top: 4px;">{{title}}</span>
        <el-button style="float: right; margin: 0 10px 0 20px;" size="mini" type="info" plain @click="submitForm(0)">保 存 草 稿
        </el-button>
        <el-button style="float: right;" size="mini" type="primary" @click="submitForm(1)">提 交 上 架
        </el-button>
      </div>
      <el-tabs type="border-card">
        <el-tab-pane label="商品信息">
          <Goodsinfomation ref="childGoodsInf" :infomationdatas='infomationdata' @infomationclick='infomationclick'/>
        </el-tab-pane>
        <el-tab-pane label="商品图片">
          <Goodsimg :imgdata='imgdate' @imgclicks='imgclick'/>
        </el-tab-pane>
        <el-tab-pane label="商品规格">
          <Guide :guidedata='guidedate' @guideclicks='guideclick'/>
        </el-tab-pane>
        <el-tab-pane label="商品参数">
          <Goodsparameter :parameterdata='parameterdata' @parameterclicks='parameterclick'/>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
  import {getGoods,GetFreight} from '@/api/module/goods'
  import descartes from "@/utils/dikaerjs.js";
  import Guide from './components/guide'
  import Goodsinfomation from './components/goodsinfomation'
  import Goodsimg from './components/goodsimg'
  import Goodsparameter from './components/goodsparameter'
  import {addGoods} from '@/api/module/goods'
  export default {
    name: 'goods',
    data() {
      return {
        infomationdata: {},
        parameterdata: {},
        goodsOnsale: 0,
        loading: false,
        applyStatus: '',
        title: "添加新商品",
        imgdate: {},
        guidedate: {},
        parameterdate: {},
        params: {
          applyStatus: 0
        },
        expressTemplateIdList: [], //'原来绑定的运费模板已经被删除',
        expressTemplateList: [],
      }
    },
    components: {
      Guide,
      Goodsinfomation,
      Goodsimg,
      Goodsparameter
    },
    created() {
      this.getFreight();//运费模板数据，回显匹配专用
      this.getParams();
    },
    methods: {
      // 运费模板
      getFreight() {
        GetFreight(this.queryParams).then(res => {
          this.expressTemplateList = res.data;
          this.expressTemplateIdList = this.expressTemplateList.filter(function(item) {
            return item.Id;
          })
        });
      },
      getParams() {
        let goodsId = this.$route.query.goodsId;
        if (goodsId > 0) {
          this.title = "编辑商品信息";
          this.genGoodsInfo(goodsId);
        }
      },
      // 获取商品详情
      genGoodsInfo(goodsId) {
        this.loading = true;
        const goods_id = goodsId;
        getGoods(goods_id).then(res => {
          console.log(9999,res);
          if(res.code === 1 && res.data) {
            this.goodsOnsale = res.data.isOnsale;
            // 对发货时效单独处理
            if(res.data.Delayompensate == 0) {
              res.data.Delayompensate = '';
            }
            //res.data.freightId 返回的值类型有  0（string/number）|| ‘全国包邮通用模板’（string）|| 310(number)
            let resourceType = '1'; // 为了单元框正常显示，先给一个默认值，// 字符串 ‘0’,代表  数据为单独运费
            let serviceagsTagsVal = [];
            if(res.data.ServiceagsTags) {
              serviceagsTagsVal = JSON.parse(res.data.ServiceagsTags);
            }

            // 库存，后台返回字段更换，提前处理 specOption
            if( res.data.goodsSpecs.specOption && res.data.goodsSpecs.specOption.length > 0) {
              res.data.goodsSpecs.specOption.forEach(function(item){
                if(item.stock) {
                  item['goodsNowStock'] = item.stock;
                }
              });
            }

            this.infomationdata = {
              goodsId: res.data.goodsId,
              goodsName: res.data.goodsName,
              categoryId: res.data.categoryId,
              scPrice: res.data.scPrice / 100,
              price: res.data.price / 100,
              jsPrice: res.data.jsPrice / 100,
              goodsNowStock: res.data.goodsNowStock,
              producingArea: res.data.producingArea,
              weight: res.data.weight,
              unit: res.data.unit,
              goodsBrand: res.data.goodsBrand,
              wlPrice: res.data.wlPrice,
              pywlPrice: res.data.pywlPrice,
              resource: resourceType,
              Delayompensate: res.data.Delayompensate,
              aftersaleTime: res.data.aftersaleTime,
              mark: res.data.mark,
              serviceagsTags: serviceagsTagsVal,
              description: res.data.description,
              freightId: res.data.freightId,
              outGoodsId: res.data.outGoodsId,
            };
            this.guidedate = res.data.goodsSpecs;
            this.guidedate["goodsSpec"] = res.data.goodsSpec;
            this.parameterdata = res.data.Params ? res.data.Params : {};
            this.imgdate = {
              "ruleFormdialogImageUrl": res.data.image,
              "ruleFormdialogImageUrlplus": res.data.defaultImage
            };
          }else if(res.code === 0) {
            if(res.msg) {
              this.$message({type:'error',message: res.msg});
            }else {
              this.$message({type:'error',message: '数据出错啦'});
            }
          }

          this.loading = false;
        });
      },
      info() {
        addgoods(this.listQuery).then(res => {
          this.list = res.data.items
          this.total = res.data.total
          this.listLoading = false
        })
      },
      //商品信息
      infomationclick(type) {
        Object.assign(this.params, type);
      },
      //商品图片
      imgclick(type) {
        let img = [];
        type.ruleFormdialogImageUrl.forEach((res, index) => {
          img.push(res.url)
        })
        this.params["imgs"] = img;
        this.params["defaultImg"] = ''
        if(type.ruleFormdialogImageUrlplus.length > 0) {
          this.params["defaultImg"] = type.ruleFormdialogImageUrlplus[0].url;
        }
      },
      //规格
      guideclick(type, specsGroup) {
        this.params["specs"] = type;
        this.params["specsGroup"] = specsGroup;
        // 浮点处理
        if(this.params.specs && this.params.specs.length > 0) {
          for(let i = 0; i < this.params.specs.length; i++) {
            if(this.params.specs[i].jsPrice ) {
              this.params.specs[i].jsPrice = parseInt(this.params.specs[i].jsPrice * 100);
            }
            if(this.params.specs[i].price ) {
              this.params.specs[i].price = parseInt(this.params.specs[i].price * 100);
            }
            if(this.params.specs[i].scPrice ) {
              this.params.specs[i].scPrice = parseInt(this.params.specs[i].scPrice * 100);
            }
          }
        }
      },
      //参数
      parameterclick(type) {
        this.params["goodsPram"] = type;
      },

      /** 确定按钮 */
      submitForm(status) {
        this.params.applyStatus = 0;
        this.params.isOnsale = this.goodsOnsale;

        if(status === 1) {
          this.params.applyStatus = 1;
        }

        if(this.params.resource == 0) {
          this.params.freightId = 0;
        }else if(this.params.resource == 1) {
          this.params.wlPrice = 0;
          this.params.pywlPrice = 0;
          // 运费模板字段单独处理,兼容老数据
          if(this.params.freightId === '全国包邮通用模板' || this.params.freightId == 0) {
            this.params.freightId = 310;
          }
        }

        console.log("gogogogog",this.params);
        //return ;

        // 商品信息  表单字段校验
        let isGoodInfMsg = this.$refs['childGoodsInf'].validateGoodsInfForm();
        // 商品图片  校验
        let isGoodSImgMsg = 'defaultImg' in this.params;

        if(!isGoodInfMsg) {
          if(!('goodsName' in this.params)) {
            this.$message({type: 'error',message: '[ 商品信息 ] 未填写完整！'});
            return;
          }

          if('goodsName' in this.params) {
            if(this.params.goodsName === '') {
              this.$message({type: 'error',message: '[ 商品信息 ] 中 商品名称未填写！'});
              return;
            }

            if(this.params.categoryId === 0) {
              this.$message({type: 'error',message: '[ 商品信息 ] 中 商品分类未填写！'});
              return;
            }

            if(this.params.scPrice === '') {
              this.$message({type: 'error',message: '[ 商品信息 ] 中 市场原价未填写！'});
              return;
            }

            if(this.params.price === '') {
              this.$message({type: 'error',message: '[ 商品信息 ] 中 指导售价未填写！'});
              return;
            }

            if(this.params.jsPrice === '') {
              this.$message({type: 'error',message: '[ 商品信息 ] 中 结算价格未填写！'});
              return;
            }

            if(this.params.goodsNowStock === '') {
              this.$message({type: 'error',message: '[ 商品信息 ] 中 商品库存未填写！'});
              return;
            }

            if(this.params.unit === '') {
              this.$message({type: 'error',message: '[ 商品信息 ] 中 商品单位未填写！'});
              return;
            }

            if(this.params.goodsBrand === '') {
              this.$message({type: 'error',message: '[ 商品信息 ] 中 商品名称未填写！'});
              return;
            }
          }
        }

        if(!isGoodSImgMsg) {
          this.$message({type: 'error',message: '[ 商品图片 ] 未上传图片！'});
          return;
        }else {
          if('defaultImg' in this.params) {
            if(this.params.defaultImg === '') {
              this.$message({type: 'error',message: '[ 商品图片 ] 中 商品主图未上传！'});
              return;
            }
            if(this.params.imgs.length === 0) {
              this.$message({type: 'error',message: '[ 商品图片 ] 中 商品轮播图未上传！'});
              return;
            }
          }
        }
        this.loading = true;
        addGoods(this.params).then(res => {
          if (res.code === 1) {
            this.$message({
              message: res.msg,
              type: 'success'
            });
            this.$emit('closeDialog',false);
            if (this.goodsOnsale) {
              var redUrl = '/system/goods/onsale';
            } else {
              var redUrl = '/system/goods/offsale';
            }
            this.$router.push({
              path: redUrl
            });
          } else if(res.code === 0) {
            if(res.msg) {
              this.$message.error(res.msg);
            }else {
              this.$message.error("操作失败！");
            }

          }
          this.loading = false;
        });

      },
      //------  通用方法  -----
      verifiesForm(type,fieldName,obj) {
        // 先判断类型，字符串类型type === text,  下拉形式字段 select
        if(type === 'text') {
          // 没有这个属性，肯定没有填写，抛出提示
          if(!(fieldName in obj)) {
            return 1;
          }
        }

        if(type === 'select') {

        }

        // 如果有这个属性，那么进一步判断，这个必填值是否填写
        // if(fieldName in obj && !obj[fieldName]) {
        //   return 2
        // }

      }
    }
  }
</script>
<style scoped lang="scss" type="text/stylus">
  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);
  }

  .addbtn {
    background-color: #5bc0de !important;
    color: #fff !important;
    border-radius: 0 4px 4px 0;
  }

  /deep/.el-card__body {
    height: calc(100% - 50px);
    overflow: hidden;
  }

  .el-tabs {
    height: 100%;
    overflow: hidden;

    /deep/.el-tabs__content {
      height: calc(100% - 50px);
      overflow-y: scroll;
    }
  }

  .eldelbtn {
    height: 30px;
    padding: 5px 20px !important;
    margin-left: -3px;
  }

  .childlist {
    margin-top: 10px;
  }

  .el-button--medium {
    padding: 10px 12px;
  }

  .dfbtn {
    position: relative;
  }

  .goods .el-tabs__content {
    height: 100%;
    overflow-y: scroll;
  }
</style>
