<template>
  <div class="good-info-box" v-loading="loading > 0">
    <Header :title="title"></Header>
    <div class="container">
      <div class="content">
        <div class="base-info group">
          <div class="basic">
            <!-- <span>*</span> -->
            基本信息
          </div>
          <el-form
            ref="form"
            :rules="rules"
            :model="baseInfo"
            class="good-form base-info-form"
            label-width="auto"
          >
            <el-form-item label="商品名称" prop="name" class="form-item">
              <el-input
                placeholder="请输入商品名称"
                v-model="baseInfo.name"
                class="good-input"
              ></el-input>
              <span class="tip">商品名称不要超过五十个字</span>
            </el-form-item>
            <el-form-item label="宣传语" prop="tagline" class="form-item">
              <el-input
                placeholder="商品备注/副标题"
                v-model="baseInfo.tagline"
                class="good-input"
              ></el-input>
              <span class="tip">商品描述不要超过四十个字</span>
            </el-form-item>
            <el-form-item
              label="关联分类"
              prop="secondSortId"
              class="form-item"
            >
              <!-- <el-select
                placeholder="请选择"
                v-model="baseInfo.secondSortId"
                class="good-input"
                style="width: 185px"
              >
                <el-option
                  v-for="item in categoryList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                ></el-option>
              </el-select> -->
              <el-cascader
                v-model="baseInfo.secondSortId"
                :options="categoryList"
                placeholder="请选择"
                :props="{
                  children: 'second',
                  value: 'id',
                  label: 'name',
                }"
                class="good-input"
                style="width: 185px"
              ></el-cascader>
            </el-form-item>
            <!-- <el-form-item label="关联分区" prop="secondSortId" class="form-item">
              <el-select
                placeholder="请选择"
                v-model="baseInfo.secondSortId"
                class="good-input"
                style="width: 185px"
              >
                <el-option
                  v-for="item in categoryList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                ></el-option>
              </el-select>
            </el-form-item> -->
            <el-form-item label="商品图片" class="form-item" prop="masterPic">
              <p class="tips" style="margin-bottom: 8px">
                建议尺寸：600*600，图片类型jpg、png
              </p>
              <div class="img-box">
                <imgUpLoader
                  :max-pic-num="1"
                  @getPics="getMasterImgList"
                  :index="0"
                  text="主图"
                  :imgUrl="baseInfo.masterPic"
                />
                <imgUpLoader
                  v-for="(item, index) in bannerNum"
                  :key="index"
                  :max-pic-num="1"
                  @getPics="getImgList"
                  :index="index"
                  text="细节图"
                  :imgUrl="baseInfo.slideshow[index]"
                />
              </div>
            </el-form-item>
            <el-form-item label="商品状态" prop="status" class="form-item">
              <el-radio-group v-model="baseInfo.status">
                <el-radio :label="3">出售中</el-radio>
                <el-radio :label="1">仓库中</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- <el-form-item label="商品类型" prop="genre" class="form-item">
              <el-select
                placeholder="请选择"
                v-model="baseInfo.genre"
                class="good-input"
                style="width: 185px"
              >
                <el-option :value="1" label="自营"></el-option>
                <el-option :value="2" label="供应链"></el-option>
              </el-select>
            </el-form-item> -->
            <!-- <el-form-item label="购买限制" prop="newBuy" class="form-item">
              <el-checkbox v-model="baseInfo.newBuy">仅新用户可购买</el-checkbox>
            </el-form-item> -->
            <!-- <el-form-item
              label="限购数量"
              prop="limitNum"
              class="form-item"
            >
              <el-input
                placeholder="请输入限购数量"
                v-model="baseInfo.limitNum"
                class="good-input"
                style="width: 150px"
              ></el-input>
            </el-form-item> -->
            <el-form-item
              label="商品销量"
              prop="baseMonthlySales"
              class="form-item"
            >
              <el-input
                placeholder="请输入商品销量"
                v-model="baseInfo.baseMonthlySales"
                class="good-input"
                style="width: 185px"
              >
                <template slot="append">件</template>
              </el-input>
            </el-form-item>
            <el-form-item label="商品成本" prop="cost" class="form-item">
              <el-input
                placeholder="请输入商品成本"
                v-model="baseInfo.cost"
                class="good-input"
                style="width: 185px"
              >
              <template slot="append">元</template>
            </el-input>
            </el-form-item>
            <el-form-item label="打赏成本" prop="rewardAmount" class="form-item">
              <el-input
                placeholder="请输入打赏成本"
                v-model="baseInfo.rewardAmount"
                class="good-input"
                style="width: 185px"
              >
              <template slot="append">元</template>
            </el-input>
            </el-form-item>
            <el-form-item label="商品商家" prop="sid" class="form-item">
              <el-select
                placeholder="请选择"
                v-model="baseInfo.sid"
                class="good-input"
                style="width: 185px"
              >
                <el-option
                  v-for="item in businessList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="供应链商品ID" prop="chainId" class="form-item">
              <el-input
                placeholder="请输入供应链商品ID"
                v-model="baseInfo.chainId"
                class="good-input"
                style="width: 180px"
              ></el-input>
            </el-form-item>
            <!-- <el-form-item label="商品参数" prop="option" class="form-item">
              <div class="option-box">
                <div class="option-item option-head">
                  <div class="cell1">参数名称</div>
                  <div class="cell2">参数值</div>
                </div>
                <div class="option-item" v-for="(item, index) in optionList" :key="index">
                  <div class="cell1">
                    <input type="text" v-model="item.name" placeholder="请输入"/>
                  </div>
                  <div class="cell2">
                    <input type="text" v-model="item.value" placeholder="请输入"/>
                  </div>
                </div>
                <div class="option-btn" @click="addOption">+添加参数</div>
              </div>
            </el-form-item> -->
          </el-form>
        </div>
        <div class="good-specs-box group">
          <div class="basic">
            <!-- <span>*</span> -->
            售卖信息
          </div>
          <div class="specs good-specs">
            <goods-attr
              :attrSku="key"
              :skuTable="attribute"
              :sales="baseInfo.linePrice"
              @editAttr="editAttr"
              @getSales="getSales"
            />
          </div>
          <div class="specs good-specs-des"></div>
        </div>
        <div class="base-info group">
          <div class="basic">
            商品说明
            <span style="font-size: 13px"
              >该部分内容展示在商品详情页后部分</span
            >
          </div>
          <div class="remarks">
            <el-form class="good-form" label-width="auto">
              <el-form-item label="商品描述：" class="form-item">
                <el-input
                  type="textarea"
                  :rows="4"
                  placeholder="请输入商品描述"
                  v-model="baseInfo.detailDes"
                  class="remarks-input"
                >
                </el-input>
              </el-form-item>
            </el-form>
            <div class="good-detail">
              <UpImgDetail :max-pic-num="10" :imageList="baseInfo.detailPic" />
            </div>
          </div>
        </div>
      </div>
      <div class="btn-box">
        <button class="cancel-btn" @click="handleCancel">取消</button>
        <button class="confirm-btn" @click="handleConfirm">保存</button>
      </div>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
