<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="form.ruleTitle"
              placeholder="请输入上架规则名称"
              prefix-icon="el-icon-search"
              clearable
              class="w-260"
              @keyup.enter.native="getList"
              @clear="getList"
            />
            <el-select
              v-model="form.memberType"
              placeholder="类型"
              clearable
              class="w-140"
              @change="getList"
            >
              <el-option
                v-for="item in selectOption"
                :label="item.label"
                :value="item.value"
                :key="item.label"
              />
            </el-select>
            <el-checkbox
              v-model="form.showSelfFlag"
              label="仅看本人"
              border
              :true-label="1"
              :false-label="0"
              @change="getList"
            />
          </div>

          <el-button
            type="primary"
            size="small"
            @click="$router.push('/addRule')"
            v-if="$getButtonLimit($buttonCode.ruleListAdd)"
            :limit-code="$buttonCode.ruleListAdd"
          >
            新建上架规则
          </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="memberType"
            label="类型"
          >
            <template slot-scope="{row}">
              {{ row.memberType | filterMemberType }}
            </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,'查看')"
                v-show="row.relationCount&&row.relationCount!=0"
              >
                查看/移除
              </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 prop="creatorName" label="创建人" />
          <el-table-column
            label="操作"
            fixed="right"
            width="220px"
          >
            <template slot-scope="{row}">
              <el-button
                type="text"
                @click="relatingDetail(row.integralMallProRuleId,'选择')"
                v-if="$getButtonLimit($buttonCode.ruleListRelate)"
                :limit-code="$buttonCode.ruleListRelate"
              >
                关联商品
              </el-button>
              <el-button
                type="text"
                @click="$router.push('/editRule/' + row.integralMallProRuleId)"
                v-if="$getButtonLimit($buttonCode.ruleListEdit)"
                :limit-code="$buttonCode.ruleListEdit"
              >
                编辑
              </el-button>
              <el-button
                type="text"
                @click="$router.push('/copyRule/' + row.integralMallProRuleId)"
                v-if="$getButtonLimit($buttonCode.ruleListCopy)"
                :limit-code="$buttonCode.ruleListCopy"
              >
                复制
              </el-button>
              <el-dropdown
                v-if="$getButtonLimit($buttonCode.ruleListDel)"
                style="margin-left:20px;"
                placement="bottom-start"
                @command="command => handleCommand(command, row)"
              >
                <span class="el-dropdown-link" style="color:#1890ff;cursor: pointer;"> <i class="el-icon-more" /> </span>
                <el-dropdown-menu slot="dropdown" style="width:110px;">
                  <el-dropdown-item
                    command="1"
                    v-if="$getButtonLimit($buttonCode.ruleListDel)"
                    :limit-code="$buttonCode.ruleListDel"
                  >
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
                <!-- <el-button
                  type="text"
                  @click="delRelating(row)"
                  v-if="$getButtonLimit($buttonCode.ruleListDel)"
                  :limit-code="$buttonCode.ruleListDel"
                >
                  删除
                </el-button> -->
              </el-dropdown>
            </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="form.currentPage"
              :page-size.sync="form.pageSize"
              @current-change="getList"
              :total="totalCount"
            />
          </div>
        </div>
        <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-show="type=='查看'&&$getButtonLimit($buttonCode.ruleListDelGoods)"
                :disabled="!multipleSelection.length"
                slot="reference"
                :limit-code="$buttonCode.ruleListDelGoods"
              >
                批量移除
              </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="relateCount"
              />
            </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) {
      let str = '';
      switch (val) {
        case 1:
          str = '优惠券';
          break;
        case 2:
          str = '优惠券';
          break;
        case 3:
          str = '礼品';
          break;
      }
      return str;
    },
    filterMemberType (val) {
      let str = '';
      switch (val) {
        case 1:
          str = '全部客户';
          break;
        case 3:
          str = '人群筛选';
          break;
        case 4:
          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: '',
      },
      form: {
        ruleTitle: '',
        memberType: '',
        showSelfFlag: 0,
        currentPage: 1,
        pageSize: 20,
      },
      relateCount: '',
      totalCount: '',
      integralMallProRuleId: '',
      defaultImg: '../../../../static/img/pic_default.png',
    };
  },
  computed: {
    selectOption () {
      let option = [
        { label: '全部客户', value: 1 },
        { label: '人群筛选', value: 3 },
        { label: '门店筛选', value: 4 },
      ];
      if (this.$store.state.product.ruleMemberFilterClose == 1) {
        option = option.filter(item => item.label != '人群筛选' && item.label != '全部客户');
      }
      return option;
    },
  },
  mounted () {
    this.getList();
  },
  methods: {
    handleCommand (command, row) {
      if (command == 1) {
        this.delRelating(row);
      }
    },
    getList () {
      this.loading = true;
      request.get('/api-integral-mall/page-rule', { params: this.form }).then(res => {
        console.log(res);
        this.tableDate = res.data.result.result || [];
        this.totalCount = res.data.result.totalCount;
      }).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 (row) {
      if (row.relationCount && row.relationCount != 0) {
        this.$message.error(`当前规则关联了${row.relationCount}款商品，无法删除`);
        return;
      }
      this.$confirm('删除后，该上架规则将无法被引用，是否确认删除？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.loading = true;
          request.post('/api-integral-mall/del-rule', { integralMallProRuleId: row.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.relateCount = 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>
