<template>
  <div class="attention-textAndImg-wrap">
    <el-dialog
      title="选择卡券"
      :visible.sync="dialogCard"
      width="800px"
      :before-close="handleCardClose"
      >
      <div>
        <div class="text-img-search clearfix">
          <span>选择卡券（共{{total}}条）</span>
          <div class="fl">
            <el-input
                placeholder="请输入内容"
                prefix-icon="el-icon-search"
                class="search-input"
                v-model="searchText"
                @keyup.native="(value) => toSearchInput(value)" clearable  @clear="clearInput">
            </el-input>
            <!-- <el-button class="search-btn" type="primary">查询</el-button> -->
            <p class="limit-text">领取限制 < 100的卡券不支持选择，系统已自动过滤</p>
          </div>
        </div>
        <div class="pic-list-box">
          <el-table
            ref="multipleTable"
            :data="cardData"
            class="card-table"
            tooltip-effect="dark"
            style="width: 100%"
            @row-click="handleCurrentChangeTable">
            <el-table-column label="" width="55">
              <template slot-scope="scope">
                <el-radio class="radio-style" :label="scope.row.coupCardId" v-model="radio" :disabled="scope.row.disabled">
                  &nbsp;
                </el-radio>
              </template>
            </el-table-column>

            <el-table-column
              label="卡券名称">
              <template slot-scope="scope">{{ scope.row.cardName }}</template>
            </el-table-column>
            <el-table-column
              prop="subName"
              label="备注名">
            </el-table-column>
            <el-table-column
              prop=""
              label="有效期"
              width="100">
              <template slot-scope="scope">
                <div v-if="scope.row.cardEffectiveMode == 0">{{scope.row.beginDate+'-'+ scope.row.endDate}}</div>
                <div v-if="scope.row.cardEffectiveMode == 1">领取{{scope.row.startDay +'-'+ scope.row.limitDay}}天后,可以使用</div>
              </template>
            </el-table-column>
            <el-table-column
              prop=""
              label="领取限制"
              width="100">
              <template slot-scope="scope">
                每人限制{{scope.row.cardLimit}}张
              </template>
            </el-table-column>
            <el-table-column
              prop=""
              label="适用门店"
              width="100">
              <template slot-scope="scope">
                <div v-if="scope.row.storeMode == 0">所有门店</div>
                <div v-if="scope.row.storeMode == 1">部分分组</div>
                <div v-if="scope.row.storeMode == 2">部分门店</div>
              </template>
            </el-table-column>
            <el-table-column
              prop="couponStock"
              label="库存"
              width="130">
            </el-table-column>
          </el-table>
          <div class="pagination" v-if="total>0">
            <el-pagination
              @size-change="cardSizeChange"
              @current-change="cardCurrentChange"
              :current-page="cardCurrentPage"
              small
              :page-size="cardPageSize"
              layout="prev, pager, next"
              :total="total">
            </el-pagination>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCardcancel">取 消</el-button>
        <el-button type="primary" @click="dialogCardConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  // import { getRequest } from './api';
  import qs from 'qs';
  export default {
    name: 'vue-gic-card',
    props: ['showCardDialog','projectName','cardLimit', 'cardType','disabledList'],
    data () {
      return {
        repProjectName: 'gic-web', // 项目名
        searchText: '',
        cardData: [],
        currentRow: null,
        radio: null,
        dialogCard: false,

        cardCurrentPage: 1,
        cardPageSize: 5,
        total: 0,
        cardLimitType: '',
        cardTypes: '',

        // 获取 location origin
        baseUrl: '',
      }
    },
    beforeMount() {
      var that = this
      var host = window.location.origin;
      console.log("当前host:",host)
      if (host.indexOf('localhost') != '-1') {
        that.baseUrl = 'http://gicdev.demogic.com';
      }else {
        that.baseUrl = host
      }
    },
    methods:{
      handleCurrentChangeTable(val) { // 当前格发生变化时触发
        var that = this
        console.log("table: ",val);
        if (!val.disabled) {
          that.radio = val.coupCardId;
          that.currentRow = val;
        }
      },

      // 页码变化
      cardSizeChange(val){    // 选择分页符
        console.log(`每页 ${val} 条`);
      },

      // 当前页变化
      cardCurrentChange(val) {
        console.log(`当前页: ${val}`);
        var that = this;
        that.cardCurrentPage = val;
        that.getCardList();
      },

      // 设置接收参数
      setNewData(cardFlag) {
        var that = this;
        that.dialogCard = cardFlag;
        console.log("弹框是否显示: ",cardFlag)
      },

      // 搜索输入
      toSearchInput: function(value) {
        var that = this;
        console.log("搜索值: ",that.searchText,value)
        // 搜索重置当前页 为 1
        that.cardCurrentPage = 1;
        that.getCardList();

      },
      // 清空输入
      clearInput: function(e) {
        var that = this;
        console.log(e,that.searchText);
        // 搜索重置当前页 为 1
        that.cardCurrentPage = 1;
        that.getCardList();

      },

      //  确认
      dialogCardConfirm() {
        var that = this;

        if (!that.currentRow||!Object.keys(that.currentRow).length||!Object.values(that.currentRow).length) {
          that.$message.error({
            duration: 1000,
            message: "请选择卡券"
          })
          return;
        }

        that.$emit('selectCard',that.currentRow)
        that.currentRow = {};
        that.radio = null;
      },

      handleCardClose() {
        var that = this;
        that.dialogCardcancel();
      },

      //  取消
      dialogCardcancel() {
        var that = this;
        that.$confirm('确认关闭?', '', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: ''
        }).then(() => {
          console.log("点击确认")
          that.currentRow = {};
          that.radio = null;
          that.$emit('selectCard')
        }).catch(() => {
           console.log("取消 取消关闭")
        });
      },

      // 获取卡券列表
      getCardList() {
        var that = this
        var para = {
          currentPage: that.cardCurrentPage,
          pageSize: that.cardPageSize,
          searchParam: that.searchText || '',
          requestProject: that.repProjectName,
          cardLimitType: that.cardLimitType,
          cardTypes: that.cardTypes,
        }
        that.axios.post(that.baseUrl+'/api-plug/get-coupon-list',qs.stringify(para))
        .then((res) => {
          console.log(res,res.data,res.data.errorCode)
          var resData = res.data
          if (resData.errorCode == 0) {
            if (!!resData.result) {
                if (!!resData.result.result) {
                  resData.result.result.forEach(function(ele,index){
                    if (!!ele.beginDate) {
                      ele.beginDate = that.formatDate(ele.beginDate,'.')
                    }
                    if (!!ele.endDate) {
                      ele.endDate = that.formatDate(ele.endDate,'.')
                    }
                    console.log(ele)
                    ele.disabled = that.disabledList.indexOf(ele.coupCardId) >= 0;
                  })
                  that.cardData = resData.result.result
                }
              that.total =  resData.result.totalCount
            }

            return;
          }
          that.$message.error({
            duration: 1000,
            message: resData.message
          })

        })
        .catch(function (error) {
          console.log(error);
          // that.toLogin()
          that.$message.error({
            duration: 1000,
            message: error.message
          })
        });
      },

      formatDate(time,flag) {
        var that = this
        //  (0-9)年月数字的显示
        function formatDig(num) {
          return num > 9 ? '' + num : '0' + num;
        }
        var myDate = new Date(time);
        let y = myDate.getFullYear();
        let m = myDate.getMonth()+1;
        let d = myDate.getDate();
        return y + flag + formatDig(m) + flag + formatDig(d) + flag
      }
    },
    watch: {
      showCardDialog(newData,oldData){
        this.setNewData(newData)
      },
      projectName(newData,oldData){
        this.repProjectName = newData || 'gic-web';
      },
      cardLimit(newData,oldData){
        this.cardLimitType = newData;
      },
      cardType(newData,oldData){
        this.cardTypes = newData;
      },
    },

    /* 接收数据 */
    mounted(){
      console.log("传递的参数对象:",this.showCardDialog)
      var that = this;

      // 项目名
      that.repProjectName = that.projectName || 'gic-web';

      that.cardLimitType = that.cardLimit;
      that.cardTypes = that.cardType;

      that.getCardList()


      that.setNewData(that.showCardDialog)
    }
  }