import GoodsAttr from '../../components/goods/goodsAttr';
import imgUpLoader from '../../components/goods/imgUpLoader';
import UpImgDetail from '../../components/goods/upImgDetail';
import Header from '../../components/common/header';
export default {
  components: { GoodsAttr, imgUpLoader, UpImgDetail, Header },
  name: 'goods-lock',
  data() {
    return {
      loading: 0,
      title: {
        // 页面标题
        firstTitile: '商品管理',
        secondTitle: '商品详情'
      },
      categoryList: [],
      goodsInfo: {},
      bannerNum: 5,
      rules: {
        name: [
          {
            required: true,
            message: '请输入商品名称',
            trigger: 'blur'
          },
          {
            max: 50,
            message: '商品名称不能超过五十个字',
            trigger: 'blur'
          }
        ],
        tagline: [
          {
            max: 40,
            message: '商品名称不能超过四十个字',
            trigger: 'blur'
          }
        ],
        secondSortId: [
          {
            required: true,
            message: '请输入商品分类',
            trigger: 'change'
          }
        ],
        masterPic: [
          {
            required: true,
            message: '请上传主图图片',
            trigger: 'change'
          }
        ],
        goods_type: [
          {
            required: true,
            message: '请选择类型',
            trigger: 'change'
          }
        ],
        status: [
          {
            required: true,
            message: '请选择状态',
            trigger: 'change'
          }
        ],
        genre: [
          {
            required: true,
            message: '请选择商品类型',
            trigger: 'change'
          }
        ],
        limitNum: [
          {
            required: true,
            message: '请输入限购数量',
            trigger: 'blur'
          }
        ],
        sid: [
          {
            required: true,
            message: '请选择商品商家',
            trigger: 'change'
          }
        ],
        freight: [
          {
            required: true,
            message: '请选择运费模板',
            trigger: 'change'
          }
        ]
      },
      attribute: [],
      key: [],
      // weight: false,
      remarks: '',
      skuList: [],
      gid: null,
      id: null,
      freightList: [],
      optionList: [{ name: '', value: '' }],
      baseInfo: {
        status: null,
        name: '',
        detailDes: '',
        detailPic: [],
        tagline: '',
        slideshow: [],
        secondSortId: null,
        linePrice: null,
        masterPic: '',
        genre: 1,
        baseMonthlySales: null,
        sid: null,
        cost: null,
        rewardAmount: null,
        twig: null,
        newBuy: 0,
        limitNum: 0,
        chainId: null,
        detailContent: '',
        shopId: null
      },
      businessList: []
    };
  },
  computed: {},
  async mounted() {
    this.getBusinessList();
    await this.getCategoryList();
    // this.getFreightList();
    let query = this.$route.query;
    if (query && query.gid) {
      this.gid = query.gid;
      this.getGoodDetail(query.gid);
    }
  },
  methods: {
    // 获取商品信息
    getGoodDetail(gid) {
      this.loading++;
      this.httpGet(this.$root.goodsDetail, { gid }).then(
        (res) => {
          this.loading--;
          let baseInfo = { ...this.baseInfo };
          for (let key in baseInfo) {
            baseInfo[key] = res[key];
          }
          baseInfo.secondSortId = [res.firstSortId, res.secondSortId];
          baseInfo.newBuy = Boolean(baseInfo.newBuy);
          this.baseInfo = { ...baseInfo };
          this.skuList = res.skuList;
          this.key = this.getAttrName(res.skuList);
          this.attribute = this.getAttrs(res.skuList);
          this.gid = res.gid;
          this.id = res.id;
        },
        (res) => {
          this.loading--;
          this.$message.error(res);
        }
      );
    },
    getBusinessList() {
      this.loading++;
      this.httpGet(this.$root.getBusinessList, {
        size: 9999
      }).then(
        (res) => {
          this.loading--;
          // this.businessList = [{ name: '未选择', id: 0 }, ...res.list];
          this.businessList = res.list;
        },
        (res) => {
          this.loading--;
          this.$message.error(res);
        }
      );
    },
    // 根据组件转换格式为接口需要格式
    getAttrs(skus) {
      let newSkus = [...skus];
      let skusFormat = newSkus.map((item) => {
        let obj = {};
        item.attrs.forEach((attr) => {
          obj[attr.keyName] = attr.value;
        });
        return {
          ...item,
          attribute: obj
        };
      });
      return skusFormat;
    },
    // 获取所有规格
    getAttrName(skus) {
      let newAttrs = [];
      skus.forEach((item) => {
        item.attrs.forEach((attr) => {
          if (newAttrs.indexOf(attr.keyName) < 0) {
            newAttrs.push(attr.keyName);
          }
        });
      });
      return newAttrs;
    },
    // 获取分类列表
    getCategoryList() {
      this.loading++;
      this.httpGet(this.$root.getGoodsCategoryList, {}).then(
        (res) => {
          this.loading--;
          this.categoryList = res.list.filter((item) => item.second.length);
        },
        (res) => {
          this.loading--;
          this.$message.error(res);
        }
      );
    },
    // 获取模板列表
    getFreightList() {
      this.loading++;
      this.httpGet(this.$root.getFreightList, {}).then(
        (res) => {
          this.loading--;
          this.freightList = res.list;
        },
        (res) => {
          this.loading--;
          this.$message.error(res);
        }
      );
    },
    // 取消
    handleCancel() {
      this.$router.push({ name: 'goodsManage' });
    },
    getMasterImgList(index, val) {
      if (val === '') {
        // slideshow.splice(index, 1);
        this.baseInfo.masterPic = null;
      } else {
        this.baseInfo.masterPic = val;
      }
      this.$refs.form.clearValidate(['masterPic']);
    },
    // 设置
    getImgList(index, val) {
      // 获取主图
      let slideshow = [...this.baseInfo.slideshow];
      if (val === '') {
        // slideshow.splice(index, 1);
        slideshow[index] = null;
      } else {
        slideshow[index] = val;
      }
      // this.bannerNum = slideshow.length <= 5 ? slideshow.length : 5;
      this.baseInfo.slideshow = slideshow;
      this.$refs.form.clearValidate(['slideshow']);
    },
    // 获取规格值
    editAttr(val) {
      console.log(val);
      let newSkus = val.map((item) => {
        let arr = [];
        for (let key in item.attribute) {
          arr.push({
            keyName: key,
            value: item.attribute[key]
          });
        }
        return {
          sku: {
            price: +item.price,
            stock: +item.stock,
            pic: item.pic,
            kid: item.kid,
            code: item.code,
            chainId: item.chainId,
            cost: +item.cost || 0
          },
          attrs: arr
        };
      });
      this.skuList = newSkus;
    },
    getSales(val) {
      this.baseInfo.linePrice = +val;
    },
    // getDetail(val) {
    //   this.baseInfoForm.details = [...val];
    // },
    // 下一步
    handleConfirm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (!this.skuList.length) {
            this.$message({
              message: '请选择商品规格',
              type: 'warning'
            });
            return;
          }
          // for (let spuKey in this.spu) {
          //   this.spu[spuKey] = this.baseInfo[spuKey];
          // }
          this.addGood();
        } else {
          this.$message({
            message: '请填写商品信息',
            type: 'warning'
          });
        }
      });
    },
    // 添加商品
    addGood() {
      // 请求数据
      let inputData = {
        spu: this.baseInfo,
        skuList: this.skuList,
        secondSortId: this.baseInfo.secondSortId[1]
      };
      console.log(inputData.spu);
      inputData.spu.slideshow = this.baseInfo.slideshow.filter((item) => item);
      inputData.spu.baseMonthlySales = +inputData.spu.baseMonthlySales || 0;
      inputData.spu.cost = +inputData.spu.cost || 0;
      inputData.spu.rewardAmount = +inputData.spu.rewardAmount || 0;
      inputData.spu.limitNum = +inputData.spu.limitNum || 0;
      inputData.spu.newBuy = +inputData.spu.newBuy || 0;
      // inputData.spu.freight = 1;
      // 是否为编辑商品
      let method = 'httpPost';
      if (this.gid) {
        method = 'httpPut';
        inputData.spu.id = this.id;
        inputData.spu.gid = this.gid;
      }
      this.loading++;
      this[method](
        this.gid ? this.$root.editGoods : this.$root.createGoods, // 添加商品 or 创建商品
        inputData
      ).then(
        (res) => {
          this.$message({
            message: this.gid ? '商品修改成功' : '商品创建成功',
            type: 'success'
          });
          this.loading--;
          this.$router.push({
            name: 'goodsManage'
          });
        },
        (res) => {
          this.loading--;
          this.$message.error(res);
        }
      );
    },
    addOption() {
      this.optionList.push({
        name: '',
        value: ''
      });
    }
  }
};
</script>
<style lang="stylus" rel="stylesheet/stylus">
@import '~assets/public.styl';
</style>
<style lang="stylus" rel="stylesheet/stylus" scoped>
@import '~assets/main.styl';

