<style scoped>
.user-panel {
  margin: 10px auto;
}
.avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
</style>
<template>
  <el-dialog v-drag-dialog
      :visible.sync="showDialog"
      :modal-append-to-body="false"
      append-to-body
      :modal="true"
      :title="modalTitle"
      style="text-align:left;"
      @close="closeDialog"
      :close-on-click-modal="false"
        width="1200px"
  >
    <div class="user-panel" v-loading="loading">
        
        <el-row class="button-group">
            <el-select v-model="formModel.awardId" size="small" placeholder="请选择奖项">
                <el-option
                v-for="item in awardInfoList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
                </el-option>
            </el-select>
          <el-button type="primary" size="small" @click="handleStart" style="margin-left:10px">开始抽奖</el-button>
        </el-row>
        <el-divider></el-divider>
        <el-table
        :data="tableData"
        style="min-height:400px;"
        v-loading="loading"
        stripe
        @sort-change="sortChange"
        @selection-change="handleSelectionChange"
      >
        <el-table-column  prop="lotteryPersonnelImage"  label="头像">
            <template slot-scope="{row}">
            <a v-if="row.lotteryPersonnelImage" :href="row.lotteryPersonnelImage" target="_blank">
              <el-image
              style="width: 50px; height: 50px"
              :src="row.lotteryPersonnelImage"
              fit="fit"></el-image>
            </a>
          </template>
        </el-table-column>
        <el-table-column prop="lotteryPersonnelNickName" label="昵称" ></el-table-column>
        <el-table-column prop="lotteryPersonnelPhone" label="中奖人电话" ></el-table-column>
        <el-table-column prop="awardName" label="奖项" ></el-table-column>
        <el-table-column prop="awardPrizeName" label="奖品" width="320"></el-table-column>
        <el-table-column prop="activityName" label="所属活动" width="280"></el-table-column>
        <!-- <el-table-column label="操作" width="200">
          <template slot-scope="{row}" >
            <el-button size="mini" type="warning" @click="handleEdit(row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column> -->
      </el-table>
      <awardInfo-detail
          v-if="showDetailModal"
          @close="onDetailModalClose"
          :title="title"
          :activityId="activityId"
          :businessKey="businessKey"
        ></awardInfo-detail>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">保 存</el-button>
    </span>
  </el-dialog>
</template>
<script>
import Constant from "@/constant";
import winningInfoApi from "@/api/base/winningInfo";
import awardInfoDetail from "./awardInfo-detail";
import awardInfoApi from "@/api/base/awardInfo";
import { getToken } from "@/utils/auth"; // get token from cookie

