<template>
  <div class="app-container">
    <!--搜索区-->

    <el-button
      type="primary"
      icon="el-icon-plus"
      class="margin-left"
      @click="addOrUpdate('add')"
      >添加</el-button
    >
    <el-button
      type="primary"
      icon="el-icon-download"
      @click="download"
      class="margin-left"
      >下载模板</el-button
    >
    <!-- v-if="checkRole([2])" -->
    <el-button
      type="primary"
      @click="addOrUpdate('upload')"
      class="margin-left"
      v-if="checkRole([1, 2])"
      plain
      >批量导入</el-button
    >
    <a href="javascript:;" v-if="checkRole([5])" class="file margin-sm"
      >批量导入<input
        type="file"
        name="file"
        ref="file"
        @change="chooseFile($event)"
    /></a>
    <el-button
      type="danger"
      @click="addOrUpdate('delete')"
      class="margin-left"
      v-if="checkRole([1, 2])"
      plain
      >批量删除</el-button
    >
    <!-- @change="upload($event)" -->
    <el-input
      v-model="page.data.controlName"
      placeholder="请输入布控人姓名"
      class="margin-left input"
    ></el-input>
    <el-input
      v-model="page.data.controlPhone"
      placeholder="请输入布控人手机号"
      class="margin-left input"
    ></el-input>

    <el-input
      v-model="page.data.controlUnit"
      placeholder="请输入布控人单位"
      class="margin-left input"
    ></el-input>
    <el-input
      v-model="page.data.earlyWarningName"
      placeholder="请输入预警人员姓名"
      class="margin-left input"
    ></el-input>
    <el-input
      v-model="page.data.earlyWarningIdNumber"
      placeholder="请输入预警人员证件号"
      class="margin-left input"
    ></el-input>
    <el-button
      type="primary"
      icon="el-icon-search"
      class="margin-left"
      @click="fetchData"
      >搜索</el-button
    >

    <!--主表格-->
    <el-table
      class="table"
      ref="table_form"
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column label="序号" align="center" width="80px">
        <template slot-scope="scope">
          {{ indexMethod(scope.$index) }}
        </template>
      </el-table-column>
      <el-table-column label="账号名称" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.username | matchNull }}</span>
        </template>
      </el-table-column>
      <el-table-column label="布控人姓名" align="center">
        <template slot-scope="scope">
          {{ scope.row.controlName | matchNull }}
        </template>
      </el-table-column>
      <el-table-column label="布控人手机号" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.controlPhone | matchNull }}</span>
        </template>
      </el-table-column>
      <el-table-column label="布控人单位" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.controlUnit | matchNull }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预警人员姓名" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.earlyWarningName | matchNull }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预警人员证件号" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.earlyWarningIdNumber | matchNull }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="" label="操作区" width="160">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="small"
            @click="addOrUpdate('update', scope.row)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            size="small"
            @click="deleteUser(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!--分页栏-->
    <pagination
      :total="total"
      :page.sync="page.pageNum"
      :limit.sync="page.pageSize"
      @pagination="fetchData"
    />
    <!--添加、编辑对话框-->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="40%">
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        label-width="120px"
        label-position="left"
      >
        <el-form-item label="绑定账号" prop="adminId">
          <el-select
            filterable
            clearable
            v-model="form.adminId"
            placeholder="请选择账号"
          >
            <el-option
              v-for="item in user_list"
              :key="item.adminId"
              :label="item.username"
              :value="item.adminId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="布控人姓名" prop="controlName">
          <el-input v-model.trim="form.controlName" />
        </el-form-item>
        <el-form-item label="布控人手机号" prop="controlPhone">
          <el-input
            maxlength="11"
            show-word-limit
            v-model.trim="form.controlPhone"
          />
        </el-form-item>
        <el-form-item label="布控人单位" prop="controlUnit">
          <el-input
            maxlength="50"
            show-word-limit
            v-model.trim="form.controlUnit"
          />
        </el-form-item>
        <el-form-item label="预警人员姓名" prop="earlyWarningName">
          <el-input v-model.trim="form.earlyWarningName" />
        </el-form-item>
        <el-form-item label="预警人员证件号" prop="earlyWarningIdNumber">
          <el-input v-model.trim="form.earlyWarningIdNumber" />
        </el-form-item>
      </el-form>

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

    <!--批量导入对话框-->
    <el-dialog title="批量导入" :visible.sync="dialogVisibleUpload" width="40%">
      <el-form
        :model="form_upload"
        :rules="rules_upload"
        ref="form_upload"
        label-width="120px"
        label-position="left"
      >
        <el-form-item label="绑定账号" prop="adminId">
          <el-select
            filterable
            clearable
            v-model="form_upload.adminId"
            placeholder="请选择账号"
          >
            <el-option
              v-for="item in user_list"
              :key="item.adminId"
              :label="item.username"
              :value="item.adminId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传文件" prop="file">
          <a href="javascript:;" class="file"
            >{{ form_upload.file ? form_upload.file.name : "选择文件"
            }}<input
              type="file"
              name="file"
              ref="file"
              @change="chooseFile($event)"
          /></a>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleUpload = false"> 取消 </el-button>
        <el-button type="primary" @click="upload"> 确定 </el-button>
      </div>
    </el-dialog>
    <!--批量删除对话框-->
    <el-dialog title="批量删除" :visible.sync="dialogVisibleDelete" width="40%">
      <el-form
        :model="form_delete"
        :rules="rules_delete"
        ref="form_delete"
        label-width="120px"
        label-position="left"
      >
        <el-form-item label="布控人单位" prop="adminId">
          <el-select
            filterable
            clearable
            multiple
            remote
            v-model="form_delete.adminId"
            placeholder="请选择布控人单位"
          >
            <el-option
              v-for="item in user_list"
              :key="item.adminId"
              :label="item.username"
              :value="item.adminId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择时间" prop="file">
          <el-date-picker
      v-model="form_delete.file"
      type="datetimerange"
      range-separator="至"
      start-placeholder="开始日期"
      end-placeholder="结束日期">
    </el-date-picker>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleDelete = false"> 取消 </el-button>
        <el-button type="primary" @click="batchDelete"> 确定 </el-button>
      </div>
    </el-dialog>
    <!--错误返回-->
    <el-dialog
      title="提示"
      center
      :visible.sync="resultVisible"
      destroy-on-close
    >
      <el-table
        class="table"
        ref="table_form_result"
        v-loading="false"
        :data="result_list"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
        height="500"
      >
        <el-table-column label="错误序号" align="center" width="100px">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="错误描述" align="center">
          <template slot-scope="scope">
            {{ scope.row | matchNull }}
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="resultVisible = false">
          我已知晓
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUserListSearch } from "@/api/user_manage";
import {
  userControlEarlyWarningListExcel,
  getPageList,
  addOrUpdate,
  deleteWarning,
} from "@/api/monitor_management";
import Pagination from "@/components/Pagination";
import { checkRole } from "@/utils/checkRole";

