<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-form ref="queryForm" :model="listQuery" label-width="100px">
        <el-row>
          <el-col :span="4">
            <el-form-item label="手机号">
              <el-input v-model.number="listQuery.phone" placeholder="请输入手机号"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item label="姓名">
              <el-input v-model.number="listQuery.name" placeholder="请输入姓名"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item label="状态">
              <el-select class="filter-item" v-model="listQuery.status" placeholder="请选员工状态">
                <el-option :key="undefined" label="全部" :value="undefined"></el-option>
                <el-option
                  v-for="(item,index) in statusList "
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-button class="filter-item" type="primary" v-waves icon="search" @click="handleFilter">搜索</el-button>
      <el-button
        class="filter-item"
        type="primary"
        v-waves
        icon="delete"
        @click="cleaningQuery"
      >清除搜索条件</el-button>

      <el-button class="filter-item" type="primary" v-waves @click="addStaff">新增员工</el-button>
      <el-button class="filter-item" type="primary" v-waves @click="toLoad">批量导入员工</el-button>

      <el-table
        :key="tableKey"
        :data="list"
        v-loading="listLoading"
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column prop="name" label="姓名" width="180" align="center"></el-table-column>
        <el-table-column prop="phone" label="手机号" align="center"></el-table-column>
        <el-table-column prop="positionName" label="身份" align="center"></el-table-column>
        <el-table-column label="状态" align="center">
          <template scope="scope">
            <span v-if="scope.row.status == 1">已核销</span>
            <span v-else>未核销</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="400" fixed="right">
          <template scope="scope">
            <el-button
              size="small"
              class="el-button el-button--text el-button--small"
              @click="editorStaff(scope.row)"
              v-if="scope.row.status != 1"
            >编辑</el-button>
            <el-button
              size="small"
              class="el-button el-button--text el-button--small"
              @click="deleteStaff(scope.row)"
              v-if="scope.row.status != 1"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="listQuery.page"
        :page-sizes="[10,20,30, 50]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top:20px"
      ></el-pagination>

      <!-- 新增编辑员工 -->
      <el-dialog
        :title="staffTitle"
        :visible.sync="bulkUploadMember"
        class="member"
        @close="closeAdd"
      >
        <el-form :model="staffTitleFrom" ref="userMembership" :rules="rules" label-width="100px">
          <el-form-item label="员工姓名">
            <el-input v-model.number="staffTitleFrom.name" placeholder="请输入姓名"></el-input>
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model.number="staffTitleFrom.phone" placeholder="请输入手机号"></el-input>
          </el-form-item>
          <el-form-item label="员工身份">
            <el-select
              class="filter-item"
              v-model="staffTitleFrom.positionId"
              placeholder="请选择员工身份"
              style="width:100%"
            >
              <el-option :key="undefined" label="全部" :value="undefined"></el-option>
              <el-option
                v-for="(item,index) in postionsList "
                :key="index"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <div style="text-align:center">
            <el-button type="primary" @click="confirm">确 定</el-button>
            <el-button type="primary" @click="bulkUploadMember = false">取消</el-button>
          </div>
        </el-form>
      </el-dialog>

      <!--批量导入会员窗口-->
      <el-dialog title="导入会员" :visible.sync="tolead">
        <el-form :model="fileForm">
          <el-form-item label="上传文件" label-width="80px">
            <el-button type="primary" icon="el-icon-download">
              <a
                class="el-icon-download"
                href="https://mgmt.dfangche.com/axshare/userposition.xlsx"
              >下载模板</a>
            </el-button>

            <el-upload
              ref="uploadExcel"
              :limit="limitNum"
              action="1111"
              :headers="getHeaderWithToken"
              accept=".xlsx"
              :http-request="upLoad"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :before-upload="beforeUploadFile"
              :on-change="fileChange"
              :on-exceed="exceedFile"
              :file-list="fileList"
            >
              <el-button size="small" type="primary" icon="el-icon-edit">
                上传文件
                <i class="el-icon-upload el-icon--right"></i>
              </el-button>
              <div slot="tip" class="el-upload__tip">只能上传xlsx(Excel2007以上版本)文件，且不超过10M</div>
            </el-upload>
            <el-button
              size="small"
              class="filter-item"
              type="primary"
              @click="cancelNotDeleteForm"
            >取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

      <!-- 提示 -->
      <el-dialog title="上传提示" :visible.sync="uploadHiut">
        <p>
          上传成功:
          <b>{{uploadListHiut.success}}</b>条,上传失败:
          <b>{{uploadListHiut.error}}</b>条
        </p>
        <ul class="defeated">
          <li v-for="(item,index) in uploadListHiut.uploadList" :key="index">
            <p>
              失败行数:
              <span>{{item.num}}</span>,失败原因:
              <span>{{item.msg}}</span>
            </p>
          </li>
        </ul>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  staffList,
  postions,
  addEditor,
  deleteStaffs
} from "src/api/admin/userManagement/index";
import { getToken } from "src/utils/auth";
import { mapGetters } from "vuex";
import { staffImport } from "src/api/admin/UserMember/index";
export default {
  created() {
    this.getList();
    this.postionsFn();
  },
  computed: {
    ...mapGetters(["elements"]),
    /**
     * 获取token
     */

    getHeaderWithToken() {
      return { Authorization: getToken() };
    }
  },
  data() {
    return {
      activeId: "",
      uploadListHiut: {
        uploadList: [],
        success: "",
        error: ""
      },
      uploadHiut: false,
      fileList: [],
      BASE_API: process.env.BASE_API,
      limitNum: 1,
      fileForm: {
        file: ""
      },
      tolead: false,
      listQuery: {
        name: "",
        phone: "",
        status: null,
        page: 1,
        limit: 10
      },
      total: null,
      tableKey: 0,
      list: [],
      listLoading: true,
      statusList: [
        {
          label: "未核销",
          value: "0"
        },
        {
          label: "已核销",
          value: "1"
        }
      ],
      postionsList: [],
      staffTitle: "新增员工",
      bulkUploadMember: false,
      staffTitleFrom: {
        phone: "",
        name: "",
        positionId: ""
      },
      rules: {}
    };
  },
  methods: {
    //新增,编辑员工弹窗关闭
    closeAdd() {
      this.staffTitleFrom = {
        phone: "",
        name: "",
        positionId: ""
      };
    },
    upLoad(file) {
      var form = new FormData();
      // 文件对象
      form.append("file", file.file);
      staffImport(form).then(res => {
        console.log(res);
        this.uploadHiut = true;
        (this.uploadListHiut = {
          uploadList: res.data.data,
          success: res.data.success,
          error: res.data.error
        }),
          this.getList();
      });
    },
    //excel上传
    handleRemove(file, fileList) {
      //console.log(file, fileList);
    },
    handlePreview(file) {
      //console.log(file);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    // 文件超出个数限制时的钩子
    exceedFile(files, fileList) {
      this.$notify.warning({
        title: "警告",
        message: `只能选择 ${
          this.limitNum
        } 个文件，当前共选择了 ${files.length + fileList.length} 个`
      });
    },
    // 文件状态改变时的钩子
    fileChange(file, fileList) {
      //console.log("change");
      //console.log(file);
      this.fileForm.file = file.raw;
      //console.log(this.fileForm.file);
      // console.log(fileList);
    },
    // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
    beforeUploadFile(file) {
      //console.log("before upload");
      //console.log(file);
      let extension = file.name.substring(file.name.lastIndexOf(".") + 1);
      let size = file.size / 1024 / 1024;
      if (extension !== "xlsx") {
        this.$notify.warning({
          title: "警告",
          message: `只能上传Excel 2007以上版本（即后缀是.xlsx）的文件`
        });
      }
      if (size > 10) {
        this.$notify.warning({
          title: "警告",
          message: `文件大小不得超过10M`
        });
      }
    },
    cancelNotDeleteForm() {
      this.tolead = false;
      this.$refs.uploadExcel.clearFiles();
    },
    //员工列表
    getList() {
      staffList(this.listQuery).then(data => {
        this.listLoading = true;
        if (data.status == 200) {
          console.log(data);
          this.list = data.data.data;
          this.total = data.data.totalCount;
          this.listLoading = false;
        }
      });
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },
    //搜索
    handleFilter() {
      this.getList();
    },
    //清空搜索条件
    cleaningQuery() {
      this.listQuery.page = 1;
      this.listQuery.limit = 10;
      this.listQuery.name = "";
      this.listQuery.phone = "";
      this.listQuery.status = "";
      this.getList();
    },
    //新增员工
    addStaff() {
      this.staffTitle == "新增员工"
      this.bulkUploadMember = true;
    },
    //批量导入员工
    toLoad() {
      this.tolead = true;
    },
    //编辑员工
    editorStaff(row) {
      this.activeId = row.id;
      this.staffTitle = "编辑员工";
      this.bulkUploadMember = true;
      this.staffTitleFrom = {
        phone: row.phone,
        name: row.name,
        positionId: row.positionId
      };
    },
    //删除员工
    deleteStaff(row) {
      this.$confirm("确定删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        deleteStaffs(row.id).then(data => {
          if (data.status == 200) {
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success",
              duration: 2000
            });
            this.getList();
          } else {
            this.$notify({
              title: "失败",
              message: "删除失败",
              type: "failed",
              duration: 2000
            });
          }
        });
      });
    },
    //确定
    confirm(formName) {
      if (this.staffTitle == "新增员工") {
        addEditor(this.staffTitleFrom).then(data => {
          if (data.status == 200) {
            this.$notify({
              title: "成功",
              message: "新增成功",
              type: "success",
              duration: 2000
            });
            this.bulkUploadMember = false;
            this.getList();
          }
        });
      } else {
        this.staffTitleFrom.id = this.activeId;
        addEditor(this.staffTitleFrom).then(data => {
          if (data.status == 200) {
            this.$notify({
              title: "成功",
              message: "编辑成功",
              type: "success",
              duration: 2000
            });
            this.bulkUploadMember = false;
            this.getList();
          }
        });
      }
    },
    //身份列表
    postionsFn() {
      postions().then(data => {
        //console.log(data);
        if (data.status == 200) {
          this.postionsList = data.data;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
};
</script>
<style>
.member .el-dialog--small {
  width: 500px;
}
.defeated {
  padding: 0;
}
.defeated li {
  list-style: none;
}
</style>
