<template>
  <div class="div_main">
    <div class="div_search">
      <el-form
        :inline="true"
        :model="dataForm"
        @keyup.enter.native="getDataList()"
      >
        <el-form-item label="所属组织名称" prop="orgName" label-width="130px">
          <el-cascader
            ref="org"
            v-model="orgIds"
            :options="organizationList"
            :props="{ checkStrictly: true, multiple: false, emitPath: true }"
            style="width: 200px"
            clearable
            @change="orgChangeHandle"
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="核酸检测点名称" prop="name">
          <el-input
            v-model="dataForm.name"
            placeholder="核酸检测点名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="咨询电话" prop="mobile">
          <el-input
            v-model="dataForm.mobile"
            placeholder="咨询电话"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            class="diy-button--search"
            size="small"
            @click="getDataList()"
            >{{ $t("query") }}</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button size="small" class="diy-button--reset" @click="resetSearch"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <div class="div_table">
      <div class="exportBtn">
        <el-button
          class="diy-button--add"
          type="primary"
          size="small"
          @click="addOrUpdateHandle('', '新增检测点')"
          >{{ $t("add") }}</el-button
        >
        <el-button
          style="margin-left: 10px"
          class="diy-button--export"
          size="small"
          @click="handleExportModule()"
          >下载模板</el-button
        >

        <el-upload
          style=""
          ref="upload"
          :multiple="false"
          :show-file-list="false"
          :before-upload="
            (file) => {
              beforeUpload(file);
            }
          "
          action=""
          accept=".xls,.xlsx"
          :http-request="
            () => {
              uploadFile();
            }
          "
        >
          <el-button
            style="margin-left: 10px"
            size="small"
            class="diy-button--delete"
            >导入</el-button
          >
        </el-upload>
        <el-button
          style="float: left; margin-left: 10px"
          class="diy-button--reset"
          size="small"
          @click="handleExport"
          >导出</el-button
        >
        <!--<el-button class="diy-button&#45;&#45;reset" style="float:left;margin-left:10px"-->
        <!--size="small" @click="exportHandle()">{{ $t('export') }}</el-button>-->
        <el-button
          style="margin-left: 15px"
          class="diy-button--more"
          size="small"
          @click="handleSendNotice"
          v-if="noticeVisible"
          >发送通知</el-button
        >
      </div>
      <el-table
        v-loading="dataListLoading"
        :data="dataList"
        border
        :header-cell-style="{ background: '#2195FE', color: '#FFFFFF' }"
        style="width: 100%; height: 564px"
        ><el-table-column
          label="序号"
          header-align="center"
          align="center"
          type="index"
          width="50"
        ></el-table-column>
        <el-table-column
          prop="orgName"
          label="所属组织名称"
          header-align="center"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="name"
          label="核酸检测点名称"
          header-align="center"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="serveTime"
          label="服务时间"
          header-align="center"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="mobile"
          label="咨询电话"
          header-align="center"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="address"
          label="检测点地址"
          header-align="center"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          :label="$t('handle')"
          fixed="right"
          header-align="center"
          align="center"
          width="150"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              class="div-table-button--detail"
              @click="addOrUpdateHandle(scope.row.id, '查看')"
              >{{ "查看" }}</el-button
            >
            <el-button
              type="text"
              size="small"
              class="div-table-button--edit"
              @click="addOrUpdateHandle(scope.row.id, '修改')"
              >{{ scope.row.longitude === null ? "待完善" : "修改" }}</el-button
            >
            <el-button
              type="text"
              size="small"
              class="div-table-button--delete--noline"
              @click="handleDelete(scope.row.id)"
              >{{ $t("delete") }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="pageNo"
        :page-sizes="[20, 50, 100, 200]"
        :page-size="pageSize"
        layout="sizes, prev, pager, next, total"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 弹窗, 新增 / 修改 -->
    <el-dialog
      :visible.sync="addOrUpdateVisible"
      :title="dialogTitle"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      width="850px"
      top="5vh"
      custom-class="dialog-h"
    >
      <add-or-update
        ref="addOrUpdate"
        @refreshDataList="getDataList"
        @closeDialog="closeDialog"
        :dialogTitle="dialogTitle"
      ></add-or-update>
    </el-dialog>
    <!-- 发送通知弹出框 -->
    <el-dialog
      :visible.sync="sendNoticeFormShow"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="发送通知"
      width="850px"
      top="5vh"
      class="dialog-h"
      @closed="diaClose"
      :destroy-on-close="true"
    >
      <icpoint-noice
        ref="ref_sendnotice"
        @diaClose="diaClose"
        :noticeOrigin="noticeOrigin"
      ></icpoint-noice>
    </el-dialog>
  </div>
</template>

<script>
import mixinViewModule from "@/mixins/view-module";
import AddOrUpdate from "./icpointnucleicmonitoring-add-or-update";
import icpointNoice from "./icpointNoice";
import { requestPost } from "@/js/dai/request";
export default {
  mixins: [mixinViewModule],
  data() {
    return {
      dataForm: {
        name: "",
        mobile: "",
        orgId: "",
      },
      organizationList: [],
      orgIds: [],
      dialogTitle: "",
      sendNoticeFormShow: false,
      noticeVisible: false,
      noticeOrigin: "3",
      pageSize: 20,
      pageNo: 0,
      total: 0,
    };
  },
  components: {
    AddOrUpdate,
    icpointNoice,
  },
  created() {
    this.noticeFun();
    this.getFormInfo();
  },
  methods: {
    async loadTable() {
      this.dataListLoading = true;
      const url = "/epmetuser/icPointNucleicMonitoring/page";
      let params = {
        limit: this.pageSize,
        page: this.pageNo,
      };
      const { data, code, msg } = await requestGet(url, params);

      if (code === 0) {
        console.log(data.list);
        this.dataList = data.list;
        this.total = data.total;
      } else {
        this.$message.error(msg);
      }
      this.dataListLoading = false;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.pageNo = 1;
      this.loadTable();
    },
    handleCurrentChange(val) {
      this.pageNo = val;
      this.loadTable();
    },
    async handleDelete(id) {
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.deleteNat(id);
        })
        .catch((err) => {
          if (err == "cancel") {
          }
        });
    },
    async deleteNat(id) {
      const url = "/epmetuser/icPointNucleicMonitoring/delete";
      let params = [id];
      const { data, code, msg } = await requestPost(url, params);
      if (code === 0) {
        this.$message({
          type: "success",
          message: "删除成功",
        });
        this.getDataList();
      } else {
        this.$message.error(msg);
      }
    },
    //导出表格
    async handleExport() {
      let title = "核酸检测点";

      const url = "/epmetuser/icPointNucleicMonitoring/point-export";

      app.ajax.exportFilePost(
        url,
        this.dataForm,
        (data, rspMsg) => {
          this.download(data, title + ".xlsx");
        },
        (rspMsg, data) => {
          this.$message.error(rspMsg);
        }
      );
    },
    //重置搜索条件
    resetSearch() {
      this.dataForm = {
        name: "",
        mobile: "",
        orgId: "",
      };
      this.pageNo = 1;
      this.orgIds = [];
    },
    // 发送通知
    handleSendNotice() {
      this.sendNoticeFormShow = true;
    },
    // 关闭通知
    diaClose() {
      this.sendNoticeFormShow = false;
    },
    // 新增 / 修改
    addOrUpdateHandle(id, title) {
      this.dialogTitle = title;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.dataForm.id = id;
        this.$refs.addOrUpdate.init();
      });
      this.addOrUpdateVisible = true;
    },
    // 关闭弹窗
    closeDialog() {
      this.addOrUpdateVisible = false;
      this.dialogTitle = "";
    },
    // 获取所属组织列表
    getFormInfo() {
      this.$http
        .post(`/gov/org/agency/getOrgTreeListByCustomerId`)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.organizationList = res.data;
          this.deleteChildren(this.organizationList);
        })
        .catch(() => {});
    },
    // 获取发送通知按钮显示与隐藏
    noticeFun() {
      this.$http
        .post(`/epmetuser/icPointNucleicMonitoring/getShowType`)
        .then(({ data: res }) => {
          if (res.code === 0 && res.data) {
            this.noticeVisible = true;
          }
        })
        .catch(() => {});
    },
    deleteChildren(arr) {
      let childs = arr;
      for (let i = childs.length; i--; i > 0) {
        if (childs[i].children) {
          if (childs[i].children.length) {
            this.deleteChildren(childs[i].children);
          } else {
            delete childs[i].children;
          }
        }
      }
      return arr;
    },
    orgChangeHandle() {
      this.dataForm.orgId = this.orgIds[this.orgIds.length - 1];
      console.log(this.dataForm);
    },
    handleExportModule() {
      let title = "核酸检测点模板";
      let url = "/epmetuser/icPointNucleicMonitoring/exporttemplate";

      let params = {};

      app.ajax.exportFilePost(
        url,
        params,
        (data, rspMsg) => {
          this.download(data, title + ".xls");
        },
        (rspMsg, data) => {
          this.$message.error(rspMsg);
        }
      );
    },
    // 下载文件
    download(data, fileName) {
      if (!data) {
        return;
      }

      var csvData = new Blob([data]);

      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(csvData, fileName);
      }
      // for Non-IE (chrome, firefox etc.)
      else {
        var a = document.createElement("a");
        document.body.appendChild(a);
        a.style = "display: none";
        var url = window.URL.createObjectURL(csvData);
        a.href = url;
        a.download = fileName;
        a.click();
        a.remove();
        window.URL.revokeObjectURL(url);
      }
    },
    // 上传文件之前的钩子
    beforeUpload(file) {
      this.files = file;

      const isText = file.type === "application/vnd.ms-excel";
      const isTextComputer =
        file.type ===
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

      if (!isText && !isTextComputer) {
        this.$message.error("请选择正确格式的文件");
        this.files = null;
        this.fileName = "";
        return false;
      } else {
        this.fileName = file.name;
        return true;
      }
    },
    async uploadFile() {
      if (this.fileName == "") {
        this.$message.warning("请选择要上传的文件！");
        return false;
      }

      this.$message({
        showClose: true,
        message: "导入中，请到系统管理-导入记录中查看进度",
        duration: 0,
      });

      //清空上传列表
      this.$refs["upload"].clearFiles();
      let url = "";

      let fileFormData = new FormData();
      fileFormData.append("file", this.files); //filename是键，file是值，就是要传的文件，test.zip是要传的文件名

      url = "/epmetuser/icPointNucleicMonitoring/pointImport";

      window.app.ajax.post2(
        url,
        fileFormData,
        (data, rspMsg) => {
          if (data.code === 0 && data.msg == "success") {
            // this.$message.success('导入成功')
          } else {
            // this.$message({
            //   showClose: true,
            //   message: rspMsg,
            //   duration: 0,
            //   type: "error"
            // })
            // this.$message.error(rspMsg)
          }
          this.loadTable();
        },
        (rspMsg, data) => {},
        { headers: { "Content-Type": "multipart/form-data" } }
      );
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/assets/scss/modules/visual/communityManage.scss";
@import "@/assets/scss/modules/management/list-main.scss";
.exportBtn {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  margin-top: 10px;
  margin-left: 10px;
}
.div_left_table {
  margin-top: 10px;
  margin-left: 15px;
  background-color: #ffffff;
  border-radius: 5px;
  padding: 10px;
}
.dialog-h >>> .el-dialog__body {
  overflow: scroll;
}
</style>
