<template>
  <zj-page-layout hasFooter>
    <view class="all-container">
      <view class="top-container">
        <view class="row">
          <view class="label"><text>*</text>商品名称</view>
          <u--textarea v-model="name" placeholder="请输入商品名称" autoHeight border="none" ></u--textarea>
        </view>
        <view class="row">
          <view class="label"><text>*</text>商品描述</view>
          <u--textarea v-model="description" placeholder="请输入商品描述" autoHeight border="none" ></u--textarea>
        </view>
        <view class="row">
          <view class="label"><text>*</text>商品图片（最多9张）</view>
          <view class="images">
            <view class="img" v-for="(it, idx) in imageList">
              <image :src="it" mode="aspectFill" @tap="prevImg(it)"></image>
              <text class="iconfont icon-guanbi1" @tap="delImage(idx)"></text>
            </view>
            <view class="add" @tap="addImage()" v-if="imageList.length < 9">
              <text class="iconfont icon-jiahao"></text>
              <text class="text">上传图片</text>
            </view>
          </view>
        </view>
      </view>

      <view class="bottom-container">
        <view class="row column">
          <view class="label"><text>*</text>商品分类</view>
          <view class="radio">
            <view
              class="it ellipsis"
              :class="category == item.categoryId ? 'active' : ''"
              @tap="category = item.categoryId"
              v-for="(item, index) in categoryList"
              :key="index">
              {{item.name}}
            </view>
          </view>
        </view>
        <view class="row aic">
          <view class="label"><text>*</text>商品价格（含运费）</view>
          <u--input placeholder="请输入金额，0为面议" border="none" inputAlign="right" type="digit" v-model="price"></u--input>
        </view>
        <view class="row aic">
          <view class="label"><text>*</text>上架数量</view>
          <u--input placeholder="请输入数量" border="none" inputAlign="right" type="number" v-model="num"></u--input>
        </view>
        <view class="row aic">
          <view class="label">商品品牌</view>
          <u--input placeholder="请输入如格力、美的" border="none" inputAlign="right" v-model="brand"></u--input>
        </view>
        <view class="row aic">
          <view class="label">功率（W）</view>
          <u--input placeholder="请输入" border="none" inputAlign="right" v-model="power"></u--input>
        </view>
        <view class="row column">
          <view class="label">能效标识</view>
          <view class="radio">
            <view
              class="it ellipsis"
              :class="energy == item ? 'active' : ''"
              @tap="energy = item"
              v-for="(item, index) in energyList"
              :key="index">
              {{item}}
            </view>
          </view>
        </view>
        <view class="row aic">
          <view class="label">制造日期</view>
          <view class="right" @tap="isShowDatePicker = true">
            <view class="placeholder" v-if="!date">请选择</view>
            <view v-else>{{date}}</view>
            <view class="iconfont icon-jinru"></view>
          </view>
        </view>
      </view>
    </view>

    <template slot="footer">
      <view class="footer-btn-group">
        <u-button type="primary" text="发布" shape="circle" @tap="submitData"></u-button>
      </view>
    </template>

    <u-datetime-picker
      :show="isShowDatePicker"
      v-model="datePickerValue"
      mode="year-month"
      closeOnClickOverlay
      @confirm="confirmDatePicker"
      @cancel="isShowDatePicker = false"
      @close="isShowDatePicker = false"
    ></u-datetime-picker>
  </zj-page-layout>
</template>

