<template>
<section class="dm-wrap">
    <div class="pb22 clearfix">
      <el-input v-model="listParams.giftName" class="w300" placeholder="请输入礼品名称" clearable @change="getPageGiftList"><i slot="prefix" class="el-input__icon el-icon-search"></i></el-input>
      <el-button class="fr" type="primary"  @click="$router.push('/gift/info')">新增礼品</el-button>
    </div>
    <div class="filter--box">
      <el-select class="vertical-middle w150 pl10" v-model="listParams.category" placeholder="选择分类" @change="getPageGiftList">
        <el-option v-for="v in categoryOptions" :key="v.integralMallCategoryId" :label="v.categoryName" :value="v.integralMallCategoryId"></el-option>
      </el-select>
      <el-select class="vertical-middle w150" v-model="listParams.changeType" placeholder="选择兑换方式" @change="getPageGiftList">
        <el-option v-for="v in changeTypeOptions" :key="v.value" :label="v.label" :value="v.value"></el-option>
      </el-select>
      <el-select class="vertical-middle w150" v-model="listParams.releaseType" placeholder="选择兑换状态" @change="getPageGiftList">
        <el-option v-for="v in releaseTypeOptions" :key="v.value" :label="v.label" :value="v.value"></el-option>
      </el-select>
      <el-select class="vertical-middle w150" v-model="listParams.showStatus" placeholder="选择显示状态" @change="getPageGiftList">
        <el-option v-for="v in showStatusOptions" :key="v.value" :label="v.label" :value="v.value"></el-option>
      </el-select>
      <el-checkbox class="vertical-middle" size="small" border  :true-label="1" :false-label="0" v-model="listParams.proHot" @change="getPageGiftList">只看热门推荐</el-checkbox>
    </div>
  <el-table tooltipEffect="light" :data="tableList" style="width: 100%" v-loading="loading" @sort-change="sortList">
    <el-table-column :show-overflow-tooltip="false" width="90" align="left"  prop="proHot" fixed="left" label="热门推荐">
      <template slot-scope="scope">
        <el-switch
          v-model="scope.row.proHot"
          :active-value="1"
          :inactive-value="0" @change="changeHotFun(scope.row)">
        </el-switch>
      </template>
    </el-table-column>
    <el-table-column label="礼品信息" align="left" prop="proName" min-width="260">
      <template slot-scope="scope">
          <div class="ellipsis-100" >
              <img class="vertical-middle table__avatar--gift" :src="scope.row.mainImageUrl || defaultAvatar" width="60" height="60" />
              <div class="inline-block vertical-middle">
                  <p class="table-name--ellipsis">{{scope.row.proName || '--'}}</p>
                  <div v-if="scope.row.giftCategoryName">
                    <el-tooltip class="item" effect="dark" :content="scope.row.giftCategoryName" placement="bottom">
                      <p class="fz13 gray table-name--ellipsis">{{scope.row.giftCategoryName}}</p>
                    </el-tooltip>
                  </div>
                  <p v-else>--</p>
                  <!-- <p class="fz13 gray table-name--ellipsis">{{scope.row.giftCategoryName || '--'}}</p> -->
              </div>
          </div>
      </template>
    </el-table-column>
    <el-table-column label="积分费用" align="left" prop="integralCost">
      <template slot-scope="scope">
        <updateCount :model="scope.row" theType="integralCost" typeName="积分" @refresh="getPageGiftList"></updateCount>
      </template>
    </el-table-column>
    <el-table-column label="现金费用" align="left" prop="cashCost">
      <template slot-scope="scope">
          <updateCount :model="scope.row" :precision="2" theType="cashCost" typeName="元" @refresh="getPageGiftList"></updateCount>
      </template>
    </el-table-column>
    <el-table-column label="库存" align="left" prop="sortCost"  sortable="custom">
      <template slot-scope="scope">
          <updateCount :model="scope.row" theType="virtualStock" @refresh="getPageGiftList"></updateCount>
      </template>
    </el-table-column>
    <el-table-column label="兑换次数" align="left" prop="sortTimes" sortable="custom">
      <template slot-scope="scope">
        <span v-if="scope.row.changeType == 1" @click="$router.push('/gift/wxexchange/'+scope.row.integralMallProId)" class="blue">{{scope.row.allExchangeNumber}}</span>
        <span v-else @click="$router.push('/gift/exchange/'+scope.row.integralMallProId)" class="blue">{{scope.row.allExchangeNumber}}</span>
      </template>
    </el-table-column>
    <el-table-column label="兑换方式" align="left" prop="changeType">
      <template slot-scope="scope" >
        <span v-if="scope.row.changeType == 1">微信兑换</span>
        <span v-if="scope.row.changeType == 2">快递发货</span>
        <span v-if="scope.row.changeType == 3">在线发货</span>
      </template>
    </el-table-column>
    <el-table-column label="兑换状态" align="left" prop="status" min-width="100px">
      <template slot-scope="scope" >
        <span v-html="renderStatus(scope.row).html"></span>
      </template>
    </el-table-column>
    <el-table-column label="显示状态" align="center" prop="proShowStatus">
      <template slot-scope="scope" >
        {{renderShowStatus(scope.row)}}
      </template>
    </el-table-column>
    <el-table-column label="操作" align="left" fixed="right" min-width="160">
        <template slot-scope="scope">
          <el-button type="text" @click="getLink(scope.row.integralMallProId)">推广</el-button>
          <el-button type="text" @click="$router.push('/gift/info/'+scope.row.integralMallProId)">编辑</el-button>
          <dm-delete @confirm="delData(scope.row)" tips="是否删除该优惠券?">
            <el-button type="text">删除</el-button>
          </dm-delete>
        </template>
    </el-table-column>
  </el-table>
  <el-pagination v-show="tableList.length" background class="dm-pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listParams.currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="listParams.pageSize" layout="total, sizes, prev, pager, next" :total="total"></el-pagination>
  <!-- 推广 -->
  <eqCodeDialog :modalData="modalData"></eqCodeDialog>