.good-info-box {
  height: 100%;
  width: 100%;
  flex-y(flex-start, flex-start);
  overflow-y: hidden;
  background: bg-color;

  .container {
    box-sizing: border-box;
    height: 100%;
    width: 100%;
    overflow-y: auto;
    flex-y(flex-start, flex-start);
    padding: 24px;

    // content 表格
    .content {
      flex: 1;
      width: 100%;
      font-size: 14px;
      background: white;
      box-sizing: border-box;
      padding: 24px 20px;
      border-radius: 2px;

      .group {
        .basic {
          height: 48px;
          line-height: 48px;
          font-size: 20px;
          text-indent: 20px;
          margin-top: 20px;
          color: gray3;
          flex-x(flex-start);

          span {
            // color: red;
            color: gray6;
            margin-right: 3px;
          }
        }
      }

      .base-info {
        .good-form {
          padding: 20px 0 30px;

          .img-box {
            flex-x(flex-start);
          }
        }

        .base-info-form {
          margin-left: 90px;
        }

        .good-input {
          width: 620px;
        }

        .tip {
          font-size: 14px;
          color: gray6;
          margin-left: 16px;
        }

        .red {
          color: red;
        }

        .option-box {
          background: #F7F8FA;
          padding: 0 24px;
          border-radius: 2px;
          border: 1px solid #E8E8E8;
          // height: 32px;
          overflow: hidden;

          .option-item {
            flex-x(flex-start);
            height: 40px;

            &.option-head {
              height: 32px;
            }

            input {
              height: 32px;
              background: #fff;
              border: 1px solid #E8E8E8;
              box-sizing: border-box;
            }

            .cell1 {
              width: 330px;

              input {
                width: 310px;
                padding: 0 10px;
                box-sizing: border-box;
              }
            }

            .cell2 {
              input {
                width: 500px;
                padding: 0 10px;
                box-sizing: border-box;
              }
            }
          }

          .option-btn {
            width: 94px;
            height: 32px;
            border: 1px solid #E8E8E8;
            box-sizing: border-box;
            background: #fff;
            flex-x(center);
            font-size: 14px;
            border-radius: 2px;
            cursor: pointer;
            margin-top: 12px;
            margin-bottom: 16px;
          }
        }
      }

      .good-specs-box {
        .good-specs {
          // padding: 20px;
          // border: 1px solid gray9;
          margin: 30px 70px 0 60px;
        }
      }

      .remarks {
        width: 100%;
        padding-left: 95px;
        box-sizing: border-box;

        .remarks-input {
          max-width: 600px;

          textarea {
            font-size: 14px;
            max-width: 600px;
          }
        }

        .good-detail {
          padding-left: 82px;
        }
      }

      .good-detail {
        padding-bottom: 50px;
      }
    }
  }

  .btn-box {
    background: white;
    width: 100%;
    flex-x(center);
    padding-bottom: 48px;

    .cancel-btn {
      width: 96px;
      height: 40px;
      cancel-btn();
      // border-radius: 23px;
    }

    .confirm-btn {
      width: 96px;
      height: 40px;
      margin-left: 20px;
      confirm-btn();
    }
  }
}
</style>