<script>
  import { uploadImgFull } from '@/common/utils/util.js';

  export default {
    data() {
      return {
        id: '',
        type: 1,

        name: '',
        description: '',
        imageList: [],
        category: '',
        price: '',
        num: 1,
        brand: '',
        power: '',
        energy: '',
        date: '',

        categoryList: [],
        isShowDatePicker: false,
        datePickerValue: Number(new Date()),
        energyList: ['一级能效', '二级能效', '三级能效', '四级能效', '五级能效'],
      }
    },

    onLoad({id = '', type = 1}) {
      this.id = id;
      this.type = type;
      this.getCategoryList();

      if(id) {
        this.getDetail();
      }
    },

    methods: {
      getCategoryList() {
        this.$api.get('/goods/category/list', {
          type: 5,
        }).then(res => {
          this.categoryList = res.data;
        })
      },

      getDetail() {
        this.$api.post('/es/goods/detail', {
          id: this.id,
        }).then(res => {
          const data = res.data;
          this.name = data.goodsName;
          this.description = data.goodsNote;
          this.imageList = data.imgList.map(o => o.imgUrl);
          this.category = data.categoryId;
          this.price = data.price;
          this.num = data.qty;
          this.brand = data.brand;
          this.power = data.power;
          this.energy = data.mark;
          this.date = data.makeDate;
        })
      },

      // 添加图片
      async addImage() {
      	uni.chooseImage({
      		count: 9 - this.imageList.length,
          sizeType: ['compressed'],
      		success: res => {
      			uni.showLoading();
      			res.tempFilePaths.forEach(async item => {
      				let data = await uploadImgFull(item);
              this.imageList.push(data.url);
      			});
      			uni.hideLoading();
      		},
      		fail: err => {}
      	})
      },

      // 删除图片
      delImage(idx) {
        this.imageList.splice(idx, 1);
      },

      //预览图片
      prevImg(url) {
      	uni.previewImage({
      		current: url,
      		urls: this.imageList
      	})
      },

      confirmDatePicker(e) {
        const timestamp = e.value;
        const date = new Date(timestamp); // 将时间戳转换为日期对象
        const year = date.getFullYear(); // 获取年份
        const month = date.getMonth() + 1; // 获取月份
        this.date = `${year}-${String(month).padStart(2, '0')}`;
        this.isShowDatePicker = false;
      },

      submitData() {
        if(!this.name) return this.$toast('请输入商品名称');
        if(!this.description) return this.$toast('请输入商品描述');
        if(!this.category) return this.$toast('请选择商品分类');
        if(!this.imageList.length) return this.$toast('请上传商品图片');
        if(!this.price && this.price !== 0) return this.$toast('请输入商品价格');
        if(!this.num) return this.$toast('请输入上架数量');

        this.$api.postJson((this.id && this.type == 2) ? '/es/goods/update' : '/es/goods/add', {
          id: this.id,
          goodsName: this.name,
          goodsNote: this.description,
          imgList: this.imageList.map(o => {
            return {
              imgUrl: o
            }
          }),
          categoryId: this.category,
          categoryName: this.categoryList.find(o => o.categoryId == this.category).name,
          price: this.price,
          qty: this.num,
          brand: this.brand,
          power: this.power,
          mark: this.energy,
          makeDate: this.date,
        }).then(res => {
          this.$successToast(this.id ? '编辑成功' : '发布成功');
          this.crossPage.$emit('refreshRecycleList');
          this.crossPage.$emit('refreshRecycleIssueList');
          this.crossPage.$emit('refreshRecycleDetail');
          this.$navToPage({
          	delta: 1
          }, 'navigateBack')
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.all-container {
  padding: 20rpx 0 60rpx;
}

.top-container {
  background: #ffffff;
  padding: 30rpx;
  .row {
    border-bottom: 1px solid #eaeaea;
    padding: 20rpx 0;
    &:first-child {
      padding-top: 0;
      margin-top: 0;
    }
    &:last-child {
      padding-bottom: 0;
      border-bottom: none;
    }
    .label {
      font-size: 28rpx;
      font-weight: 500;
      text {
        color: red;
      }
    }
    .images {
      display: flex;
      flex-wrap: wrap;
      .add {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        width: 180rpx;
        height: 180rpx;
        border: 2rpx dashed #dadada;
        border-radius: 10rpx;
        margin-top: 20rpx;
        box-sizing: border-box;
        .iconfont {
          font-size: 48rpx;
          color: #999999;
        }
        .text {
          font-size: 24rpx;
          color: #999999;
          margin-top: 10rpx;
        }
      }
      .img {
        position: relative;
        margin-right: 20rpx;
        margin-top: 20rpx;
        image {
          width: 180rpx;
          height: 180rpx;
          border-radius: 10rpx;
          overflow: hidden;
          display: block;
        }
        video {
          width: 100%;
          height: 240px;
        }
        text {
          position: absolute;
          right: -10rpx;
          top: -10rpx;
          width: 40rpx;
          height: 40rpx;
          border-radius: 50%;
          background: #FF3F42;
          font-size: 24rpx;
          color: #FFFFFF;
          text-align: center;
          line-height: 40rpx;
          display: block;
        }
      }
    }
  }
}

.bottom-container {
  background: #ffffff;
  padding: 30rpx;
  margin-top: 20rpx;
  .row {
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #eaeaea;
    padding: 20rpx 0;
    &:first-child {
      padding-top: 0;
      margin-top: 0;
    }
    &:last-child {
      padding-bottom: 0;
      border-bottom: none;
    }
    &.aic {
      align-items: center;
    }
    &.column {
      flex-direction: column;
    }
    .label {
      font-size: 28rpx;
      font-weight: 500;
      margin-right: 40rpx;
      flex-shrink: 0;
      text {
        color: red;
      }
    }
    .radio {
      display: flex;
      flex-wrap: wrap;
      .it {
        width: calc((100% - 20rpx) / 2);
        height: 76rpx;
        border-radius: 76rpx;
        background: #f5f5f5;
        font-size: 28rpx;
        line-height: 76rpx;
        text-align: center;
        margin-top: 20rpx;
        margin-right: 20rpx;
        padding: 0 20rpx;
        box-sizing: border-box;
        &:nth-child(2n) {
          margin-right: 0;
        }
        &.active {
          background: rgba($color: $theme-color, $alpha: .1);
          border: 1rpx solid $theme-color;
          color: $theme-color;
          font-weight: 500;
        }
      }
    }
    ::v-deep .u-radio-group {
      flex-wrap: wrap;
      .u-radio {
        width: 50%;
        margin-top: 20rpx;
        justify-content: flex-end;
        &:nth-child(1), &:nth-child(2) {
          margin-top: 0;
        }
      }
    }
    .right {
      display: flex;
      align-items: center;
      .placeholder {
        font-size: 28rpx;
        color: $sec-font;
      }
      .iconfont {
        margin-left: 12rpx;
      }
    }
  }
}

</style>
