<template>
  <div class="app-container">
    <el-card shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
      </div>
      <div style="margin-top: 15px">
        <el-form
          size="small"
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          @submit.native.prevent
        >
          <!-- <el-form-item label="姓名">
            <el-input v-model="queryParams.name" placeholder="请输入" />
          </el-form-item> -->
          <el-form-item label="手机号">
            <el-input v-model="queryParams.phone" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="queryParams.status"
              clearable
              placeholder="请选择"
            >
              <el-option key="0" label="未领取" value="0" />
              <el-option key="1" label="已领取" value="1" />
            </el-select>
          </el-form-item>
          <el-button type="primary" @click="handleSearchList" size="small">
            查询
          </el-button>
        </el-form>
      </div>
    </el-card>
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
      <div class="btn-add">
        <el-button @click="handleAdd" size="small" type="success"
          >手动添加</el-button
        >
        <el-button @click="handleDelete(false)" size="small" type="success"
          >一键删除</el-button
        >
        <el-button @click="handleImport" size="small" type="success">
          导入
        </el-button>
        <el-button @click="handleExport" size="small" type="warning">
          导出
        </el-button>
      </div>
    </el-card>
    <!-- @selection-change="handleSelectionChange" -->
    <el-table style="width: 100%" class="table-container" :data="dataList">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column
        label="序号"
        align="center"
        type="index"
      ></el-table-column>
      <el-table-column
        label="姓名"
        prop="name"
        align="center"
      ></el-table-column>
      <el-table-column
        label="手机号"
        prop="phone"
        align="center"
      ></el-table-column>
      <el-table-column
        label="单位"
        align="center"
        prop="unit"
      ></el-table-column>
      <el-table-column
        label="地址"
        align="center"
        prop="address"
      ></el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
      ></el-table-column>
      <el-table-column label="领取状态" align="center" prop="status">
        <template slot-scope="scope">
          {{ scope.row.status == 0 ? '未领取' : '已领取' }}
        </template>
      </el-table-column>
      <el-table-column
        label="领取时间"
        align="center"
        prop="receiveTime"
      ></el-table-column>
      <el-table-column
        label="操作"
        class-name="small-padding fixed-width"
        align="center"
      >
        <template slot-scope="scope">
          <el-button @click="handleUpdate(scope.row)" type="text" size="mini"
            >编辑</el-button
          >
          <el-button
            @click="handleDelete(scope.row)"
            type="text"
            size="mini"
            class="text-danger"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getDataList"
    />
    <!-- 添加修改 -->
    <el-dialog :title="title" :visible.sync="dialogVisible" width="25%">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" maxlength="11"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="
          upload.url + '?activityId=' + queryParams.activityId + '&unit=' + unit
        "
        :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-link type="info" style="font-size:12px" @click="importTemplate"
            >下载模板</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 {
  userList,
  orderDelete,
  aUserCreate,
  aUserUpdate,
  aUserDelete
} from '@/api/index';
import { getToken } from '@/utils/auth';
export default {
  name: 'Index',
  data() {
    return {
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/aUser/importDate'
      },
      unit: '',
      // 选中数组
      ids: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        activityId: null
      },
      queryPost: {
        name: '',
        phone: '',
        unit: ''
      },
      total: 0,
      dataList: [],
      dialogVisible: false,
      title: '',
      form: {},
      rules: {
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入', trigger: 'blur' }],
        unit: [{ required: true, message: '请输入', trigger: 'blur' }],
        address: [{ required: true, message: '请输入', trigger: 'blur' }]
      }
    };
  },
  methods: {
    importTemplate() {
      window.location.href =
        'http://192.168.0.125:9000/pic/20210901/1432982759525191680.xlsx';
    },
    handleSearchList() {
      this.queryParams.pageNum = 1;
      this.getDataList();
    },
    getDataList() {
      userList(this.queryParams).then(({ data }) => {
        this.dataList = data.list;
        this.total = data.total;
      });
    },
    // 添加
    handleAdd() {
      this.form = {
        activityId: this.queryParams.activityId, // 活动id
        unit: this.unit // 单位
      };
      this.resetForm('form');
      this.dialogVisible = true;
      this.title = '添加名单';
    },
    // 编辑
    handleUpdate(row) {
      this.resetForm('form');
      this.form = Object.assign({}, row);
      this.dialogVisible = true;
      this.title = '修改名单';
    },
    // 提交
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.title == '修改名单') {
            aUserUpdate(this.form).then(response => {
              this.msgSuccess('修改成功');
              this.dialogVisible = false;
              this.getDataList();
            });
          } else {
            aUserCreate(this.form).then(response => {
              console.log(response);
              this.msgSuccess('新增成功');
              this.dialogVisible = false;
              this.getDataList();
            });
          }
        }
      });
    },
    // 导出
    handleExport() {
      this.$confirm('是否确认导出所有定时任务数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        window.location.href =
          process.env.VUE_APP_BASE_API +
          '/aUser/export?activityId=' +
          this.queryParams.activityId;
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = '导入名单';
      this.upload.open = true;
    },
    // 文件上传中处理
    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.data, '导入结果', {
        dangerouslyUseHTMLString: true
      });
      this.getDataList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      if (!row && !this.total) return this.msgInfo('暂无数据');
      const val = row ? `删除 '${row.name}' 这条` : '清空所有';
      this.$confirm(`确认${val}数据?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const query = !row.id
            ? { id: this.queryParams.activityId }
            : { ids: [row.id] };
          return aUserDelete(query);
        })
        .then(() => {
          this.getDataList();
          this.msgSuccess('删除成功');
        });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
    }
  },
  created() {
    // const { id } = this.$route.query;
    // if (!id) {
    //   this.msgError('无ID');
    //   this.$router.go(-1);
    //   return;
    // }
    const { row } = this.$route.query;
    const query = JSON.parse(row);
    if (!query || !query.id) {
      this.msgError('无ID');
      this.$router.go(-1);
      return;
    }
    console.log(query);
    this.unit = query.unit;
    this.queryParams.activityId = query.id;
    this.getDataList();
  }
};
</script>