</script>

<style lang="scss" scoped>
  #wrap{
    background: #fff;
  }
  .search-input{
    width: 180px;
  }
  .attention-textAndImg-wrap /deep/{
    .text-img-search {
      margin: 10px 15px;
      font-size: 14px;
      color: #292929;
      height: 36px;
      line-height: 36px;
      > span{
        float: left;
        margin-right: 10px;
      }

      /deep/.search-input{
        width: 180px;
        .el-input__inner {
          height: 36px;
          line-height: 36px;
        }
      }
      .search-btn{
        margin-left: 4px;
      }
      .limit-text{
        color: #909399;
        font-size: 12px;
        line-height: 1;
        padding-top: 4px;
        display: inline-block;
        margin-left: 20px;
      }
    }
    .pic-list-box{
      .list-img{
        width: 80px;
        height: 80px;
        img{
          width: 100%;
          height: 100%;
        }
      }
      .card-table{
        position: relative;
        .radio-style{
         /* position: absolute;
          left: 27px;
          top: 15px;*/
        }
      }
    }

    .el-table thead tr, .el-table thead th {
        background: #f1f3f7;
    }
  }
  .pagination{
    text-align: right;
    margin-top: 20px;
  }
  .pic-list-box /deep/ .el-table__row{
    cursor: pointer;
  }
  .attention-textAndImg-wrap /deep/ .el-dialog__body{
    padding: 10px 20px;
  }


</style>
