<template>
  <div>
    <el-drawer
      size="50%"
      title="商品优惠券列表"
      :visible.sync="drawer"
      :direction="direction"
      :before-close="handleClose"
    >
      <div style="padding:15px">
        <!-- <el-button class="closeBtn" type="primary" plain 
              @click="handleClose">确定选中并关闭</el-button
            > -->
        <!-- <el-form
          :inline="true"
          :model="query"
          @keyup.enter.native="getDataList()"
        > -->
          <!-- <el-form-item label="课程名称">
            <el-input
              v-model="query.courseName"
              placeholder="课程名称"
              clearable
            ></el-input>
          </el-form-item> -->          
          <!-- <el-form-item> -->
            <el-button type="primary" @click="getAllCoupon()"
              >绑定新优惠券</el-button
            >
          <!-- </el-form-item> -->
        <!-- </el-form> -->
      </div>
      <div style="padding: 15px">
        <!-- {{dataList}} -->
        <el-table
          v-loading="dataListLoading"
          :data="dataList"
          border
          style="width: 100%; "
        >
          <!-- <el-table-column type="selection" > </el-table-column> -->
          <el-table-column prop="id" label="名称">
            <template slot-scope="scope">{{scope.row.couponEntity.couponName}}</template>
        </el-table-column>
        <!-- <el-table-column prop="id" label="获得途径">
            <template slot-scope="scope">
                <span v-if="scope.row.getType == 0">后台赠送<br/>
                  <i>原因：{{scope.row.remark}}</i>
                </span>
                <span v-if="scope.row.getType == 1">主动获取</span>
            </template>
        </el-table-column> -->
        <el-table-column prop="id" label="使用上限（x张）">
            <template slot-scope="scope">
                {{scope.row.couponEntity.limitedCollar}}               
            </template>
        </el-table-column>
        <el-table-column prop="id" label="使用门槛(元)">
            <template slot-scope="scope">
                {{scope.row.couponEntity.useLevel}}               
            </template>
        </el-table-column>
        <el-table-column prop="id" label="优惠券范围">
            <template slot-scope="scope">
                {{scope.row.couponEntity.couponRange | getRange}}               
            </template>
        </el-table-column>
        <el-table-column prop="id" label="优惠券类型">
            <template slot-scope="scope">
                {{scope.row.couponEntity.effectType | getType}}               
            </template>
        </el-table-column>
          <el-table-column prop="description" label="操作" width="120">
            <template slot-scope="scope">
              <el-button
                type="danger"
                plain
                size="small"
                @click="deleteHandle(scope.row.id)"
              >
               断开绑定
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
          :current-page="pageIndex"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="totalPage"
          style="padding: 30px 0; text-align: center;"
          layout="total, sizes, prev, pager, next, jumper"
        >
        </el-pagination>
      </div>
    </el-drawer>
    <el-dialog
      title="添加优惠券绑定"
      :close-on-click-modal="false"
      :visible.sync="youVisible"
      append-to-body
      width="600px"
      @close="dialogHandleClose"
    >
      <el-form :model="youForm" label-width="100px">
        <el-form-item label="选择优惠券">
          <el-select
            v-model="youForm.ids"            
            filterable
            remote
            reserve-keyword
            placeholder="请输入优惠券名称"
            :remote-method="getAllCoupon"
            :loading="loading"
          >
            <el-option
              v-for="item in couponList"
              :key="item.id"
              :label="item.couponName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>        
        <!-- {{youForm.ids}} -->
        <el-form-item>
            <el-button
            type="primary"
            @click="surYou" 
            >绑 定</el-button
          >
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="youVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "productCouponList",
  props: ["productId"],
  data() {
    return {
      youVisible: false,
      // userId: this.$router.query.userId,
      drawer: true,
      direction: "rtl",
      dataList: [],
      selected: [],
      query: {
        //   courseName: ""
        status: "",
        getType: ""
      },
      couponList: [],
      statusList: [
        {
          label: "未使用",
          value: "0"
        },
        {
          label: "已使用",
          value: "1"
        },
        {
          label: "已过期",
          value: "2"
        }
      ],
      typeList: [
        {
          label: "后台赠送",
          value: "0"
        },
        {
          label: "主动获取",
          value: "1"
        }
      ],
      pageSize: 10,
      pageIndex: 1,
      totalPage: 0,
      dataListLoading: false,
      youForm: {
        couponName:'',       
        ids:undefined
      },
      loading: false,

    };
  },

  mounted() {
    console.log("挂载", this.productId);
    //   this.userId =
    this.getDataList();
  },
     filters: {
      // 格式化时间
      getType (value) { 
          switch (value) {
            case 0:
              return '长期有效'
            case 1:
              return '领取生效'
            case 2:
              return '自定义'
          }
      },
      getRange (value) {       
          switch (value) {
            case 0:
              
              return '无限制'
            case 1:
              return '课程券'
            case 2:
              return '课程品类券'           
          }       
      }
    },
  methods: {
    deleteHandle (id) {
        // var ids = id ? [id] : this.dataListSelections.map(item => {
        //   return item.id
        // })
        this.$confirm(`确定对[id=${id}]进行删除操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/common/coupon/unbindCouponToProduct'),
            method: 'post',
            data: this.$http.adornData({
              "id": id
            })
          }).then(({data}) => {
            if(data.code!== 0) return this.$message.error(data.msg)

            if (data && data.code === 0) {
              this.$message({
                message: '解绑成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
    dialogHandleClose(){
      this.youVisible = false
      this.youForm.ids = undefined
      // this.youForm.remark = ''

    },
    surYou() {
        if(!this.youForm.ids){
          this.$message({
            message: '请选择优惠券',
            type: 'warning',
            duration: 1500,
          })
          return
        }
       var data = {
        "couponId": this.youForm.ids,       
        "productId": this.productId,        

       }
        this.$http({
          url: this.$http.adornUrl('/common/coupon/setCouponToProduct'),
          method: 'post',
          data: this.$http.adornData(data)
        }).then(({
          data
        }) => {
            if (data.code!== 0) return this.$message.error(data.msg);

          if (data && data.code === 0) {
            this.$message({
              message: '绑定成功',
              type: 'success',
              duration: 1500,
            })  
            this.dialogHandleClose()          
            this.getDataList()
          }
          // else{
          //   this.$message({
          //     message: data.msg,
          //     type: 'error',
          //     duration: 1500,
          //   })
          // }
        })
      },
    givePersonCoupon() {
        // this.youVisible = true
    },
    getAllCoupon() {
      this.loading = true;
      this.$http({
        url: this.$http.adornUrl("/common/coupon/getCouponList"),
        method: "post",
        data: this.$http.adornData({
          page: 1,
          limit: 10,
          couponName: this.youForm.couponName,
          currentState: '0', //当前状态 0 发放中 1结束
          couponType: '', //优惠券类型  0现金 1折扣
          couponRange: '' //优惠卷范围 0无限制 1课程卷 2课程品类卷
        })
      })
        .then(({ data }) => {
          if (data.code !== 0) return this.$message.error(data.msg);
          if (data && data.code === 0) {
            this.couponList = data.couponPage.records;
                this.youVisible = true
            // this.totalPage = data.couponPage.total;
          } else {
            this.dataList = [];
            // this.totalPage = 0;
          }
          this.loading = false;
        })
        .catch(e => {
          this.$message.error(e.msg);
          this.loading = false;
        });
    },
      handleSelect(row) {
      var _list = this.selected.map(item => item.id);
      if (_list.includes(row.id)) {
        this.$message({
          message: "已选择该课程",
          type: "warning"
        });
        return;
      }
      this.selected.push(row);
      let index = this.dataList.findIndex(item => item.id === row.id);
      this.dataList.splice(index, 1);
      this.$message({
        message: "选择成功",
        type: "success"
      });
      console.log("选择的课程", this.selected);
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    handleClose(done) {
      this.$emit("close", this.selected);
      this.selected = [];
    },
    getDataList() {
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl("/common/coupon/couponToProductList"),
        method: "post",
        data: this.$http.adornData({
          page: this.pageIndex,
          limit: this.pageSize,
          productId: this.productId

        })
      })
        .then(({ data }) => {
          if (data.code != 0) return this.$message.error(data.msg);
          // console.log('data',data)
          if (data && data.code === 0) {
            this.dataList = data.couponToShopproductPage.records;

            this.totalPage = data.couponToShopproductPage.total;
          } else {
            this.dataList = [];
            this.totalPage = 0;
          }
          this.dataListLoading = false;
        })
        .catch(e => {
          this.$message.error(e.msg);
          this.dataListLoading = false;
        });
    }
  }
};
</script>

<style lang="sass" scoped>
.closeBtn{position: absolute;right: 15px;top: 15px;}
</style>
