<template> 
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button
          style="float:right"
          type="primary"
          @click="handleSearchList()"
          size="small">
          查询搜索
        </el-button>
        <el-button
          style="float:right;margin-right: 15px"
          @click="handleResetSearch()"
          size="small">
          重置
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="listQuery" size="small" label-width="140px">
          <el-form-item label="输入搜索：">
            <el-input v-model="listQuery.keyword" class="input-width" placeholder="用户名称" clearable></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
      <div class="btn-operate-wrap">
        <el-button class="btn-add btn-operate" @click="handleAdd()" size="mini">添加</el-button>
        <el-button class="btn-operate" @click="handleImport()" size="mini">导入</el-button>
      </div>
      <!-- <el-button size="mini" class="btn-add" @click="handleAdd()" style="margin-left: 20px">添加</el-button> -->
    </el-card>
    <div class="table-container">
      <el-table ref="rollbuyTable"
                :data="list"
                style="width: 100%;"
                v-loading="listLoading" border>
        <el-table-column label="编号" width="100" align="center">
          <template slot-scope="scope">{{scope.row.id}}</template>
        </el-table-column>
        <el-table-column label="用户名称" align="center">
          <template slot-scope="scope">{{scope.row.memberName}}</template>
        </el-table-column>
        <el-table-column label="产品名称" align="center">
          <template slot-scope="scope">{{scope.row.productName}}</template>
        </el-table-column>
        <el-table-column label="购买金额" align="center">
          <template slot-scope="scope">{{scope.row.money}}</template>
        </el-table-column>
        <el-table-column label="供应商名称" align="center">
          <template slot-scope="scope">{{scope.row.compName}}</template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button size="mini"
                       type="text"
                       @click="handleUpdate(scope.$index, scope.row)">
              编辑
            </el-button>
            <el-button size="mini"
                       type="text"
                       @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        :page-sizes="[10,15,20]"
        :total="total">
      </el-pagination>
    </div>
    <el-dialog
      :title="isEdit?'编辑数据':'添加数据'"
      :visible.sync="dialogVisible"
      width="40%">
      <el-form :model="rollbuy"
               ref="rollbuyForm"
               label-width="150px" size="small">
        <el-form-item label="用户名称：">
          <el-input v-model="rollbuy.memberName" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="产品名称：">
          <el-input v-model="rollbuy.productName" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="购买金额：">
          <el-input v-model="rollbuy.money"  type="number" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="供应商名称：">
          <el-input v-model="rollbuy.compName" style="width: 250px"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleDialogConfirm()" size="small">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        name="uploadFile"
        :data='upload.uploadData'
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" @change="uploadTypeChange" />是否更新已经存在的用户数据
          <!-- <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link> -->
          <el-link type="info" style="font-size:12px" @click="downloadExcel('/static/template/走马灯模板.xlsx','走马灯模板')">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
  import {fetchList, createrollbuy, updaterollbuy, deleterollbuy, excelImport} from '@/api/rollbuy';
  import {formatDate} from '@/utils/date';
  import { getToken } from '@/utils/auth'
  let  token = getToken()
  // import {createuse,updateuse,deleteuse,roleuse} from '@/api/permissions'
  // import SingleUpload from '@/components/Upload/singleUpload'
  // import MultiUpload from '@/components/Upload/multiUpload'

  const defaultListQuery = {
    pageNum: 1,
    pageSize: 10,
    keyword: null
  };
  const defaultRollbuy = {
    id: null,
    memberName: null,
    money: null,
    productName:null,
    compName:null,
  };
  export default {
    components: {
      // SingleUpload
    },
    name: 'rollbuyList',
    data() {
      return {
        // createuse,
        // updateuse,
        // deleteuse,
        // roleuse,
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: true,
          // 设置上传的请求头部
          headers: { Authorization:getToken() },
          // 上传的地址
          url: process.env.BASE_API + "/rollbuy/excelImport",
          //额外参数
          uploadData:{
            type:1
          }
        },
        listQuery: Object.assign({}, defaultListQuery),
        list: null,
        total: null,
        listLoading: false,
        dialogVisible: false,
        rollbuy: Object.assign({}, defaultRollbuy),
        isEdit: false,
      }
    },
    created() {
      this.getList();
    },
    filters: {
      formatDateTime(time) {
        if (time == null || time === '') {
          return 'N/A';
        }
        let date = new Date(time);
        return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
      }
    },
    methods: {
      handleResetSearch() {
        this.listQuery = Object.assign({}, defaultListQuery);
        this.getList();
      },
      handleSearchList() {
        this.listQuery.pageNum = 1;
        this.getList();
      },
      handleSizeChange(val) {
        this.listQuery.pageNum = 1;
        this.listQuery.pageSize = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.pageNum = val;
        this.getList();
      },
      handleAdd() {
        this.dialogVisible = true;
        this.isEdit = false;
        this.rollbuy = Object.assign({},defaultRollbuy);
      },
      rollbuyChange(e){
        let obj = this.rollbuyType.filter( (item) =>{
          return item.name == e
        })
        if(obj.length>0){          
          this.rollbuy.categoryId = obj[0].id
        }
      },
      handleDelete(index, row) {
        this.$confirm('是否要删除该专题?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleterollbuy(row.id).then(response => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getList();
          }).catch( err =>{ console.log('handleDelete err',err)});
        });
      },
      handleUpdate(index, row) {
        this.dialogVisible = true;
        this.isEdit = true;
        this.rollbuy = Object.assign({},row);      
        console.log('row',row);
      },
      handleDialogConfirm() {
        this.$confirm('是否要确认?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (this.isEdit) {
            // console.log('this.company',this.company);
            // console.log('this.rollbuy',this.rollbuy);
            // return false;
            updaterollbuy(this.rollbuy).then(response => {
              this.$message({
                message: '修改成功！',
                type: 'success'
              });
              this.dialogVisible =false;
              this.getList();
            })
          } else {
            createrollbuy(this.rollbuy).then(response => {
              this.$message({
                message: '添加成功！',
                type: 'success'
              });
              this.dialogVisible =false;
              this.getList();
            })
          }
        })
      },
      getList() {
        this.listLoading = true;
        fetchList(this.listQuery).then(response => {
          this.listLoading = false;
          this.list = response.data.list;
          this.total = response.data.total;
        });
      },
      //上传
      handleImport() {
        this.upload.title = "数据导入";
        this.upload.open = true;
      },
      /** 下载模板操作 */
    importTemplate() {
      // window.location.href = '/static/template/走马灯模板.xlsx'
      // this.download('/product/out', {
      // }, `产品导入_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.message, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    //上传类型改变
    uploadTypeChange(e){
      // console.log('uploadTypeChange',e);
      if(e){
        this.upload.uploadData.type = 1;
      }else{
        this.upload.uploadData.type = 0;
      }
      console.log('this.upload.uploadData.type',this.upload.uploadData.type);
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }


    }
  }
</script>
<style></style>


