<template>
  <el-dialog :title="choosePruoductObj.title"
             :visible.sync="choosePruoductObj.open"
             :width="choosePruoductObj.width"
             @open="init()"
             @close="cancel"
             append-to-body>
    <el-form ref="auditForm" inline :model="choosePruoductObj.queryParams" label-width="80px">
        <el-form-item label="商品名称" prop="nameLike">
          <el-input
            size="small"
            placeholder="请输入商品名称"
            v-model="choosePruoductObj.queryParams.nameLike"
            clearable
          />
        </el-form-item>
        <el-form-item label="商品编码" prop="outProductId">
        <el-input
          size="small"
          placeholder="请输入商品编码"
          v-model="choosePruoductObj.queryParams.outProductId"
          clearable
        />
        </el-form-item>
        <el-form-item style="float: right">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="getProductList">搜索</el-button>
        </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <span>申请展示日期范围：</span>
          <el-date-picker
            v-model="handleDateArray"
            clearable
            size="small"
            type="daterange"
            :picker-options="pickerOptions"
            value-format="yyyy-MM-dd"
            placeholder="选择日期范围"
            @change="handleDateChange"
          />
      <span style="color: #999; font-size: 12px;"> 温馨提示：尽量选择2天后的日期开始展示，为审核留出足够时间</span>
    </el-row>
    <el-table class="mt20"
              :data="choosePruoductObj.list"
              ref="table"
              v-loading="choosePruoductObj.loading"
              max-height="500" border
              row-key="productId"
              @selection-change="handleSelectionChange"
              :header-cell-style="{'text-align': 'center'}"
              :cell-style="{'text-align': 'center'}"
    >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="主图" prop="pic">
        <template slot-scope="{ row }">
          <el-image v-if="row.pic" :src="row.pic" :preview-src-list="[row.pic]" class="small-img"/>
        </template>
      </el-table-column>
      <el-table-column label="名称/编码" min-width="200" prop="outProductId">
        <template slot-scope="{ row }">
          <div>名称：{{ row.name }} </div>
          <div v-if="row.outProductId">编码：{{ row.outProductId }}</div>
        </template>
      </el-table-column>
      <el-table-column label="品牌/分类" prop="brandName">
        <template  #default="{ row }" >
          <div v-if="row.brandName">品牌：{{ row.brandName }}</div>
          <div v-if="row.productCategoryName">分类：{{ row.productCategoryName }}</div>
        </template>
      </el-table-column>
      <el-table-column label="价格/排序" prop="price">
        <template  #default="{ row }">
          <div v-if="row.price">价格：{{ row.price }}</div>
          <div v-if="row.sort">排序：{{ row.sort }}</div>
        </template>
      </el-table-column>
      <el-table-column label="场馆内上架状态/商品课程" prop="" width="180">
        <template  #default="{ row }">
          <dict-tag :value="row.publishStatus" prop-name="pms_publish_status"/>
          &nbsp;&nbsp;
          <dict-tag :value="row.isCourse" prop-name="pms_is_course" />
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="choosePruoductObj.total>0"
      :total="choosePruoductObj.total"
      :page.sync="choosePruoductObj.queryParams.pageNum"
      :limit.sync="choosePruoductObj.queryParams.pageSize"
      @pagination="getProductList"
    />
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">提 交</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import {listPmsProduct} from "@/api/pms/product";
import { getProductShow,addProductShow,updateProductShow} from "@/api/pms/productShow";
import ProductCategorySelect from "@/views/components/ProductCategorySelect.vue";

export default {
  components: {ProductCategorySelect},
  name: "ProductSelect",
  data() {
    return {
      loadingSelect: false,
      pickerOptions: {
        disabledDate(time) {
          // 返回 true 表示禁用，禁止选择今天之前的日期（今天及之后可选）
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      selectProduct: [],
      handleDateArray: [],
      form: {
        showStartTime:'',
        showEndTime:'',
        productId:'',
        id:''
      },
      choosePruoductObj: {
        loading: false,
        open: false,
        title: "选择商品提交申请",
        list: [],
        width: '60%',
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          sale:'1',
          nameLike: null,
          outProductId: null
        },
        total: 0
      }
    }
  },
  methods: {

    submitForm() {
      if (this.selectProduct.length>1 || this.selectProduct.length===0){
        this.$message.warning('请选择一条记录进行提交');
        return;
      }
      if(this.form.showStartTime=='' || this.form.showEndTime==''){
        this.$message.warning('请选择展示日期范围');
        return;
      }
      this.form.productId=this.selectProduct[0].id;

      // 判断是否为新增还是更新
      if(this.form.id){
        updateProductShow(this.form).then(()=>{
          this.$message.success('提交成功');
          this.choosePruoductObj.open=false;
          this.$emit("refreshData")
        })
      }else {
        addProductShow(this.form).then(()=>{
          this.$message.success('提交成功');
          this.choosePruoductObj.open=false;
          this.$emit("refreshData")
        })
      }
    },
    async init() {
      this.choosePruoductObj.queryParams.pageNum = 1;
      await this.getProductList();
      this.choosePruoductObj.open = true
      this.$nextTick(()=>{
        if (this.selectProduct.length>0){
          this.judge()
        }
      })
    },
    judge() {
      this.$nextTick(()=>{
        this.choosePruoductObj.list.forEach(ele => {
          if (this.selectProduct.some(item => item.id === ele.id)) {
            this.$refs.table.toggleRowSelection(ele, true)
          } else {
            this.$refs.table.toggleRowSelection(ele, false)
          }
        });
      })
    },
    handleDateChange(val) {
      if (val) {
        this.form.showStartTime = val[0];
        this.form.showEndTime = val[1];
      } else {
        delete this.form.showStartTime;
        delete this.form.showEndTime;
      }
    },
    handleSelectionChange(selection) {
      this.selectProduct= selection
    },
    async getProductList() {
      this.choosePruoductObj.loading = true;
      const query = {...this.choosePruoductObj.queryParams, pageNum: undefined, pageSize: undefined};
      const {pageNum, pageSize} = this.choosePruoductObj.queryParams;
      const pageReq = {page: pageNum - 1, size: pageSize};

      await listPmsProduct(query, pageReq).then(response => {
        const { content, totalElements } = response
        this.choosePruoductObj.list = content;
        this.choosePruoductObj.total = Number(totalElements);
        this.choosePruoductObj.loading = false;
      });
    },
    cancel() {
      this.$refs.table.clearSelection()
      this.selectProduct = [];
      this.handleDateArray = [];
      this.form = {
        showStartTime:'',
        showEndTime:'',
        productId:''
      }
      this.choosePruoductObj.open = false;
    }
  }
}
</script>

<style lang="stylus">
.line
  display flex
  align-items center
  margin-bottom: 5px;
  border-bottom 1px dashed #ccc

.line:last-child
  border-bottom 0 !important
  margin-bottom 0 !important
</style>
