<template>
  <el-dialog
    :visible.sync="dialogVisible"
    title="选择商品"
    width="1000px"
    @close="cancelSubmit()"
  >
    <div>
      <div class="search-item">
        <el-select
          v-model="type"
          clearable
          class="w-160"
          @change="changeType"
        >
          <el-option label="礼品" :value="0" />
          <el-option label="优惠券" :value="1" />
        </el-select>
      </div>
      <div class="search-item">
        <el-select
          v-model="giftType"
          placeholder="所有商品分类"
          clearable
          class="w-160"
          @change="changeGiftType"
        >
          <el-option label="实物礼品" :value="1" />
          <el-option label="虚拟礼品" :value="2" />
        </el-select>
      </div>
      <div class="search-item">
        <el-select
          v-model="shelf"
          placeholder="所有商品状态"
          clearable
          class="w-160"
          @change="getInfo"
        >
          <el-option label="已上架" :value="2" />
          <el-option label="已下架" :value="1" />
        </el-select>
      </div>
      <div class="search-item">
        <el-input
          v-model.trim="query.giftName"
          placeholder="请输入关键词进行搜索"
          prefix-icon="el-icon-search"
          clearable
          class="w-300"
          @change="getInfo"
        />
      </div>
    </div>
    <div v-loading="loading" style="margin-top:20px">
      <el-table
        :data="tableData"
        ref="maytable"
        style="width: 100%"
        :row-key="getRowKeys"
        @sort-change="sortChange"
        @row-click="handleSelectSingle"
        @selection-change="handleSelectAll"
      >
        <el-table-column type="selection" width="50" reserve-selection />
        <el-table-column label="商品信息" min-width="200px">
          <template slot-scope="{ row }">
            <div class="gift-info" v-if="!type">
              <img :src="row.mainImageUrl" alt>
              <div class="info-name">
                <div style="display:flex;flex-direction:column;justify-content:center;margin-top:7px">
                  <p class="pro-ellipsis">
                    {{ row.proName }}
                  </p>
                  <p class="category-ellipsis">
                    礼品编码：{{ row.proCode }}
                  </p>
                </div>
              </div>
            </div>
            <div class="gift-info" v-else>
              <img v-if="row.mainImageUrl" :src="row.mainImageUrl" alt>
              <img v-if="row.cardType === 2 && !row.mainImageUrl" src="../../static/img/quan02.png" alt>
              <img v-if="row.cardType === 0 && !row.mainImageUrl" src="../../static/img/quan01.png" alt>
              <img v-if="row.cardType === 1 && !row.mainImageUrl" src="../../static/img/quan03.png" alt>
              <div class="info-name">
                <div style="display:flex;flex-direction:column;justify-content:center;margin-top:7px">
                  <p class="pro-ellipsis">
                    {{ row.proTitle }}
                  </p>
                  <p v-if="row.proReferId.split(',').length > 1" class="category-ellipsis">
                    --
                  </p>
                  <p v-else class="category-ellipsis">
                    {{ row.remarks || '--' }}
                  </p>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="投放有效期" v-if="type" min-width="120px">
          <template slot-scope="{ row }">
            <p v-if="row.proReferId.split(',').length === 1 && row.exchangeFixDateBegin && row.exchangeFixDateEnd">
              {{ getTimeAll(row.exchangeFixDateBegin) }}&nbsp;至
            </p>
            <p v-if="row.proReferId.split(',').length === 1 && row.exchangeFixDateBegin && row.exchangeFixDateEnd">
              {{ getTimeAll(row.exchangeFixDateEnd) }}
            </p>
            <p v-if="row.proReferId.split(',').length === 1 && !row.exchangeFixDateBegin && !row.exchangeFixDateEnd">
              长期有效
            </p>
            <p v-if="row.proReferId.split(',').length !== 1">
              --
            </p>
          </template>
        </el-table-column>
        <el-table-column label="商品状态">
          <template slot-scope="{ row }">
            <span class="dm-status--success" v-if="row.status === 2 && row.canEdit && row.releaseType === 1">已上架</span>
            <span class="dm-status--info" v-if="row.status === 2 && row.canEdit && row.releaseType === 2 && row.isShelves === 1">已下架</span>
            <span class="dm-status--success" v-if="row.status === 2 && row.canEdit && row.releaseType === 2 && row.isShelves === 0">已上架</span>
            <span class="dm-status--info" v-if="row.status === 1 && row.canEdit">已下架</span>
          </template>
        </el-table-column>
        <el-table-column label="积分" prop="integralCost" />
        <el-table-column label="现金(元)" prop="cashCost" />
        <el-table-column label="库存" prop="sortCost" sortable="custom">
          <template slot-scope="{ row }">
            {{ row.virtualStock }}
          </template>
        </el-table-column>
        <template slot="empty">
          <div class="no-data-wrap">
            <div class="no-data-icon">
              <img src="../../static/img/no-data_icon.png">
            </div>
            <p>暂无数据</p>
          </div>
        </template>
      </el-table>
      <div class="pagination-conteiner" v-if="tableData.length > 0">
        <div class="pagination">
          <!-- <el-pagination v-if="total != 0" small @current-change="getInfo('1')" hide-on-single-page layout="prev, pager, next" :total="total"></el-pagination> -->
          <el-pagination
            small
            @current-change="changeCurrent"
            hide-on-single-page
            :page-size="5"
            layout="prev, pager, next"
            :total="total"
          />
        </div>
      </div>
      <div style="margin-top: 20px;text-align:right">
        <el-button type="default" @click="cancelSubmit">
          取消
        </el-button>
        <el-button type="primary" @click="confirmSelect">
          确认
        </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import qs from 'qs';
