<template>
   <div class="app-container calendar-list-container" v-loading.body="showLoadingBody">
    <div>
      <div class="filter-container" ref="filter-container">
        <el-form ref="queryForm" :inline="inline" :model="listQuery" label-width="50px">
          <el-row>
            <el-col :span="5">
              <el-form-item label="标题">
                <el-input v-model.number="listQuery.title" placeholder="请输入标题"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item>
                <el-select class="filter-item" v-model="listQuery.channel" placeholder="类型">
                  <el-option key="" label="全部" value=""> </el-option>
                  <el-option v-for="(item,index) in channelType" :key="index" :label="item.val" :value="item.id"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>
             <el-button class="filter-item" type="primary" v-waves icon="search" @click="handleFilter">搜索</el-button>
             <el-button class="filter-item" type="primary" @click="addCunpon" style="float: right;">+ 添加优惠券</el-button>
          </el-row>
        </el-form>
      </div>
      <el-table :key='tableKey' :data="list" border fit highlight-current-row style="width: 100%;">
        <el-table-column type="index" align="center" label="ID" width="100">
          <template scope="scope">
            <span>{{scope.row.id}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="优惠券标题">
          <template scope="scope">
            <span>{{scope.row.title}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="类型">
          <template scope="scope">
            <span v-if="scope.row.channel==0">全平台</span>
            <span v-if="scope.row.channel==1">租车</span>
            <span v-if="scope.row.channel==2">旅游</span>
            <span v-if="scope.row.channel==3">营地</span>
            <span v-if="scope.row.channel==4">会员</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="金额">
          <template scope="scope">
            <span>{{scope.row.usedAmount}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="已领取">
          <template scope="scope">
            <span>{{scope.row.takeCount}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="已使用">
          <template scope="scope">
            <span>{{scope.row.usedCount}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="创建时间">
          <template scope="scope">
            <span>{{scope.row.crtTimeStr}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作"  width="150" fixed="right">
          <template scope="scope">
            <el-button size="small" class="el-button el-button--text el-button--small" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button class="el-button el-button--text el-button--small" style="color:red;" size="small" @click="deleteHandler(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-show="!listLoading" class="pagination-container">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                       :current-page.sync="listQuery.page" :page-sizes="[10,20,30,40,50]" :page-size="listQuery.limit"
                       layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
      </div>
    </div>

    <!-- 优惠券编辑 -->
	<el-dialog :title="modalTitle" :visible.sync="editDialogVisible">
		<el-form :model="formdata" :rules="rules" ref="form" label-width="110px">
            <div style="font-weight: bold;">基础设置</div>
            <hr style="background-color:#e5e5e5;height:1px;border:none;margin:10px 0">
			      <el-row>
                <el-col :span="12">
                    <el-form-item label="优惠券标题" prop="title">
                        <el-input v-model="formdata.title" placeholder="请输入优惠券标题" :disabled="isUpdate"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="适用人群">
                        <el-radio-group v-model="formdata.user_type_name" size="medium">
                          <el-radio-button label="普通用户" :disabled="formdata.user_type_name=='会员用户'&&isUpdate"></el-radio-button>
                          <el-radio-button label="会员用户" :disabled="formdata.user_type_name=='普通用户'&&isUpdate"></el-radio-button>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="优惠金额">
                        <el-input v-model="formdata.usedAmount" placeholder="请输入优惠金额" :disabled="isUpdate"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="优惠方式">
                        <el-select class="filter-item" v-model="formdata.type" placeholder="请选择" style="width:110px" :disabled="isUpdate">
                            <el-option v-for="(item,index) in cunponType " :key="index" :label="item.val"
                                    :value="item.id" :disabled="item.id==2"></el-option>
                        </el-select>
                        <span v-if="formdata.type==1">满</span>
                        <el-input v-model="formdata.withAmount" placeholder="请输入金额" style="width:100px" v-if="formdata.type==1" :disabled="isUpdate"></el-input>
                        <span v-if="formdata.type==1">可用</span>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="有效期">
                        <el-radio-group v-model="formdata.valid_type_name" size="medium">
                          <el-radio-button label="绝对时效" :disabled="formdata.valid_type_name=='相对时效'&&isUpdate"></el-radio-button>
                          <el-radio-button label="相对时效" :disabled="formdata.valid_type_name=='绝对时效'&&isUpdate"></el-radio-button>
                          <el-radio-button label="永久时效" :disabled="formdata.valid_type_name=='永久时效'&&isUpdate"></el-radio-button>
                        </el-radio-group>
                        <div style="display:inline-block" v-show="formdata.valid_type_name=='绝对时效'">
                          <el-date-picker v-model="formdata.validStartTimeStr" type = "date" placeholder = "开始时间" :disabled="isUpdate" :picker-options="pickerOptionsStart"></el-date-picker>
                          <span> - </span>
                          <el-date-picker v-model="formdata.validEndTimeStr" type = "date" placeholder = "结束时间" :disabled="isUpdate" :picker-options="pickerOptionsEnd1"></el-date-picker>
                        </div>
                        <div style="display:inline-block" v-show="formdata.valid_type_name=='相对时效'">
                          <span>领取后</span>
                          <el-input v-model="formdata.validDays" placeholder="请输入金额" style="width:100px" :disabled="isUpdate" type="number"></el-input>
                          <span>天有效</span>
                        </div>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="是否可转赠">
                        <el-radio-group v-model="formdata.cangive" size="medium">
                          <el-radio-button label="是" disabled=""></el-radio-button>
                          <el-radio-button label="否" ></el-radio-button>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="跳转链接">
                        <el-input v-model="formdata.url" placeholder="请输入跳转链接"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
            <el-form-item label="优惠券图片" :style="{display:'block'}">
              <el-upload
                class="upload-demo"
                :headers="getHeaderWithToken"
                :action="BASE_API+'/api/universal/file/app/unauth/admin/upload'"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                list-type="picture">
                <img v-if="$utils.isString(formdata.icon) && !$utils.isEmpty(formdata.icon)" :src="formdata.icon"
                     style="width:300px;max-height: 100px;">
                <i v-else class="el-icon-plus avatar-uploader-icon"
                   style="lineHeight:100px;width:300px;height: 100px;border: 1px dashed #ccc;"></i>
              </el-upload>
            </el-form-item>
          </el-row>
          <div style="font-weight: bold;">高级设置</div>
           <hr style="background-color:#e5e5e5;height:1px;border:none;margin:10px 0">
           <el-row>
                <el-col :span="12">
                    <el-form-item label="优惠券类别" >
                        <el-select class="filter-item" v-model="formdata.used" placeholder="请选择" :disabled="isUpdate">
                            <el-option v-for="(item,index) in usedType " :key="index" :label="item.val"
                                    :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="适用范围" >
                        <el-select class="filter-item" v-model="formdata.channel" placeholder="请选择" :disabled="isUpdate">
                            <el-option v-for="(item,index) in channelType " :key="index" :label="item.val"
                                    :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="开始发放时间" >
                        <el-radio-group v-model="formdata.startTimeName" size="medium">
                          <el-radio-button label="不限"></el-radio-button>
                          <el-radio-button label="自定义" ></el-radio-button>
                        </el-radio-group>
                        <div style="display:inline-block" v-show="formdata.startTimeName=='自定义'">
                          <el-date-picker v-model="formdata.startTimeStr" type = "date" placeholder = "开始发放时间" :picker-options="pickerOptionsStart"></el-date-picker>
                        </div>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="结束发放时间" >
                        <el-radio-group v-model="formdata.endTimeName" size="medium">
                          <el-radio-button label="不限"></el-radio-button>
                          <el-radio-button label="自定义" ></el-radio-button>
                        </el-radio-group>
                        <div style="display:inline-block" v-show="formdata.endTimeName=='自定义'">
                          <el-date-picker v-model="formdata.endTimeStr" type = "date" placeholder = "结束发放时间" :picker-options="pickerOptionsEnd"></el-date-picker>
                        </div>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="最多发放数量" >
                       <el-input v-model="formdata.quota" placeholder="请输入最多发放数量"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="每人限领次数" >
                        <el-input v-model="formdata.limitCollar" placeholder="请输入限领次数"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
		</el-form>
        <div slot="footer"  class="dialog-footer">
          <el-button  @click="cancelHandel">取消</el-button>
          <el-button v-if="modalTitle=='优惠券添加'" type="primary" @click="create('form')">确 定</el-button>
          <el-button v-else type="primary" @click="update('form')">确 定</el-button>
        </div>
	</el-dialog>
  </div>
</template>

<script>
  import 'static/css/uploadImg.css';// 引入图片上传组件对话框
  import {
    formatDate
  } from 'utils/dateFormattor';

  import {
    toEast8Date,
    deepCopyDate,
    newEast8Date,
    convertDate2Str,
    timestamp2Date,
    getYMD
  } from 'utils/dateUtils';

  import {mapGetters} from 'vuex';
  import {
    getToken
  } from 'utils/auth';
  import {
    cunponManagementList,
    delObj,
    getObj,
    addObj
  } from 'api/cunponManagements';
  import Element1 from "../admin/menu/components/element";
  import ElRow from "element-ui/packages/row/src/row";
  import ElCol from "element-ui/packages/col/src/col";

  export default {
    name: 'cunponManagement',
    components: {
      ElCol,
      ElRow,
      Element1,
    },
    data() {
      return {
        cunponType:[
            {
                id:1,
                val:'满减卷'
            },{
                id:2,
                val:'叠加满减卷'
            },{
                id:3,
                val:'无门槛卷'
            }
        ],
        usedType:[
          {
            id:10,
            val:'店铺优惠卷'
          },
          {
            id:11,
            val:'新人店铺卷'
          },
          {
            id:20,
            val:'商品优惠券'
          },
          {
            id:30,
            val:'类目优惠券'
          },
          {
            id:60,
            val:'平台优惠券'
          },
          {
            id:61,
            val:'新人平台券'
          }
        ],
        channelType:[
          {
            id:0,
            val:'全平台'
          },
          {
            id:1,
            val:'租车'
          },
          {
            id:2,
            val:'旅游'
          },
          {
            id:3,
            val:'营地'
          },
          {
            id:4,
            val:'会员'
          }
        ],
        BASE_API: process.env.BASE_API,
        showLoadingBody: false,
        // list: null,
        total: null,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20,
          title: '',//标题
          channel:'',//状态
        },
        inline: true,
        tableKey: 0,
        editDialogVisible:false,
        formdata:{},
        modalTitle:'',
        isUpdate:false,
        rules:{
             title: {
                type: 'string',
                required: true,
                message: '请输入标题',
                trigger: 'blur'
            },
        },
        list:[],
        pickerOptionsStart: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7;
          }
        },
        // pickerOptionsStart: {
        //         disabledDate: time => {
        //           const endDateVal = new Date(this.formdata.endTimeStr).getTime()
        //           if (endDateVal) {
        //             return time.getTime() > endDateVal - 0
        //           }
        //         }
        // },
        pickerOptionsEnd: {
                disabledDate: time => {
                  const beginDateVal = new Date(this.formdata.startTimeStr).getTime()
                  if (beginDateVal) {
                    return time.getTime() < beginDateVal - 0
                  }
                }
        },
         pickerOptionsEnd1: {
                disabledDate: time => {
                  const beginDateVal = new Date(this.formdata.validStartTimeStr).getTime()
                  if (beginDateVal) {
                    return time.getTime() < beginDateVal - 0
                  }
                }
        }

      }
    },
    created() {
      this.getList();
    },
    computed: {
      ...mapGetters([
        'elements'
      ]),
      getHeaderWithToken() {
        return {Authorization: getToken()};
      },
    },
    methods: {
      /**
       * 获取提现列表
       * */
      getList() {
        this.listLoading = true;
        cunponManagementList(this.listQuery).then(response => {
          let totalCountRs = undefined;
          let listRs = undefined;
          if (!this.$utils.isEmpty(response.data.data) && this.$utils.isInteger(response.data.totalCount)) {
            listRs = response.data.data;
            totalCountRs = response.data.totalCount;
            listRs.map(function(item){
              item.crtTimeStr = timestamp2Date(item.crtTime);
            });
          }
          this.listLoading = false;
          this.list = listRs;
          this.total = totalCountRs;
        })

      },
      handleFilter() {
        this.listQuery.page = 1;
        this.$refs.queryForm.validate(valid => {
          if (valid) {
            this.getList();
          } else {
            return false;
          }
        });
      },
      handleSizeChange(val) {
        this.listQuery.limit = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.page = val;
        this.getList();
      },
      handleUpdate(row){
          var that = this;
          that.modalTitle = '优惠券编辑';
          that.isUpdate = true;
          that.cleanForm();
          getObj(row.id).then(response => {
            console.log(response)
            var item = response.data;
            item.user_type_name = item.userType==0?'普通用户':'会员用户';
            item.valid_type_name = item.validType==1?'绝对时效':item.validType==2?'相对时效':'永久时效';
            //相对时效的时间
            if(item.validStartTime>0){
              item.validStartTimeStr = getYMD(item.validStartTime);
            }else{
              item.validStartTimeStr = '';
            }
            if(item.validEndTime>0){
              item.validEndTimeStr = getYMD(item.validEndTime);
            }else{
              item.validEndTimeStr = '';
            }
            //高级设置，发放时间
            if(item.startTime>0){
              item.startTimeStr = getYMD(item.startTime);
            }else{
              item.startTimeStr = '';
            }
            if(item.endTime>0){
              item.endTimeStr = getYMD(item.endTime);
            }else{
              item.endTimeStr = '';
            }

            item.startTimeName=item.startTime==0?'不限':'自定义';
            item.endTimeName=item.endTime==0?'不限':'自定义';
            item.cangive='否';
            that.formdata = item;
            that.editDialogVisible = true;
          })


      },
      addCunpon(){
          var that = this;
          that.modalTitle = '优惠券添加';
          that.isUpdate = false;
          that.cleanForm();
          console.log(that.formdata)
          that.editDialogVisible = true;
      },
      deleteHandler(row){
        this.$confirm('确定删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delObj(row.id).then(() => {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            });
            row.visible2 = false;
            const index = this.list.indexOf(row);
            this.list.splice(index, 1);
          });
        })
      },
      /**
       * 创建
       * */
      create(formName) {
        var that = this;
        const set = this.$refs;
        set[formName].validate(valid => {
          if (valid) {
            that.formdata.userType = that.formdata.user_type_name=='普通用户'?0:1;
            that.formdata.validType = that.formdata.valid_type_name=='绝对时效'?1:that.formdata.valid_type_name=='相对时效'?2:3;
            if(that.formdata.valid_type_name=='绝对时效'){
              that.formdata.validStartTime = new Date(this.formdata.validStartTimeStr).getTime();
              that.formdata.validEndTime = new Date(this.formdata.validEndTimeStr).getTime();
            }else{
              that.formdata.validStartTime = 0;
              that.formdata.validEndTime = 0;
            }
            if(that.formdata.valid_type_name=='相对时效'){
              if(that.formdata.validDays<=0){
                this.$notify({
                  title: '警告',
                  message: '相对时效时间需大于0',
                  type: 'warning',
                  duration: 2000
                });
                return false
              }
            }
            if(that.formdata.startTimeName=='自定义'){
              that.formdata.startTime = new Date(this.formdata.startTimeStr).getTime();
            }else{
              that.formdata.startTime = 0
            }
            if(that.formdata.endTimeName=='自定义'){
              that.formdata.endTime = new Date(this.formdata.endTimeStr).getTime();
            }else{
              that.formdata.endTime = 0
            }

            console.log(that.formdata)
            addObj(that.formdata)
              .then(response => {
                if (response.status === 200) {
                  this.editDialogVisible = false;
                  this.getList();
                  this.$notify({
                    title: '成功',
                    message: '创建成功',
                    type: 'success',
                    duration: 2000
                  });
                } else {
                  this.$notify({
                    title: '失败',
                    message: rsCode.msg[response.code] ? rsCode.msg[response.code] : '操作失败！',
                    type: 'error',
                    duration: 2000
                  });
                }
              });
          } else {
            return false;
          }
        });
      },
      /**
       * 编辑-更新
       * */
      update(formName) {
        var that = this;
        const set = this.$refs;
        set[formName].validate(valid => {
          if (valid) {
            that.formdata.userType = that.formdata.user_type_name=='普通用户'?0:1;
            that.formdata.validType = that.formdata.valid_type_name=='绝对时效'?1:that.formdata.valid_type_name=='相对时效'?2:3;

            if(that.formdata.valid_type_name=='绝对时效'){
              that.formdata.validStartTime = new Date(that.formdata.validStartTimeStr).getTime();
              that.formdata.validEndTime = new Date(that.formdata.validEndTimeStr).getTime();
            }else{
              that.formdata.validStartTime = 0;
              that.formdata.validEndTime = 0;
            }

            if(that.formdata.startTimeName=='自定义'){
              that.formdata.startTime = new Date(that.formdata.startTimeStr).getTime();
            }else{
              that.formdata.startTime = 0
            }
            if(that.formdata.endTimeName=='自定义'){
              that.formdata.endTime = new Date(that.formdata.endTimeStr).getTime();
            }else{
              that.formdata.endTime = 0
            }

            console.log(that.formdata)
            addObj(that.formdata)
              .then(response => {
                if (response.status === 200) {
                  this.editDialogVisible = false;
                  this.getList();
                  this.$notify({
                    title: '成功',
                    message: '编辑成功',
                    type: 'success',
                    duration: 2000
                  });
                } else {
                  this.$notify({
                    title: '失败',
                    message: rsCode.msg[response.code] ? rsCode.msg[response.code] : '操作失败！',
                    type: 'error',
                    duration: 2000
                  });
                }
              });
          } else {
            return false;
          }
        });
      },
      /**
       * 上传图片
       * @param file
       * @returns {boolean}
       */
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/gif';
        const isLt2M = file.size / 1024 / 1024 < 10;

        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG/GIF 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 10MB!');
        }
        this.showLoadingBody = true;
        return isJPG && isLt2M;
      },
      handleAvatarSuccess(res, file) {
        this.formdata.icon = res.data;
        this.showLoadingBody = false;
      },
      /**
       * 弹框-取消
       * */
      cancelHandel(){
        this.cleanForm();
        this.editDialogVisible = false;
      },
      /**
      * 清空表单
      * */
      cleanForm() {
        this.formdata = {
          title: '',
          user_type_name:"普通用户",
          usedAmount:'',
          type:1,
          withAmount:'',
          valid_type_name:'绝对时效',
          validStartTimeStr:'',
          validEndTimeStr:'',
          validDays:0,
          cangive:'否',
          url:'',
          icon:'',
          used:61,
          channel:0,
          startTimeName:'不限',
          endTimeName:'不限',
          startTimeStr:'',
          endTimeStr:'',
          quota:'',
          limitCollar:''
        }
      },
    }
  }
</script>

<style lang="" scope>

</style>
