<template>
  <div class="pageBox">
    <div class="cardBox">
      <div class="searchBox">
        <div class="row">
          <span>商品名称：</span>
          <el-input v-model="searchForm.sku_title" @keyup.enter.native="handleChoose" clearable></el-input>
        </div>
        <div class="row">
          <span>商品编码：</span>
          <el-input v-model="searchForm.external_sku_id" @keyup.enter.native="handleChoose" clearable></el-input>
        </div>
        <div class="row">
          <span>创建时间：</span>
          <el-date-picker
            v-model="filterTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            clearable
            style="width: 250px;"
            @change="handleChoose()">
          </el-date-picker>
        </div>
        <div class="row">
          <el-button type="primary" @click="handleChoose()" icon="el-icon-search">筛选</el-button>
        </div>
      </div>
    </div>

    <el-card>
      <div class="opaBox">
        <el-upload ref="myUpload" action="/api/combination/goods" :multiple="false" name="combinationGoods"
          :show-file-list="false" :on-success="uploadSuccess" :before-upload="beforeUpload"
          :on-error="uploadError" style="display:inline-block;margin: 0 15px 0 0;">
          <el-button type="primary" plain icon="el-icon-upload2">组合商品导入</el-button>
        </el-upload>
        <el-button type="primary" @click="addGoodsCombination" icon="el-icon-plus" v-if="is_admin">新增组合商品</el-button>
        <el-button type="warning" @click="handleExport" icon="el-icon-download">数据导出</el-button>
      </div>

      <el-table v-loading="loading" ref="multipleTable" :data="tableData" class="table" tooltip-effect="dark" border
        style="width: 100%" row-key="id" :tree-props="{ children: 'children' }" @sort-change="sortChange">
        <el-table-column label="商品信息" width="400" class-name="flex">
          <template slot-scope="scope">
            <div class="commodityimg">
              <img :src="scope.row.img_url" class="Img" />
            </div>
            <div>
              <p>{{ scope.row.title }}</p>
              <p>{{ scope.row.external_sku_id }}</p>
              <p>{{ scope.row.created_at }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="num" label="组合数量" align="center"></el-table-column>
        <el-table-column prop="order_goods_num" label="销量" align="center" sortable="custom"></el-table-column>
        <el-table-column label="剩余库存" align="center">
          <template slot-scope="scope">
            <span v-if="!scope.row.children">{{ scope.row.stock }}</span>
          </template>
        </el-table-column>
        
        <!-- <el-table-column prop="reference_price" label="售价"></el-table-column> -->
        <!-- <el-table-column sortable label="今日7点以后订单">
            <template slot-scope="scope">
                <div>
                    <span>{{ scope.row.order_goods_num }}</span>
                </div>
                <el-popover placement="right-start" trigger="hover" v-if="scope.row.order_detail.length !== 0">
                    <div>
                        <span v-for="(j, index) in scope.row.order_detail" :key="index">
                            <div>{{ j.shop.name }}:{{ j.number }}</div>
                        </span>
                    </div>
                    <el-button class="btn11" type="text" slot="reference"><img src="../../css/img/眼睛.png"
                            alt="" />
                    </el-button>
                </el-popover>
            </template>
        </el-table-column> -->
        <!-- <el-table-column sortable prop="total_orders_num" label="累计订单"></el-table-column> -->
        <el-table-column prop="sale_stock" label="可售库存" align="center" sortable="custom"></el-table-column>
        <el-table-column prop="status" label="状态" align="center"></el-table-column>
        <el-table-column label="操作" width="130" align="center" v-if="is_admin">
          <template slot-scope="scope">
            <el-button type="text" @click="handleEdit(scope.row.id)">编辑</el-button>
            <!-- <el-button type="text" @click="handleDelete(scope.row.id)">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>

      <div class="page-pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="current_page"
          :page-sizes="[10, 50, 100, 150, 200]"
          :page-size="per_page"
          layout="total, sizes, prev, pager, next, jumper"
          :total="Paginationdata.total">
        </el-pagination>
      </div>
    </el-card>

    <el-dialog title="新增组合商品" :visible.sync="dialogVisible">
      <el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="100px" class="demo-dynamic">
        <el-form-item label="商品名称" prop="title" :rules="[{ required: true, message: '请输入商品名称', trigger: 'blur' }]">
          <el-input v-model="dynamicValidateForm.title"></el-input>
        </el-form-item>
        <el-form-item label="商品编码" prop="external_sku_id">
          <el-input v-model="dynamicValidateForm.external_sku_id"></el-input>
        </el-form-item>
        <el-form-item v-for="(item, index) in dynamicValidateForm.combination_goods" :label="'花材' + (index + 1)"
          :key="item.item_id" :prop="'combination_goods.' + index + '.item_id'" :rules="{
              required: true, message: '子商品不能为空', trigger: 'blur'
          }">
          <div style="display: flex;align-items: center;">
            <el-select v-model="item.item_id" filterable remote reserve-keyword placeholder="请选择子商品"
              :remote-method="remoteMethod" :loading="remoteLoading" style="width: 240px;">
              <el-option v-for="sku in skus" :key="sku.id" :label="sku.title" :value="sku.id"></el-option>
            </el-select>
            <el-input v-model="item.item_num"  placeholder="数量" style="width: 120px;margin: 0 10px"></el-input>
            <el-button type="danger" size="mini" @click.prevent="removeItem(index)">删除</el-button>
          </div>
        </el-form-item>
        <el-form-item label=" ">
          <el-button @click="addItem" icon="el-icon-plus">添加花材</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('dynamicValidateForm')">提交</el-button>
          <el-button @click="resetForm('dynamicValidateForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
  import { getGoodsCombination, addGoodsCombination, showGoodsCombination, getGoodsFilter } from "@/api/goods.js";

  export default {
    data() {
      return {
        dialogVisible: false,
        loading: false,
        tableData: [], // 商品列表
        searchForm: {
          external_sku_id: '',
          sku_title: '' // 商品名称
        },
        sort_field: '',
        sort_value: '',
        Paginationdata: {}, // 分页相关数据
        current_page: 1, // 当前页
        per_page: 10, // 每页显示数量
        dynamicValidateForm: {
          id: 0,
          title: '',
          external_sku_id: '',
          combination_goods: [{
              item_id: '',
              item_num: 1
          }]
        },
        skus: [],
        is_admin: false,
        remoteLoading: false,
        filterTime: []
      }
    },
    methods: {
      // 列表编辑
      handleEdit(id) {
        this.dialogVisible = true;
        showGoodsCombination(id).then((res) => {
          this.dynamicValidateForm = res.data.data
          this.skus = res.data.data.skus
        })
      },
      handleDelete(id) {

      },
      // 获取商品列表
      getList() {
        this.loading = true
        let params = {
          ...this.searchForm,
          page: this.current_page,
          per_page: this.per_page,
          create_time_start: this.filterTime ? this.filterTime[0] : '',
          create_time_end: this.filterTime ? this.filterTime[1] : '',
          sort_field: this.sort_field || 'id',
          sort_value: this.sort_value || 'desc'
        }
        getGoodsCombination(params).then((res) => {
          this.tableData = res.data.data
          this.Paginationdata = res.data.meta
          this.currentPage = res.data.meta.current_page
          this.per_page = parseInt(res.data.meta.per_page)
          this.is_admin = res.data.manage && res.data.manage.is_admin
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      },
      // 筛选
      handleChoose() {
        this.current_page = 1
        this.getList()
      },
      handleSizeChange(val) {
        this.current_page = 1
        this.per_page = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.current_page = val
        this.getList()
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            addGoodsCombination(this.dynamicValidateForm).then((res) => {
              this.$message({
                message: res.data.message,
                type: 'success'
              })
              this.dialogVisible = false
              this.handleChoose()
            })
          }
        })
      },
      resetForm(formName) {
        this.$refs[formName].resetFields()
      },
      removeItem(index) {
        this.dynamicValidateForm.combination_goods.splice(index, 1)
      },
      addItem() {
        this.dynamicValidateForm.combination_goods.push({
          item_id: '',
          item_num: 1
        })
      },
      remoteMethod(query) {
        if (query !== '') {
            this.remoteLoading = true
            getGoodsFilter(query).then((res) => {
              this.skus = res.data.data
              this.remoteLoading = false
            })
        } else {
          this.skus = []
        }
      },
      addGoodsCombination() {
        this.dialogVisible = true;
        this.dynamicValidateForm = {
          id: 0,
          title: '',
          external_sku_id: '',
          combination_goods: [{
            item_id: '',
            item_num: 1
          }]
        }
      },
      beforeUpload() {
        this.loadingModule = this.$loading({
          lock: true,
          text: '表格导入中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
      },
      uploadSuccess(response) {
        this.$message({
          message: response.message,
          type: "success"
      });
        this.loadingModule.close()
      },
      uploadError(err) {
        this.$message({
          message: err.errorMessage,
          type: "error"
        });
        this.loadingModule.close()
      },
      handleExport() {
        let params = {
          exportType: 'goods_combination',
          external_sku_id: this.searchForm.external_sku_id,
          sku_title: this.searchForm.sku_title,
          create_time_start: this.filterTime ? this.filterTime[0] : '',
          create_time_end: this.filterTime ? this.filterTime[1] : ''
        }
        window.open("/goods_skus/export?" + this.objectToQueryString(params))
      },
      objectToQueryString(obj) {
        return Object.keys(obj)
              .map(key => encodeURIComponent(key) + '=' + (obj[key] ? encodeURIComponent(obj[key]) : ''))
              .join('&');
      },
      sortChange(column) {
        this.sort_field = column.order ? column.prop : ''
        this.sort_value = column.order ? (column.order == 'descending' ? 'desc' : 'asc') : ''
        this.current_page = 1
        this.getList()
      }
    },
    mounted() {
      this.handleCurrentChange(1)
    }
  }
</script>

<style lang="css" scoped>
  .searchBox{
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    white-space: nowrap;
    .row{
      font-size: 14px;
      margin-bottom: 20px;
      margin-right: 15px;
      display: flex;
      align-items: center;
    }
  }
  .opaBox{
    margin-bottom: 15px;
  }

  .btn {
    float: right;
  }

  .commodityimg {
    width: 59px;
    height: 59px;
    background: rgba(227, 227, 227, 0.39);
    opacity: 1;
    display: block;
    margin-right: 12px;
  }
  .Img {
    width: 100%;
    height: 100%;
  }
  ::v-deep .flex .cell{
    display: flex;
    align-items: center;
  }
  ::v-deep .btn11 {
    padding: 0;
    width: 14px;
    height: 14px;
  }

  ::v-deep .btn11 img {
    width: 100%;
    height: 100%;
  }

  .page {
    margin-top: 20px;
  }
</style>
