<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" @click="handleCreate">
        新增
      </el-button>
      <el-upload
        ref="upload"
        :file-list="filelist"
        class="upload-demo"
        style="float: right"
        :action="uploadUrl"
        name="file"
        accept=".xls, .xlsx"
        :limit="1"
        :http-request="modeUpload"
        :on-success="handleSuccess"
        :on-error="handleError"
      >
        <el-button slot="trigger" size="small" type="primary">选取Excel</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
      </el-upload>
    </div>
    <el-table
      :data="whitelist"
      border
      fit
      highlight-current-row
      style="width: 100%;"

      :empty-text="emptytext"
      height="480"
    >
      <el-table-column
        label="账号"
        prop="account_id"
      />
      <el-table-column
        label="类型"
        prop="type"
      />
      <!--el-table-column
        prop="createtime"
        label="创建时间"
      >
        <template slot-scope="{row}">
          <span>
            {{ parseTime(row.createtime) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        prop="modifytime"
        label="修改时间"
      >
        <template slot-scope="{row}">
          <span>
            {{ parseTime(row.modifytime) }}
          </span>
        </template>
      </el-table-column-->
      <el-table-column
        fixed="right"
        label="操作"
      >
        <template slot-scope="scope">
          <!--el-button type="text" size="small" @click="handleUpdate(scope.row)">编辑</el-button-->
          <el-button type="text" size="small" @click="handleDel(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      :current-page="curpage"
      :page-size="page_size"
      :page-count="totalpage"
      layout="prev, pager, next"
      @current-change="handleCurrentChange"
    />
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" :close-on-click-modal="false" @close="handleDialogClose()">
      <el-form ref="form" :rules="rules" :model="form" label-position="left" label-width="90px" style="width: 400px; margin-left:50px;">
        <el-form-item label="账号" prop="account_id">
          <el-input v-model="form.account_id" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-input v-model="form.type" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = handleDialogClose()">
          Cancel
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          Confirm
        </el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
// import Pagination from '@/components/Pagination/index.vue'
import { addWhiteList, getWhiteList, delWhiteList, uploadWhiteList } from '@/api/whitelist'
import { parseTime } from '@/utils'

export default {
  components: {

  },

  data() {
    return {
      form: {
        account_id: '',
        blocked: 1
      },
      dialogFormVisible: false,
      dialogStatus: '',
      listLoading: true,
      whitelist: [],
      dialogTitle: '新增',
      emptytext: ' ',
      totalpage: 0,
      curpage: 1,
      page_size: 8,
      rules: {
        account_id: [{ required: true, message: 'required', trigger: 'blur' }],
        type: [{ required: true, message: 'required', trigger: 'blur' }]
      },
      uploadUrl: '',
      uploadData: {
        file: ''
      },
      filelist: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    parseTime,
    handleDialogClose() {
      // this.getList()
    },
    handleUpdate(row) {
      this.form.type = row.type
      this.form.account_id = row.account_id
      this.dialogStatus = 'update'
      this.dialogTitle = '编辑'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    handleDel(row) {
      this.$confirm('此操作将无法恢复, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delWhiteList({ account_id: row.account_id }).then(response => {
          if (response.code === 0) {
            if (this.whitelist.length === 1 && this.curpage === this.totalpage && this.curpage > 1) {
              this.curpage--
            }
            this.getList()
            this.$notify({
              title: 'Success',
              message: 'Deleted Successfully',
              type: 'success',
              duration: 2000
            })
          }
        })
      }).catch(() => {
      })
    },
    getList() {
      const data = {
        'page_dto': {
          'page': this.curpage,
          'pageSize': this.page_size
        }
      }
      getWhiteList(data).then(response => {
        this.whitelist = response.data
        this.totalpage = response.total_page
        this.curpage = response.cur_page
        // this.pager = response.cur_page
        if (this.whitelist === undefined || this.whitelist.length <= 0) {
          this.emptytext = 'No data'
        }
      })
    },
    handleCurrentChange(val) {
      this.curpage = val
      this.getList()
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogTitle = '新增'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    resetTemp() {
      this.form = {
        account_id: '',
        blocked: 0
      }
    },
    createData() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          addWhiteList(this.form).then(response => {
            if (response.code === 0) {
              this.dialogFormVisible = false
              this.getList()
              this.$notify({
                title: 'Success',
                message: 'Created Successfully',
                type: 'success',
                duration: 2000
              })
            }
          })
        }
      })
    },
    /* updateData() {
      console.log('update', this.form)
      this.$refs['form'].validate((valid) => {
        if (valid) {
          updateWhiteList(this.form).then(response => {
            if (response.code === 0) {
              this.dialogFormVisible = false
              this.getList()
              this.$notify({
                title: 'Success',
                message: 'Updated Successfully',
                type: 'success',
                duration: 2000
              })
            }
          })
        }
      })
    }, */
    handleSuccess(response, file, fileList) {
      // 成功回调
      console.log('File uploaded successfully:', response)
    },
    handleError(err, file, fileList) {
      // 错误回调
      console.error('Error uploading file:', err)
    },
    modeUpload(item) {
      this.uploadData.file = item.file
    },
    submitUpload() {
      const data = new FormData()
      data.append('file', this.uploadData.file)
      uploadWhiteList(data).then(response => {
        this.$refs.upload.clearFiles()
        if (response.code === 0) {
          this.getList()
          this.$notify({
            title: 'Success',
            message: 'Created Successfully',
            type: 'success',
            duration: 2000
          })
        }
      })
    }
  }
}
</script>

