<template>
  <div class="mall-section-container">
    <div class="mall-content-section">
      <div class="mall-content-title">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '' }">
            <a href="/report/#/memberSummary">首页</a>
          </el-breadcrumb-item>
          <el-breadcrumb-item>积分商城</el-breadcrumb-item>
          <el-breadcrumb-item>商品</el-breadcrumb-item>
          <el-breadcrumb-item>上架规则</el-breadcrumb-item>
        </el-breadcrumb>
        <h3>
          <span>上架规则</span>
        </h3>
      </div>
      <div class="section">
        <div class="search-wrap">
          <div class="table-page-search-wrapper">
            <el-input
              v-model="ruleTitle"
              placeholder="请输入上架规则名称"
              prefix-icon="el-icon-search"
              clearable
              class="w-260"
              @keyup.enter.native="getList"
              @clear="getList"
            />
          </div>

          <el-button
            type="primary"
            size="small"
            :disabled="tableDate.length>=20"
            @click="$router.push('/addRule')"
          >
            新建上架规则({{ tableDate.length }}/20)
          </el-button>
        </div>
        <el-table
          ref="table"
          :data="tableDate"
          v-loading="loading"
          style="width: 100%"
        >
          <el-table-column
            prop="ruleTitle"
            min-width="130px"
            label="上架规则"
          >
            <template slot-scope="{row}">
              <div>
                <div class="title">
                  {{ row.ruleTitle }}
                </div>
                <div
                  style="font-size: 12px;color: rgb(144, 147, 153);"
                >
                  {{ row.ruleExplanation }}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="relationCount"
            label="已关联商品"
          >
            <template slot-scope="{row}">
              <span style="margin-right:20px">
                {{ row.relationCount }}
              </span>
              <el-button
                type="text"
                @click="relatingDetail(row.integralMallProRuleId,'查看')"
              >
                查看
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="创建时间">
            <template slot-scope="{row}">
              <p>{{ getTime(row.createTime) }}</p>
              <p>{{ getSeconds(row.createTime) }}</p>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
          >
            <template slot-scope="{row}">
              <el-button
                type="text"
                @click="relatingDetail(row.integralMallProRuleId,'选择')"
              >
                关联商品
              </el-button>
              <el-button
                type="text"
                @click="$router.push('/editRule/' + row.integralMallProRuleId)"
              >
                编辑
              </el-button>
              <el-button
                type="text"
                @click="$router.push('/copyRule/' + row.integralMallProRuleId)"
              >
                复制
              </el-button>
              <el-button
                type="text"
                @click="delRelating(row.integralMallProRuleId)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-dialog
          :title="`${type}关联商品`"
          :visible.sync="dialogTableVisible"
          width="850px"
          :before-close="cancel"
        >
          <div :class="['infoTips',type=='查看'?'infoTips_waring':'']">
            <i :class="['el-icon-info','infoTipsIcon',type=='查看'?'infoTips_waring':'']" />
            <div class="infoTipsContent">
              {{ type=='查看'?'从规则中移除商品后，上架规则不再作用于商品，商品将不能在会员小程序-积分商城上展示，请谨慎操作！':'选中已关联上架规则的商品，则规则被更新' }}
              <br>
            </div>
          </div>
          <div class="search-wrap">
            <div class="table-page-search-wrapper">
              <el-select
                v-model="relateForm.proType"
                clearable
                class="w-160"
                placeholder="所有商品类型"
                @change="searchGoods"
              >
                <el-option label="优惠券" :value="1" />
                <el-option label="礼品" :value="3" />
              </el-select>
              <el-select
                v-if="type=='选择'"
                v-model="relateForm.ruleRelationFlag"
                clearable
                placeholder="是否已关联上架规则"
                class="w-180"
                @change="searchGoods"
              >
                <el-option label="已关联上架规则" :value="1" />
                <el-option label="未关联上架规则" :value="0" />
              </el-select>
              <el-input
                placeholder="请输入礼品名称/礼品编码"
                v-model="relateForm.search"
                clearable
                size="small"
                class="w-260"
                @clear="searchGoods"
                @keyup.enter.native="searchGoods"
              />
            </div>
            <el-popconfirm
              title="确认删除吗？"
              @confirm="multipleDel"
              :loading="btnLoading"
            >
              <el-button
                type="primary"
                size="small"
                v-if="type=='查看'"
                :disabled="!multipleSelection.length"
                slot="reference"
              >
                批量移除
              </el-button>
            </el-popconfirm>
            <el-button
              type="primary"
              size="small"
              :loading="btnLoading"
              @click="submit"
              :disabled="!multipleSelection.length"
              v-if="type=='选择'"
            >
              批量添加
            </el-button>
          </div>
          <el-table
            :data="relatingGoodsTable"
            v-loading="loading"
            @selection-change="handleSelectionChange"
            ref="relatingGoodsTable"
            @row-click="onRowClick"
          >
            <el-table-column
              type="selection"
              width="55"
            />
            <el-table-column property="date" label="商品信息" min-width="160">
              <template slot-scope="{row}">
                <div class="img-text">
                  <img :src="row.mainImageUrl||defaultImg" alt="" v-if="row.proType==3">
                  <div v-if="row.proType==1||row.proType==2">
                    <img v-if="row.mainImageUrl" :src="row.mainImageUrl" 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>
                    <img v-if="row.cardType === 2 && !row.mainImageUrl" src="../../../../static/img/quan02.png" alt>
                  </div>
                  <div class="text">
                    <p class="goods-descript">
                      {{ row.proName }}
                    </p>
                    <p class="goods-code">
                      {{ row.proCode }}
                    </p>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column property="proType" label="商品类型" width="100">
              <template slot-scope="{row}">
                {{ row.proType|filterProType }}
              </template>
            </el-table-column>
            <el-table-column property="costValue" label="成本（元）" width="100" />
            <el-table-column property="virtualStock" label="当前库存" width="100" />
            <el-table-column property="ruleTitle" label="是否已关联规则" min-width="120">
              <template slot-scope="{row}">
                <p class="goods-descript">
                  {{ row.ruleTitle?row.ruleTitle:'否' }}
                </p>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-conteiner" style="padding:10px 0 0 0;">
            <div class="pagination">
              <el-pagination
                layout="prev, pager, next"
                :current-page.sync="relateForm.currentPage"
                :page-size.sync="relateForm.pageSize"
                @current-change="getRelatingGoodsTable"
                :total="totalCount"
              />
            </div>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button size="small" @click="cancel">取消</el-button>

          </span>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import request from '@/service/request.js';