export default {
  components: { Pagination },
  filters: {
    matchNull(str) {
      if (!str) {
        return "未填写";
      } else {
        return str;
      }
    },
  },
  data() {
    return {
      formData: new FormData(),
      // 主表格&主表格加载状态
      list: [],
      listLoading: true,
      // 分页参数
      page: {
        data: {
          controlName: null,
          controlPhone: null,
          controlUnit: null,
          earlyWarningIdNumber: null,
          earlyWarningName: null,
        },
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      dialogVisible: false,
      dialogVisibleUpload: false,
      dialogTitle: "添加",
      // 账号列表_搜索
      user_list: [],
      form: {
        id: null,
        controlName: null,
        controlPhone: null,
        controlUnit: null,
        earlyWarningName: null,
        earlyWarningIdNumber: null,
      },
      form_copy: {},
      // 验证规则
      rules: {
        adminId: [{ required: true, message: "请选择账号", trigger: "change" }],
        controlName: [
          { required: true, message: "请输入布控人姓名", trigger: "blur" },
        ],
        controlPhone: [
          { required: true, message: "请输入布控人手机号", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "手机号格式错误",
          },
        ],
        controlUnit: [
          { required: true, message: "请输入布控人单位", trigger: "blur" },
          {
            min: 2,
            max: 50,
            message: "长度在 2 到 50 个字符",
            trigger: "blur",
          },
        ],
        // earlyWarningName: [
        //   { required: true, message: "请输入预警人员姓名", trigger: "blur" },
        // ],
        earlyWarningIdNumber: [
          { required: true, message: "请输入预警人员证件号", trigger: "blur" },
        ],
      },
      // 批量导入
      form_upload: {
        adminId: null,
        file: null,
      },
      // 验证规则--批量导入
      rules_upload: {
        adminId: [{ required: true, message: "请选择账号", trigger: "blur" }],
        file: [{ required: true, message: "请上传文件", trigger: "blur" }],
      },
      // 修改本行数据
      row: null,
      showDialogVisible: false, //是否显示弹框
      // 批量导入错误列表
      result_list: [],
      resultVisible: false,
      // 批量删除
      dialogVisibleDelete: false,
      form_delete: {
        adminId: null,
        file: null,
      },
      rules_delete: {
        adminId: [
          { required: true, message: "请选择布控人单位", trigger: "blur" },
        ],
        file: [{ required: true, message: "请选择时间", trigger: "blur" }],
      },
    };
  },
  created() {
    this.form_copy = JSON.parse(JSON.stringify(this.form));
    this.form_upload_copy = JSON.parse(JSON.stringify(this.form_upload));
    this.form_delete_copy = JSON.parse(JSON.stringify(this.form_delete));
    this.fetchData();
    this.getUserListSearch();
  },
  methods: {
    // 查询权限
    checkRole,
    // 获取列表数据
    fetchData() {
      this.listLoading = true;
      getPageList(this.page).then((res) => {
        console.log(res);
        this.list = res.data.list;
        this.total = res.data.total;
        this.listLoading = false;
      });
    },
    // 下载模板
    download() {
      window.location.href =
        process.env.VUE_APP_BASE_API + "/excel/airportWarning.xlsx";
    },
    // 选择文件
    chooseFile(e) {
      var files = e.currentTarget.files;
      if (!files.length) {
        return;
      }
      this.form_upload.file = files[0];
      if (!checkRole([1, 2])) {
        this.upload();
      }
    },
    upload() {
      let isUpload = false;
      if (!checkRole([1, 2])) {
        isUpload = true;
      } else {
        this.$refs.form_upload.validate((valid) => {
          isUpload = valid;
        });
      }
      if (isUpload) {
        const loading = this.$loading({
          lock: true,
          text: "拼命导入中...",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
        var formData = new FormData();
        formData.append("file", this.form_upload.file);
        if (checkRole([1, 2])) {
          formData.append("adminId", this.form_upload.adminId);
        } else {
          formData.append("adminId", this.$store.getters.adminId);
        }
        userControlEarlyWarningListExcel(formData)
          .then((res) => {
            loading.close();
            this.fetchData();
            if (res.data.length > 0) {
              this.resultVisible = true;
              this.result_list = res.data;
            } else {
              this.dialogVisibleUpload = false;
              this.$message({
                type: "success",
                message: "导入成功!",
              });
            }
          })
          .catch((err) => {
            loading.close();
            this.fetchData();
          });
      }
    },
    // 获取账号列表数据_搜索
    getUserListSearch() {
      getUserListSearch().then((res) => {
        this.user_list = res.data;
      });
    },
    // 添加/修改/批量删除
    addOrUpdate(type, row) {
      if (type === "add") {
        this.dialogTitle = "添加";
        this.form = JSON.parse(JSON.stringify(this.form_copy));
        this.clearValidate(1);
      } else if (type === "update") {
        this.dialogTitle = "编辑";
        this.row = row;
        this.form = Object.assign(this.form, row);
        this.form.adminId = +this.row.adminId;
        this.clearValidate(1);
      } else if (type === "upload") {
        this.form_upload = JSON.parse(JSON.stringify(this.form_upload_copy));
        this.clearValidate(2);
      } else if (type === "delete") {
        this.form_delete = JSON.parse(JSON.stringify(this.form_delete_copy));
        this.clearValidate(3);
      }
    },
    // 清除验证规则
    clearValidate(type) {
      switch (type) {
        case 1:
          this.dialogVisible = true;
          this.$nextTick(() => {
            this.$refs["form"].clearValidate();
          });
          break;
        case 2:
          this.dialogVisibleUpload = true;
          this.$nextTick(() => {
            this.$refs["form_upload"].clearValidate();
          });
          break;
        case 3:
          this.dialogVisibleDelete = true;
          this.$nextTick(() => {
            this.$refs["form_delete"].clearValidate();
          });
          break;
        default:
          break;
      }
    },
    // 确认添加/修改
    sure() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.dialogTitle === "编辑") {
            this.form.id = this.row.id;
            console.log(this.form.adminId);
          }
          addOrUpdate(this.form).then((res) => {
            this.dialogVisible = false;
            this.fetchData();
            this.$message({
              type: "success",
              message: "添加成功!",
            });
          });
        }
      });
    },
    // 删除账号
    deleteUser(id) {
      console.log(id);
      this.$confirm("确定要删除此账号吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      }).then(() => {
        deleteWarning(id).then((res) => {
          this.fetchData();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        });
      });
    },
    // 批量删除
    batchDelete() {},
    // 返回列表序号
    indexMethod(index) {
      return (this.page.pageNum - 1) * this.page.pageSize + index + 1;
    },
  },
};
</script>
<style scoped>
.table {
  margin-top: 15px;
}

.flex {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.margin-left {
  margin: 10px 0 0 10px;
}

.input {
  width: 200px;
}
/*批量导入按钮*/
.file {
  position: relative;
  background: #d0eeff;
  border: 1px solid #99d3f5;
  border-radius: 4px;
  padding: 10px 20px;
  box-sizing: border-box;
  overflow: hidden;
  color: #1e88c7;
  text-decoration: none;
  text-indent: 0;
}
.margin-sm {
  margin: 10px 0 0 10px;
}

.file input {
  position: absolute;
  font-size: 14px;
  width: 106px;
  height: 40px;
  left: 0;
  top: 0;
  opacity: 0;
  cursor: pointer;
}

.file:hover {
  background: #aadffd;
  border-color: #78c3f3;
  color: #004974;
  text-decoration: none;
}
</style>