export default {
    props: ["activityId", "modalTitle"],
  data() {
    return {
        tableData: [],
        pageIndex: 1,
        pageSize: 10,
        totalPages: 0,
        totalElements: 0,
        field: "",
        direction: "",
        pageSizeList: [10, 20, 30],
        multipleSelection: [],
        formModel: {
            activityId:"",
            awardId:"",
            winningInfoList:[],
        },
        queryModel:{
          lotteryPersonnelPhone:"",
        },
        dataDictionaryList: [],
        showDialog: true,
        loading: false,
        submitting: false,
        showDetailModal:false,
        batchImportFileList: [],
        xlsLoading: false,
        uploadUrlXls: Constant.serverUrl + "/base/lotteryPersonnelInfo/importXls",
        uploadXlsData: {
            subFolder: "lotteryPersonnelInfo",
        },
        headers: {
            Authorization: getToken(),
        },
        awardInfoList:[],
    };
  },
  created() {
    var self = this;
    var formData = new FormData();
  
    formData.append("activityId", self.activityId);

    awardInfoApi.findByActivityId(formData).then(function (response) {
        var jsonData = response.data;
        if (jsonData.result) {
            if (jsonData.data != null && jsonData.data != "") {
                self.awardInfoList = jsonData.data;
            }
        }
    });
  },
  methods: {
    closeDialog() {
      this.$emit("close", false);
    },

      exportXls() {
        this.changePage(1,true);
      },
      handleReset(name) {
        this.$refs[name].resetFields();
      },
      handleStart(){
        var self = this;

        if(self.formModel.awardId==null||self.formModel.awardId==""){
          self.$message({
            type: "error",
            message: "请先选择奖项才能开始抽奖!"
          });
          return;
        }


        self.loading = true;

        var formData = new FormData();
        formData.append("activityId", self.activityId);
        formData.append("awardId", self.formModel.awardId);
  
        self
          .$confirm("是否确认开始抽奖?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(() => {
            winningInfoApi.startLottery(formData).then(function(response) {
                self.loading = false;
  
                var jsonData = response.data;

                if (jsonData.result) {
                    var page = jsonData.data;

                    self.tableData = page;
    
                    self.$message({
                      type: "success",
                      message: "抽奖完成!"
                    });
              }
            })
            .catch(error => {
                self.loading = false;
                // self.$message.error(error + "");
            });
          })
          .catch(() => {
            // 点击"取消"的逻辑
            self.loading = false;
          });
      },
    handleAvatarSuccess(res, file) {
        var self = this;
        self.formModel.extended1 = res.data;

        self.fileUrl =
          res.data + "?x-oss-process=image/resize,m_lfit,h_300,w_300";
    },
    beforeAvatarUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isLt2M;
    },
    handleAdd() {
        var self = this;
        
        self.title = "新增";
        self.businessKey = "";
        self.showDetailModal = true;
      },
    handleEdit(record) {
        var self = this;
  
        self.title = "编辑";
        self.businessKey = record.id;
        self.showDetailModal = true;
    },
    handleDelete(record) {
        var self = this;
  
        self
          .$confirm("是否确认删除?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(() => {
            winningInfoApi.remove(record.id).then(function(response) {
              var jsonData = response.data;
  
              if (jsonData.result) {
                // var index = self.tableData.indexOf(record);
                // self.tableData.splice(index, 1);
                self.changePage(self.pageIndex);
  
                self.$message({
                  type: "success",
                  message: "删除成功!"
                });
              }
            });
          });
      },
    onDetailModalClose(refreshed){
    this.showDetailModal = false;

    if(refreshed){
        this.changePage(this.pageIndex);
    }
    },
    beforeUpload(file, fileList) {
          //导入前判断
          var self = this;
          self.xlsLoading = true;
          return true;
      },
              //批量导入-上传成功
      handleBatchImportSuccess(response, file, fileList) {
        var self = this;
        self.xlsLoading = false;

        if (response.result) {
            self.$message.success(response.message);
            this.batchImportFileList = [];
            this.changePage(1);


        } else {
            //this.$message.error(response.message);
            this.batchImportFileList = [];
            this.changePage(1);

            if (response.data != null) {
            //下载有错误信息提示的报表
            //window.open(response.data);
            self.$message({
                showClose: true,
                dangerouslyUseHTMLString: true,
                message:
                response.message +
                `,<a href="${response.data}" target="_blank">点击下载未导入的数据报表</a>&nbsp;`,
                duration: 30000,
            });
            }
        }

        this.batchImportVisible = false;
      },
      //批量导入-预览
      handleBatchImportPreview(file) {
        console.log(file.url);
      },
      //批量导入-移除
      handleBatchImportRemove(file, fileList) {
        console.log(file, fileList);
      },
      //批量导入-移除前操作
      beforeBatchImportRemove(file, fileList) {
        console.log(file, fileList);
      },
      //批量导入-文件超出个数限制时的钩子
      handleBatchImportExceed(files, fileList) {
      this.$message.warning(
          `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
          } 个文件`
        );
      },

      handleSubmit() {
      var self = this;
      (function() {
        self.formModel.activityId = self.activityId;
        self.formModel.winningInfoList = self.tableData;

        return winningInfoApi.add(self.formModel);
      })().then(function(response) {
        var jsonData = response.data;

        if (jsonData.result) {
          self.$message({
            message: "保存成功!",
            type: "success"
          });

          self.$emit("close", true);
        } else {
          self.$message({
            message: jsonData.message + "",
            type: "warning"
          });

          self.$emit("close", false);
        }
      });
    },
  },
  mounted: function ()  {
    this.changePage(1);
  },
  components: {
    "awardInfo-detail": awardInfoDetail,
  }
};
</script>