import request from '../service/request.js';
import copy from '../utils/clone.js';
import getInputVal from '../utils/common.js';
export default {
  props: {
    selectListMore: {
      type: Object,
      default () {
        return {};
      },
    },
  },
  data () {
    return {
      getTimeAll: getInputVal.formatDate,
      loading: false,
      type: 0, // 礼品或优惠券
      shelf: '', // 上下架状态
      query: {
        sortColumn: '',
        sortType: '',
        currentPage: 1,
        pageSize: 5,
        giftName: '',
        stockStatus: 1,
      },
      giftType: '', // 商品分类
      stockStatus: '', // 礼品库存状态
      tableData: [],
      selectArr: [], // 全选数据
      selectArr2: [],
      selectArr3: [],
      val: [],
      total: 999,
      dataLength: 0,
      valCopy: '',
      valCopy2: '',
    };
  },
  created () {
    this.dialogVisible = true;
    this.getInfo();
    if (this.selectListMore.length > 0) {
      this.selectArr2 = copy(this.selectListMore);
      this.dataLength = this.selectArr2.length;
      this.requestData();
    }
  },
  methods: {
    changeCurrent (value) {
      if (value) {
        this.query.currentPage = value;
      }
      this.getInfo();
      this.requestData();
    },
    getInfo () {
      let params;
      this.loading = true;
      if (!this.type) {
        params = {
          ...this.query,
          shelf: this.shelf ? this.shelf : -1, // 上下架状态
          giftType: this.giftType ? this.giftType : -1,
          showSelfFlag: 0,
        };
        request.post('/api-integral-mall/page-gift', qs.stringify(params)).then(res => {
          if (res.data.errorCode === 0) {
            if (res.data.result.rows) {
              this.tableData = res.data.result.rows;
              this.tableData.forEach(item => {
                item.type = 1;
              });
            } else {
              this.tableData = [];
            }
            this.total = res.data.result.total;
            this.loading = false;
          } else {
            this.$message.error(res.data.message);
            this.loading = false;
          }
        });
      } else {
        params = {
          ...this.query,
          shelf: this.shelf ? this.shelf : -1, // 上下架状态
        };
        request.post('/api-integral-mall/page-cards', qs.stringify(params)).then(res => {
          if (res.data.errorCode === 0) {
            if (res.data.result.rows) {
              this.tableData = res.data.result.rows;
              this.tableData.forEach(item => {
                item.type = 0;
              });
            } else {
              this.tableData = [];
            }
            this.total = res.data.result.total;
            this.loading = false;
          } else {
            this.$message.error(res.data.message);
            this.loading = false;
          }
        });
      }
    },
    changeType () {
      this.giftType = '';
      this.query.currentPage = 1;
      this.getInfo();
      if (this.selectListMore.length > 0) {
        this.selectArr2 = copy(this.selectListMore);
        this.requestData();
      }
    },
    changeGiftType () {
      this.query.currentPage = 1;
      this.getInfo();
      if (this.selectListMore.length > 0) {
        this.selectArr2 = copy(this.selectListMore);
        this.requestData();
      }
    },
    // 排序
    sortChange (value) {
      this.query.sortColumn = value.prop;
      if (value.order == 'ascending') {
        this.query.sortType = 'asc';
      } else if (value.order == 'descending') {
        this.query.sortType = 'desc';
      }
      this.getInfo();
    },
    // 确认
    confirmSelect () {
      if (this.selectArr2.length) {
        if (this.handleResult.length) {
          this.handleResult.forEach(item => {
            this.selectArr2.push(item);
          });
        }
        this.selectArr3 = copy(this.selectArr2);
      } else {
        this.selectArr3 = this.valCopy;
      }
      if (this.selectArr3.length > 20) {
        this.$message.error(`现已选择${this.selectArr3.length}个商品，最多选择20个商品`);
        this.selectArr2 = copy(this.selectListMore);
        this.selectArr3 = [];
      } else {
        this.selectArr = copy(this.selectArr3);
        this.$emit('getSelectList', this.selectArr);
        this.dialogVisible = false;
        setInterval(() => {
          this.$emit('closeGoodsSelect');
        }, 10);
      }
    },
    getRowKeys (row) {
      // 唯一值，一般都未id
      return row.integralMallProId;
    },
    requestData () {
      // 将已选的数据筛选出来在进行选中
      setTimeout(() => {
        this.selectArr2.forEach(item => {
          this.tableData.forEach((row, index) => {
            if (row.integralMallProId === item.integralMallProId) {
              // 这是默认选中上的
              this.$refs.maytable.toggleRowSelection(this.tableData[index], true);
            }
          });
        });
      }, 1000);
    },
    // 全选操作
    handleSelectAll (val) {
      this.valCopy = copy(val);
      this.valCopy2 = copy(val);
      if (this.selectArr2.length) {
        // let result = [];
        this.handleResult = [];
        for (let i = 0; i < this.valCopy2.length; i++) {
          const obj = this.valCopy2[i];
          const num = obj.integralMallProId;
          let isExist = false;
          for (let j = 0; j < this.selectArr2.length; j++) {
            const aj = this.selectArr2[j];
            const n = aj.integralMallProId;
            if (n == num) {
              isExist = true;
              break;
            }
          }
          if (!isExist) {
            // result.push(obj);
            this.handleResult.push(obj);
          }
        }
      }
    },
    handleSelectSingle (val) {
      this.$refs.maytable.toggleRowSelection(val);
    },
    cancelSubmit () {
      this.dialogVisible = false;
      setInterval(() => {
        this.$emit('closeGoodsSelect');
      }, 10);
    },
  },
};
</script>
<style scoped>

.gift-info img {
  width: 48px;
  height: 48px;
  background: #ffffff;
  border: 1px solid #dcdfe6;
  margin-right: 10px;
  padding: 6px;
  /* border-radius: 4px;
  padding: 4px;
  border: 1px solid #dcdfe6; */
}
.info-name {
  display: inline-block;
  vertical-align: top;
  width: 60%;
}
.pro-ellipsis {
  color: #606266;
  height: 22px;
  line-height: 22px;
  /* width: 230px; */
  font-size: 14px;
}
.category-ellipsis {
  color: #909399;
  font-size: 12px;
  line-height: 17px;
  margin-top: 6px;
}
</style>
