<template>
  <div class="app-container">
    <!-- 查询和其他操作-->
    <div class="filter-container">
      <el-input
        v-model="listQuery.name"
        clearable
        class="filter-item"
        style="width: 200px;"
        placeholder="请输入姓名"
      />
      <el-input
        v-model="listQuery.tel"
        clearable
        class="filter-item"
        style="width: 200px;"
        maxlength="11"
        placeholder="请输入电话"
      />
      <el-select v-model="listQuery.state" class="filter-item" placeholder="请选择状态">
        <el-option label="开启" :value="1" />
        <el-option label="关闭" :value="2" />
      </el-select>
      <el-button
        v-permission="['GET /admin/orderBrushPerson/getPageList']"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >查找</el-button>
      <el-button
        v-permission="['POST /admin/orderBrushPerson/add']"
        class="filter-item"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreate"
      >添加</el-button>
      <el-button
        v-permission="['POST /admin/orderBrushPerson/importBrushPerson']"
        class="filter-item"
        type="primary"
        icon="el-icon-upload"
        @click="importVisible = true"
      >导入</el-button>
      <a
        href="https://servant.lifejingzhi.com/file/jzmall/brush.xlsx"
        rel="external nofollow"
        download="模板"
      >
        <el-button size="small" type="success" class="filter-item" icon="el-icon-download">下载模板</el-button>
      </a>
    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="姓名" prop="name" />

      <el-table-column align="center" label="手机号" prop="tel" />

      <el-table-column align="center" label="状态" prop="state">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.state==1">开启</el-tag>
          <el-tag type="warning" v-if="scope.row.state==2">关闭</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="创建时间" prop="createTime" />
      <el-table-column align="center" label="创建人" prop="createUserName" />
      <el-table-column align="center" label="更新时间" prop="updateTime" />
      <el-table-column align="center" label="更新人" prop="updateUserName" />

      <el-table-column
        align="center"
        label="操作"
        min-width="100"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-permission="['POST /admin/orderBrushPerson/update']"
            type="primary"
            size="mini"
            @click="handleUpdate(scope.row)"
          >编辑</el-button>
          <!-- <el-button v-permission="['POST /admin/city/delete']" type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 500px; margin-left:50px;"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="dataForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="tel">
          <el-input
            v-model="dataForm.tel"
            type="text"
            maxlength="11"
            show-word-limit
            placeholder="请输入手机号"
            :disabled="dialogStatus == 'update'"
          />
        </el-form-item>

        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="dataForm.state">
            <el-radio :label="1">开启</el-radio>
            <el-radio :label="2">关闭</el-radio>
          </el-radio-group>
        </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 :visible.sync="importVisible" title="批量导入">
      <el-form
        ref="importForm"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 800px; margin-left:50px;"
      >
        <div style="color:red;margin:10px 0">导入excel格式:刷单人姓名，手机号，状态</div>
        <el-row>
          <el-col :span="12">
            <el-form-item label="excel导入">
              <input id="im" type="file" @change="getFile($event)" ref="file" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-button
              v-permission="['POST /admin/orderBrushPerson/importBrushPerson']"
              class="filter-item"
              type="primary"
              icon="el-icon-upload2"
              @click="importConfirm"
            >导入</el-button>
          </el-col>
        </el-row>
      </el-form>
      <div v-html="importResult"></div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="importVisible = false">确定</el-button>
      </div>
    </el-dialog>

    <el-tooltip placement="top" content="返回顶部">
      <back-to-top :visibility-height="100" />
    </el-tooltip>
  </div>
</template>

<style>
.el-table th.gutter {
  display: table-cell !important;
}
.el-dialog {
  width: 800px;
}
</style>

<script>
import {
  brushList,
  brushAdd,
  brushUpdate,
  importBrushPerson
} from "@/api/brush";
import { getShop } from "@/api/goods";
import BackToTop from "@/components/BackToTop";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
import _ from "lodash";

export default {
  name: "Topic",
  components: { BackToTop, Pagination },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 20,
        tel: "",
        name: "",
        state: ""
      },
      dataForm: {
        name: "",
        tel: "",
        state: 1
      },
      shops: [],
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "创建"
      },
      rules: {
        name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
        tel: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          {
            pattern: /^1\d{10}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        state: [{ required: true, message: "状态不能为空", trigger: "blur" }]
      },
      file: "",
      importResult: "",
      importVisible: false
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.listLoading = true;
      brushList(this.listQuery)
        .then(res => {
          this.list = res.data.data.list;
          this.total = res.data.data.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });
    },

    handleFilter() {
      this.listQuery.pageNum = 1;
      this.getList();
    },
    handleCreate() {
      this.resetForm();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    resetForm() {
      this.dataForm = {
        name: "",
        tel: "",
        state: 1
      };
    },
    createData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          brushAdd(this.dataForm)
            .then(response => {
              this.dialogFormVisible = false;
              this.$notify.success({
                title: "成功",
                message: "创建成功"
              });
              this.getList();
            })
            .catch(response => {
              this.$notify.error({
                title: "失败",
                message: response.data.errmsg
              });
            });
        }
      });
    },
    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) {
          brushUpdate(this.dataForm)
            .then(() => {
              this.dialogFormVisible = false;
              this.$notify.success({
                title: "成功",
                message: "更新成功"
              });
              this.getList();
            })
            .catch(response => {
              this.$notify.error({
                title: "失败",
                message: response.data.errmsg
              });
            });
        }
      });
    },
    getFile: function(event) {
      this.file = event.target.files[0];
      console.log(this.file);
    },
    importConfirm() {
      if (!this.file) {
        this.$message.warning("请选择文件！");
        return;
      }
      if (
        this.file.name.lastIndexOf("xlsx") < 0 ||
        this.file.name.lastIndexOf("xls") < 0
      ) {
        this.$message.warning("请选择excel文件！");
        return;
      }

      const loading = this.$loading({
        lock: true,
        text: "文件导入中，请耐心等待...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      var formData = new window.FormData(); // vue 中使用 window.FormData(),否则会报 'FormData isn't definded'
      formData.append("file", this.file);

      importBrushPerson(formData)
        .then(res => {
          console.log("导入返回数据", res);
          // let element = document.getElementById("im");
          // element.outerHTML=element.outerHTML;

          this.$refs.file.value = null;
          this.file = null;

          loading.close();
          if (res.data.errno == 0) {
            this.$message.success(res.data.errmsg);
            console.info(res.data.data);
            if (res.data.data == "") {
              this.importVisible = false;
            } else {
              this.importResult = res.data.data;
            }

            this.getList();
          } else {
            this.$message.warning(res.data.errmsg);
          }
        })
        .catch(err => {
          this.$refs.file.value = null;
          this.file = null;

          loading.close();
          this.$message.warning(err.data.errmsg);
        });
    }
  }
};
</script>
