<template>
  <div class="app-container calendar-list-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input clearable class="filter-item" style="width: 200px;" placeholder="请输入员工号或员工姓名" v-model="listQuery.searchInput"></el-input>
      <el-select clearable class="filter-item" style="width: 200px;" placeholder="是否已领取" v-model="listQuery.status">
        <el-option label="未领取" value="0">
        </el-option>
        <el-option label="已领取" value="1">
        </el-option>
      </el-select>
      <!--
      <el-input clearable class="filter-item" style="width: 200px;" placeholder="请输入广告内容" v-model="listQuery.content">
      </el-input>
      -->
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">查找</el-button>
      <!--<el-button class="filter-item" type="primary" icon="el-icon-edit" @click="downLoadFile">下载模板</el-button>-->
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">批量导入</el-button>
      <el-button class="filter-item" type="primary" :loading="downloadLoading" v-waves icon="el-icon-download" @click="handleDownload">按条件导出</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table size="small" :data="list" v-loading="listLoading" element-loading-text="正在查询中。。。" border fit highlight-current-row>


      <!--<el-table-column align="center" width="100px" label="BannerID" prop="id" sortable>
      </el-table-column>-->
      <el-table-column type="index" label="序号" header-align="center" align="center">
      </el-table-column>
      <el-table-column align="center" min-width="100px" label="员工号" prop="employeno">
      </el-table-column>
      <el-table-column align="center" min-width="90px" label="员工姓名" prop="workerName">
      </el-table-column>
      <el-table-column align="center" min-width="180px" label="福利名称" prop="welfareName">
      </el-table-column>
      <el-table-column align="center" min-width="180px" label="兑换码" prop="redemptionCode">
      </el-table-column>
      <el-table-column align="center" min-width="150px" label="密码" prop="content">
        <template slot-scope="scope">
          {{scope.row.content? scope.row.content.replace(/^(.{2})(?:\w+)(.{2})$/, "\$1******\$2"):""}}
        </template>
      </el-table-column>
      <!--<el-table-column align="center" min-width="90px" label="开始时间" prop="startTime">
      </el-table-column>
      <el-table-column align="center" min-width="90px" label="结束时间" prop="endTime">
      </el-table-column>-->


      <el-table-column align="center" min-width="80px" label="是否在可用时间内" prop="inUsableTime">
        <template slot-scope="scope">
          <el-tag :type="scope.row.inUsableTime ? 'success' : 'error' ">{{ scope.row.inUsableTime ? '是' : '否' }}</el-tag>
        </template>
      </el-table-column>


      <el-table-column align="center" min-width="80px" label="领取状态" prop="inUsableTime">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status=='1' ? 'success' : 'error' ">{{ scope.row.status=='1' ? '已领取' : '未领取' }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" min-width="150px" label="领取时间" prop="receiveTime">
      </el-table-column>

      <el-table-column align="center" label="操作" width="150px" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!--<el-button type="primary" size="small" @click="handleUpdate(scope.row)">编辑</el-button>-->
          <el-button type="danger" size="small"  @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page"
        :page-sizes="[10,20,30,50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!-- 添加或修改对话框 -->
    <!--<el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="dataForm" status-icon label-position="left" label-width="100px" style='width: 400px; margin-left:50px;'>

        <el-form-item label="模板文件：" prop="url">
          <el-tooltip content="模板可下载" placement="top-start">
            <el-upload
              class="ad-avatar-uploader"
              v-model="dataForm.image"
              :action="fileImgUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeUpload">
              <template >
                <i class="el-icon-plus ad-avatar-uploader-icon"></i>
              </template>
            </el-upload>
          </el-tooltip>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>-->

    <!--导入-->
    <el-dialog title="导入" :visible.sync="dialogFormVisible" :modal-append-to-body="false" :close-on-click-modal="false" class="dialog-import">
      <div v-if="importFlag=='1'">
        <el-upload
          class="avatar-uploader"
          action="#"
          :before-upload="beforeUpload"
          :show-file-list="true"
          :limit="1"
          :http-request="uploadEmployeeExcel">
          <el-button size="small" type="primary" :disabled="processing">{{uploadTip}}</el-button>

          <div class="el-upload__tip" slot="tip" style="color:blue;">
            <a href="http://xiaoyou.dgtis.com/images/template/workerWelfare.xlsx" download="workerWelfare.xlsx" target="_blank">下载模板</a>
          </div>
          <div slot="tip" class="el-upload__tip">只能上传excel文件</div>
        </el-upload>

      </div>
      <div v-if="importFlag=='2'" >
        <div class="failure-tips">
            数据导入成功,稍后如果未刷新,请手动刷新该页面...
        </div>
        <!--<div class="failure-reason">
          <ul>
            <li>总共 {{errorResults.total}}行，成功：<span style="color: #42b983">{{errorResults.success}},</span>失败：<span style="color: #F56C6C">{{errorResults.fail}}</span>,已存在：<span style="color: #E6A23C">{{errorResults.has}}</span></li>
          </ul>
        </div>-->
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialogImport" type="primary">关闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style>
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 200px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
  }
</style>