</section>
</template>
<script>
import { getPageGiftList, getCategoryList, deleteProService ,setHotStatusService} from '@/service/api/mallApi.js';
import updateCount from '../common/update-count';
import {formateDateTimeByType,format} from '@/utils/index.js';
import eqCodeDialog from '../common/eqCode.vue'
import request from '../../../api/request.js'
export default {
    name: 'gift-list',
    components: {
      updateCount,
      eqCodeDialog
    },
    data () {
      return {
        defaultAvatar:require('../../../assets/img/head_default.png'),
        loading:false,
        tableList:[],
        listParams:{
            currentPage:1,
            pageSize:20,
            category:'',
            changeType:-1,
            releaseType:-1,
            showStatus:-1,
            proHot:'-1',
            giftName:'',
            sortType:'',
            sortColumn:'',
        },
        total:0,
        categoryOptions:[],
        releaseTypeOptions:[{label:'所有兑换状态',value:-1},{label:'兑换',value:1},{label:'不可兑换',value:0}],
        changeTypeOptions:[{label:'所有兑换方式',value:-1},{label:'微信兑换',value:1},{label:'快递发货',value:2},{label:'在线发货',value:3}],
        showStatusOptions:[{label:'所有显示状态',value:-1},{label:'显示',value:1},{label:'不显示',value:2}],
        modalData:{
          show:false,
          imgUrl:'',
          loading:false
        },
      }
    },
    created() {
      this.$store.commit('mutations_breadcrumb',[{name:'积分商城'},{name:'礼品',path:''}]);
      this.getPageGiftList();
      this.getCategoryList();
    },
    methods: {
      // 获取分类列表
      async getCategoryList() {
        let res = await getCategoryList();
        if (res.errorCode === 0) {
          this.categoryOptions = res.result || [];
          this.categoryOptions.unshift({categoryName:'所有分类',integralMallCategoryId:''})
        }
      },
      renderStatus(item) {
        var _releaseType = item.releaseType ;
				//上架日期
				var _limit_time_begin = item.limitTimeBegin ;
				//库存
				var _virtual_stock = item.virtualStock ;
				//兑换日期类型1:全部 2:固定日期 3:每月 4:每周
				// 显示状态的优先级：已过期＞无库存＞定时发布＞未在兑换时间
        var _exchange_date_type = item.exchangeDateType ;
        var dhzt_show_html ='<span class="dm-status--primary">正常</span>'
				var dhzt_show =  '正常';
				//判断是否在兑换日期内 - 未在兑换时间
        if(_virtual_stock<=0) {
          dhzt_show_html =  '<span class="dm-status--error">无库存</span>';
          dhzt_show = "无库存" ;
        }
				if(_exchange_date_type==2) {
					if(!(new Date().getTime() >= item.exchangeFixDateBegin && new Date().getTime() <= (item.exchangeFixDateEnd + (1000*60*60*24) ))) {
            dhzt_show_html =  '<span class="dm-status--warning">未在兑换时间</span>';
				    dhzt_show =  '未在兑换时间';
            return {
              text:dhzt_show,
              html:dhzt_show_html
            };
					}
				}
				if(_exchange_date_type==3) {
          dhzt_show_html =  '<span class="dm-status--warning">未在兑换时间</span>';
          dhzt_show =  '未在兑换时间';
					var _exchange_date_day = item.exchangeDateDay ;
					var day = new Date().getDate() ;
					var _arr = _exchange_date_day.split(",") ;
					_arr.map(v => {
						if(day == parseInt(v)) {
              dhzt_show_html = '<span class="dm-status--primary">正常</span>' ;
				      dhzt_show =  '正常';
						}
					})
				}

				if(_exchange_date_type==4) {
					var _exchange_date_week = item.exchangeDateWeek ;
					var week = new Date().getDay() ;
					if(week == 0) {
						week =7 ;
					}
					if(_exchange_date_week.indexOf(week) == -1) {
            dhzt_show_html =  '<span class="dm-status--warning">未在兑换时间</span>';
            dhzt_show =  '未在兑换时间';
					}
				}

				if(item.exchangeTimeType == 2 && item.exchangeTimeList && (dhzt_show == '无库存'||dhzt_show == '正常')) {
					dhzt_show_html =  '<span class="dm-status--warning">未在兑换时间</span>';
          dhzt_show =  '未在兑换时间';
					for(var k=0;k<item.exchangeTimeList.length;k++) {
						var _o = item.exchangeTimeList[k] ;
						var start = _o.exchangeTimeBeginNumber ;
						var end  = _o.exchangeTimeEndNumber ;
            var _now = format(new Date(),'hhmm') ;
						if(_now >= start && _now <= end) {
              dhzt_show_html =  '<span class="dm-status--primary">正常</span>';
              dhzt_show =  '正常';
							break ;
 						}
					}
				}

				//定时发布
				if(_releaseType == 2 && item.status==2 && new Date().getTime() < _limit_time_begin) {
          dhzt_show_html =  `<span class="dm-status--success">定时发布<br/>${formateDateTimeByType(new Date(_limit_time_begin),"yyyy-MM-dd-hh-mm-ss")}</span>`;
          dhzt_show =  '定时发布';
				}

				

				if(item.status==1) {
          dhzt_show_html = '<span class="dm-status--info">已下架</span>';
					dhzt_show = "已下架" ;
				}
        return {
          text:dhzt_show,
          html:dhzt_show_html
        };
      },
      renderShowStatus(item) {
        //商品显示状态 1:上架状态就显示 2:兑换状态下显示
        var dhzt_show =  this.renderStatus(item).text;
        var pro_show_status = item.proShowStatus ;
        var proShowStatus = "不显示" ;
        if(item.status==2) {
          if((item.releaseType==1 || (item.releaseType == 2 && new Date().getTime() >= (item.limitTimeBegin || 0)) ) && ( pro_show_status==1 || (pro_show_status==2 &&  (dhzt_show=="正常" || dhzt_show=='无库存'))) ) {
            proShowStatus = "显示" ;
          }
        }
        console.log('显示状态',proShowStatus)
        return proShowStatus;
      },

      // 列表的方法
      search() {
        this.listParams.currentPage = 1;
        this.getPageGiftList();
      },
      handleSizeChange(val) {
        this.listParams.pageSize = val;
        this.getPageGiftList();
      },
      handleCurrentChange(val) {
        this.listParams.currentPage = val;
        this.getPageGiftList();
      },
      async getPageGiftList() {
        this.loading = true;
        try {
          let res = await getPageGiftList(this.listParams);
          this.tableList = [];
          let result =  res.result.rows || [];
          result.map(v => {
            v.integralCostFlag = false;
            v.cashCostFlag = false;
            v.virtualStockFlag = false;
            v.allExchangeNumberFlag = false;
            this.tableList.push(v);
          })
          this.total = res.result.total;
        } catch(err) {
          this.$tips({type:'warning',message:'加载列表失败'});
        }
        this.loading = false;
      },
      // 删除
      delData(row) {
        deleteProService({proId:row.integralMallProId}).then(res => {
          if (res.errorCode === 0) {
            this.$tips({type: 'success',message: '删除成功!'});
            this.getPageGiftList();
          } else {
            this.$tips({type: 'error',message: '删除失败!'});
          }
        }).catch(err => {
          this.$tips({type: 'error',message: '删除失败!'});
        })
      },
      // 推广
      getLink(mallProId){
        this.modalData.loading=true
        let params={
          integralMallProId:mallProId,
          type:"gift"
        }
        this.modalData.show=true
        request.get('/api-integral-mall/get-qRCode',{params}).then(res => {
          if(res.data.errorCode===0){
            this.modalData.show=true
            this.modalData.pageUrl=res.data.result.page
            this.modalData.imgUrl=res.data.result.url
            this.modalData.loading=false
          }else{
             this.$message.error(res.data.message)
          }
        })  
      },
      // 热门推荐
      changeHotFun(row) {
        setHotStatusService({status:Number(row.proHot),integralMallProId:row.integralMallProId}).then(res => {
          if (res.errorCode === 0) {
            this.$tips({type: 'success',message: '设置成功!'});
          } else if (res.errorCode === 1){
            this.$tips({type: 'warning',message: '热门推荐礼品上限为20个,当前已超限制,请先取消其他礼品的推荐再来试试'});
          } else {
            this.$tips({type: 'error',message: '删除失败!'});
          }
          this.getPageGiftList();
        }).catch(err => {
          this.getPageGiftList();
          this.$tips({type: 'error',message: '删除失败!'});
        })
      },
      //列表 排序
      sortList(obj) {
        this.listParams.sortColumn =  obj.prop;
        this.listParams.sortType = obj.order ? (obj.order === 'descending' ? 'desc' : 'asc') : '';
        this.getPageGiftList();
      }
    }
}
</script>