import getInputVal from '@/utils/common.js';

export default {
  filters: {
    filterProType (val) {
      console.log(val);
      let str = '';
      switch (val) {
        case 1:
          str = '优惠券';
          break;
        case 2:
          str = '优惠券';
          break;
        case 3:
          str = '礼品';
          break;
      }
      return str;
    },
  },

  data () {
    return {
      getTime: getInputVal.getTime,
      getSeconds: getInputVal.getSeconds,
      loading: false,
      btnLoading: false,
      tableDate: [
      ],
      relatingGoodsTable: [
      ],
      multipleSelection: [],
      dialogTableVisible: false,
      type: '选择',
      relateForm: {
        search: '',
        proType: '',
        pageSize: 5,
        currentPage: 1,
        ruleRelationFlag: '',
      },
      ruleTitle: '',
      totalCount: '',
      integralMallProRuleId: '',
      defaultImg: '../../../../static/img/pic_default.png',
    };
  },
  mounted () {
    this.getList();
  },
  methods: {
    getList () {
      this.loading = true;
      request.get('/api-integral-mall/list-rule', { params: { ruleTitle: this.ruleTitle } }).then(res => {
        console.log(res.data.result);

        this.tableDate = res.data.result || [];
      }).finally(_ => {
        this.loading = false;
      });
    },
    relatingDetail (integralMallProRuleId, type) {
      this.dialogTableVisible = true;
      this.type = type;
      this.relateForm.currentPage = 1;
      if (type == '查看') {
        this.relateForm.integralMallProRuleId = integralMallProRuleId;
      } else {
        delete this.relateForm.integralMallProRuleId;
      }
      this.integralMallProRuleId = integralMallProRuleId;
      this.getRelatingGoodsTable();
    },
    delRelating (integralMallProRuleId) {
      this.$confirm('上架规则删除后，无法被商品关联使用，是否确认删除？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.loading = true;
          request.post('/api-integral-mall/del-rule', { integralMallProRuleId }).then(res => {
            this.$message.success('删除成功');
            this.getList();
          }).finally(_ => {
            this.loading = false;
          });
        });
    },
    handleSelectionChange (val) {
      this.multipleSelection = val;
    },
    multipleDel () {
      this.btnLoading = true;
      const data = {};
      data.integralMallProIdList = this.multipleSelection.map(item => item.integralMallProId);
      data.integralMallProRuleId = this.integralMallProRuleId;
      request.post('/api-integral-mall/del-rule-pro', data).then(res => {
        this.$message.success('删除成功');
        this.getRelatingGoodsTable();
      }).finally(_ => {
        this.btnLoading = false;
      });
    },
    onRowClick (row) {
      this.$refs.relatingGoodsTable.toggleRowSelection(row);
    },
    searchGoods () {
      this.relateForm.currentPage = 1;
      this.getRelatingGoodsTable();
    },
    cancel () {
      this.dialogTableVisible = false;
      this.relateForm = {
        search: '',
        proType: '',
        pageSize: 5,
        currentPage: 1,
        ruleRelationFlag: '',
      };
      this.getList();
    },
    getRelatingGoodsTable () {
      this.loading = true;
      const params = this.relateForm;
      request.get('/api-integral-mall/page-rule-pro', { params }).then(res => {
        this.relatingGoodsTable = res.data.result.result || [];
        this.totalCount = res.data.result.totalCount;
      }).finally(_ => {
        this.loading = false;
      });
    },
    submit () {
      this.btnLoading = true;
      const data = {};
      data.integralMallProIdList = this.multipleSelection.map(item => item.integralMallProId);
      data.integralMallProRuleId = this.integralMallProRuleId;
      request.post('/api-integral-mall/add-rule-pro', data).then(res => {
        this.$message.success('添加成功');
        this.getRelatingGoodsTable();
      }).finally(_ => {
        this.btnLoading = false;
      });
    },

  },
};
</script>

<style lang="less" scoped>
.img-text{
  height: 60px;
  align-items: center;
  display: flex;
  img{
  width: 60px;
  height: 60px;
  border-radius: 5px;
}
.text {
    margin-left: 10px;
    font-size: 12px;
    line-height: 20px;
    .goods-descript {
      width:180px;
      color: #303133;
      font-size: 14px;
      overflow:hidden;
      text-overflow:ellipsis;
      white-space:nowrap;
    }
    .goods-code {
        font-size: 12px;
        color: #909399;
    }

}

}
</style>