<script>
  import {listNews} from '@/api/news'
import { listWelfare, insertListWelfare, updateWelfare, deleteWelfare } from '@/api/welfare'
import { createStorage,insetListWelfare } from '@/api/storage'
import waves from '@/directive/waves' // 水波纹指令

export default {
  name: 'banner',
  directives: {
    waves
  },
  data() {
    return {
      list: undefined,
      total: undefined,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        searchInput: undefined,
        status:'',
        sort: '+id'
      },
      dataForm: {
        id: undefined,
        employeno: undefined,
        welfareName: undefined,
        redemptionCode: undefined,
        content: undefined,
        start_time: undefined,
        end_time: undefined,
        status: undefined,
        inUsableTime:undefined,
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        //title: [{ required: true, message: '标题不能为空', trigger: 'blur' }]
      },
      //fileImgUrl: this.upLoadUrl,
      downloadLoading: false,
      url:undefined,//上传的模板
      processing: false,
      uploadTip:'点击上传',
      importFlag:1,
      errorResults:{
        total:0,
        success:0,
        fail:0,
        has:0
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      listWelfare(this.listQuery).then(response => {
        this.list = response.data.data.list
        this.total = response.data.data.total
        this.listLoading = false
      }).catch(() => {
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        employeno: undefined,
        welfareName: undefined,
        redemptionCode: undefined,
        content: undefined,
        start_time: undefined,
        end_time: undefined,
        status: undefined,
        inUsableTime:undefined,
      }
      this.errorResults={
        total:0,
        success:0,
        fail:0,
        has:0
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    uploadUrl(item) {
      const formData = new FormData()
      formData.append('file', item.file)
      createStorage(formData).then(res => {
        this.dataForm.url = res.data.data.url
      }).catch(() => {
        this.$message.error('上传失败，请重新上传')
      })
    },
    handleDownload() {
      this.downloadLoading = true
      listWelfare({
        page: 1,
        limit: 60000,
        searchInput: this.listQuery.searchInput,
        status:this.listQuery.status,
        sort: this.listQuery.sort
      }).then(response => {
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['员工号', '员工姓名', '福利名称', '兑换码', '密码','开始时间', '结束时间', '领取状态（0未领 1已领）', '领取时间']
          const filterVal = ['employeno','workerName', 'welfareName', 'redemptionCode', 'content', 'startTime', 'endTime', 'status', 'receiveTime']
          excel.export_json_to_excel2(tHeader, response.data.data.list, filterVal, '员工福利信息')
          this.downloadLoading = false
        })
      }).catch(() => {
        this.list = []
        this.total = 0
        this.listLoading = false
      })

    },
    createData() {
      this.dialogFormVisible = false
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateBanner(this.dataForm).then(() => {
            for (const v of this.list) {
              if (v.id === this.dataForm.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.dataForm)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {

      this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteWelfare(row).then(response => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
        })
      }).catch(() => {

      })

    },
    // 图片上传
    uploadBannerImg(file) {
      const isJPGs = file.type === 'image/jpeg'
    },
    handleAvatarSuccess(res) {
      console.log(res.data.url)
      this.dataForm.image = res.data.url
    },
    //上传之前验证钩子
    beforeUpload(file){
      //上传前配置
      let excelfileExtend = ".xls,.xlsx"//设置文件格式
      let fileExtend = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
      if (excelfileExtend.indexOf(fileExtend) <= -1) {
        this.$notify.error({
          title: '失败',
          message: '文件格式错误',
          duration: 2000
        })
        return false
      }
      this.uploadTip = '正在处理中...'
      this.processing = true
    },

    //上传
    uploadEmployeeExcel(item) {
      const formData = new FormData()
      formData.append('file', item.file)
      insetListWelfare(formData).then(response => {
        this.uploadTip = '点击上传'
        this.processing = false
        console.log(response.data)
        if (response.data.data.state === 'success') {
          this.importFlag = 2
          let successCount = response.data.data.success
          if(successCount){
            this.errorResults.success = successCount;
          }
          let hasCount = response.data.data.has
          if(hasCount){
            this.errorResults.has=hasCount
          }
          let failCount = response.data.data.fail
          if(failCount){
            this.errorResults.fail=failCount
          }
          let totalCount = response.data.data.total
          if(totalCount){
            this.errorResults.total = totalCount
          }
        } else {
          this.$notify.error({
            title: '失败',
            message: response.data.data.error,
            duration: 2000
          })
        }
      }).catch(() => {
        this.$message.error('上传失败，请重新上传')
      })

    },

    getRelativeActivity(id) {
      if(id) {
        for(let v of this.newsList) {
          if(v.id === id) {
            return v.title
          }
        }
      }
      return ""
    },
    downLoadFile(){
      window.open("http://xiaoyou.dgtis.com/images/template/workerWelfare.xlsx");
    },
    //关闭导入弹框
    closeDialogImport(){
      this.resetForm()
      this.dialogFormVisible = false
      this.getList()
    },
  }
}
</script>
<style>
  .ad-avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .ad-avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .ad-avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .ad-avatar {
    display: block;
  }
</style>
