<template>
  <div class="fullHeight whiteBlock">
    <div style="padding: 15px 15px 0">
      <el-form :inline="true" ref="searchForm" :model="searchForm" size="medium">
        <el-form-item label="桥位环链编号">
          <el-input v-model="searchForm.institutionName" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.dateRangeArr" placeholder="请选择">
            <el-option
              v-for="item in stateList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传时间">
          <el-date-picker
            v-model="searchForm.dateRangeArr"
            type="datetimerange"
            value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']"
            :range-separator="$t('message.sixComplete.to')"
            :start-placeholder="$t('message.sixComplete.start')"
            :end-placeholder="$t('message.sixComplete.end')"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain @click="getList">{{
            $t("message.energyManage.waybill.query")
          }}</el-button>
          <el-button type="warning" plain @click="refresh">{{
            $t("message.deviceManage.refresh")
          }}</el-button>
          <el-button type="primary" size="medium" @click="isAdd(1)">新增</el-button>
          <el-button
            :disabled="$refs.multipleTable && $refs.multipleTable.selection.length == 0"
            :type="
              $refs.multipleTable && $refs.multipleTable.selection.length == 0
                ? 'info'
                : 'danger'
            "
            class="delete_btn"
            plain
            @click="deleteAttendanceBatch"
            >删除</el-button
          >
          <el-button
            class="border-radius_3"
            @click="exportBtnTemplateDetail"
            type="primary"
            plain
            >下载模版</el-button
          >
          <div class="upload-btn">
            <el-upload
              class="upload-demo"
              name="excelFile"
              :action="
                $http.defaults.baseURL + 'xmgl/riskListPotentialAccidentType/importExcel'
              "
              :on-change="handleChangeE"
              :on-success="handleSuccessE"
              :on-error="handleErrorE"
              :show-file-list="false"
              :headers="headers"
              :data="{ sn: $store.state.userInfo.sn }"
              :limit="1"
              accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
              :auto-upload="true"
            >
              <!-- 批量导入 -->
              <el-button type="primary" class="border-radius_3">导入</el-button>
            </el-upload>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="table_wrap whiteBlock">
      <el-table class="tables" ref="multipleTable" :data="List">
        <el-table-column type="selection" align="center" width="55"></el-table-column>
        <el-table-column
          prop="institutionName"
          label="桥位环链编号"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="institutionalPhone"
          align="center"
          label="完成状态"
        ></el-table-column>
        <el-table-column prop="remark" align="center" label="日期"></el-table-column>
        <el-table-column width="220" label="操作" align="center">
          <template slot-scope="scope">
            <div class="tableBtns">
              <div @click="edit(2, scope.row)" class="operationText">
                <img src="@/assets/images/icon-edit.png" width="15px" height="15px" />
                <span>编辑</span>
              </div>
              <div @click="deleteDev(scope.row)" class="operationText">
                <img src="@/assets/images/icon-delete.png" width="15px" height="15px" />
                <span>删除</span>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagerBox"
        @size-change="SizeChange"
        @current-change="CurrentChange"
        :current-page="pagInfo.pageNo"
        :page-sizes="$store.state.PAGESIZRS"
        :page-size="pagInfo.pageSize"
        layout="total, sizes, prev, pager, next"
        :total="Number(pagInfo.total)"
        background
      ></el-pagination>
    </div>
    <el-dialog
      :modal-append-to-body="false"
      @close="close"
      :title="title"
      :visible.sync="dialogShow"
      width="667px"
    >
      <div class="dialog_content">
        <el-form
          size="medium"
          ref="addEditForm"
          :model="addEditForm"
          :rules="addEditRules"
          label-width="120px"
          class="dialogFormBox"
        >
          <el-form-item label="桥位环链编号" prop="institutionName">
            <el-input
              v-model="addEditForm.institutionName"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          
          <el-form-item label="状态" prop="remark">
            <el-select v-model="addEditForm.dateRangeArr" placeholder="请选择">
              <el-option
                v-for="item in stateList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="日期" prop="remark">
            <el-date-picker
              v-model="addEditForm.date"
              type="datetime"
              placeholder="选择日期"
              value-format="yyyy-MM-dd HH:mm:ss"
            >
            </el-date-picker>
          </el-form-item>
          <div class="dialog-footer">
            <el-button
              class="cancleBtn"
              @click="dialogShow = false"
              icon="el-icon-circle-close"
              size="medium"
              >{{ $t("message.deviceManage.cancel") }}
            </el-button>
            <el-button
              type="primary"
              icon="el-icon-circle-check"
              @click="submit"
              size="medium"
              >{{ $t("message.deviceManage.save") }}
            </el-button>
          </div>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  addgtMaterialTestingInstitutionApi,
  deletgtMaterialTestingInstitutionApi,
  editgtMaterialTestingInstitutionApi,
  gettgtMaterialTestingInstitutionApi,
} from "@/assets/js/api/materialManagement.js";
export default {
  mounted() {
    this.getList();
  },
  data() {
    return {
      title: "",
      dialogShow: false,
      pagInfo: {
        pageNo: 1, //页数
        pageSize: 10, //条数
        total: 0, //总条数
      },
      List: [],
      addEditForm: {
        institutionName: "",
        institutionalAddress: "",
        institutionalPhone: "",
        remark: "",
      },
      addEditRules: {
        institutionName: [
          {
            required: true,
            message: "必填",
            trigger: "blur",
          },
        ],
      },
      searchForm: {
        institutionName: "",
      },
      stateList: [
        {
          value: "1",
          label: "已完成",
        },
        {
          value: "2",
          label: "未完成",
        },
      ],
    };
  },
  methods: {
    handleChangeE(file, fileList) {
      if (file.raw) {
        if (
          file.raw.type ==
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
          file.raw.type == "application/vnd.ms-excel"
        ) {
        } else {
          this.$message.error(this.$t("message.laborMange.hint5"));
        }
      }
    },
    handleSuccessE(file) {
      console.log("==========", file);
      if (file.code == 200) {
        this.$message.success(file.message); //导入成功
        this.queryBtn();
      } else {
        this.$message.error(file.message);
      }
    },
    handleErrorE() {
      this.$message.error(this.$t("message.laborMange.hint7"));
      this.queryBtn();
    },
    // 导出模版风险详情
    exportBtnTemplateDetail() {
      fetch(
        this.$http.defaults.baseURL +
          `xmgl/riskListDetail/downloadTemplate?sn=${this.$store.state.userInfo.sn}&libraryId=${this.riskListDetailInfo.id}`,
        {
          method: "get",
          headers: {
            Authorization: this.$store.state.userInfo.token,
            "Content-Type": "application/json", // 设置请求头的内容类型为JSON
          },
          // body: JSON.stringify(data) // 将data对象转换为JSON字符串并作为请求体发送
        }
      )
        .then((response) => {
          // 处理响应
          if (!response.ok) {
            throw new Error("下载失败");
          }
          return response.blob();
        })
        .then((blob) => {
          // 创建一个下载链接
          const url = window.URL.createObjectURL(blob);
          // 创建一个<a>元素
          const link = document.createElement("a");
          link.href = url;
          link.download = "风险清单库详情.xlsx"; // 指定下载文件的文件名
          // 模拟点击下载链接
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          // 释放URL对象
          window.URL.revokeObjectURL(url);
          // 处理导出的文件
          // 这里可以使用blob对象来获取导出的文件内容或者将其保存到本地
        })
        .catch((error) => {
          // 处理错误
          console.error(error);
        });
    },
    // 批量删除考勤人员
    deleteAttendanceBatch() {
      if (this.$refs.multipleTable.selection.length === 0)
        return this.$message.warning("请勾选需要删除的数据！");
      this.$confirm("删除后操作不可恢复，请谨慎操作！", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const ids = this.$refs.multipleTable.selection.map((item) => item.id).join(",");
          console.log(this.$refs.multipleTable.selection);
          deleteBatchRiskListDetailApi({ ids }).then((res) => {
            this.queryBtn();
          });
        })
        .catch(() => {});
    },
    //查询仓库数据
    getList() {
      gettgtMaterialTestingInstitutionApi({
        pageNo: this.pagInfo.pageNo,
        pageSize: this.pagInfo.pageSize,
        projectSn: this.$store.state.projectSn,
        institutionName: this.searchForm.institutionName,
      }).then((result) => {
        if (result.success) {
          this.List = result.result.records;
          this.pagInfo.total = result.result.total;
        }
      });
    },

    isAdd(type, obj) {
      if (type == 1) {
        this.title = "新增";
        this.close();
      } else if (type == 2) {
        this.title = "编辑";
        this.addEditForm = JSON.parse(JSON.stringify(obj));
      }

      this.dialogShow = true;
    },
    submit() {
      let params = JSON.parse(JSON.stringify(this.addEditForm));
      params.projectSn = this.$store.state.projectSn;
      this.$refs.addEditForm.validate((valid) => {
        if (valid) {
          if (this.title == "新增") {
            addgtMaterialTestingInstitutionApi(params).then((result) => {
              if (result.success) {
                this.$message.success(result.message);
                this.getList();
              }
            });
          } else if (this.title === "编辑") {
            editgtMaterialTestingInstitutionApi(params).then((result) => {
              if (result.success) {
                this.$message.success(result.message);
                this.getList();
              }
            });
          }
          this.dialogShow = false;
        } else {
          return false;
        }
      });
    },
    deleteDev(obj) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deletgtMaterialTestingInstitutionApi({ id: obj.id }).then((res) => {
            if (res.success) {
              this.getList();
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            } else {
              this.$message({
                type: "error",
                message: res.message,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    close() {
      this.addEditForm = {};
      this.$nextTick(() => {
        this.$refs.addEditForm.clearValidate();
      });
    },
    SizeChange(val) {
      this.pagInfo.pageSize = val;
      this.getList();
    },
    CurrentChange(val) {
      this.pagInfo.pageNo = val;
      this.getList();
    },
    refresh() {
      this.searchForm = {};
      this.pagInfo.pageNo = 1; //页数
      this.pagInfo.pageSize = 10; //条数
      this.getList();
    },
  },
  computed: {
    headers() {
      return {
        Authorization: this.$store.state.userInfo.token,
      };
    },
  },
};
</script>
<style lang="less" scoped>
.el-date-editor {
  width: 360px;
}
.pagerBox {
  margin-top: 30px;
}
.table_wrap {
  height: calc(100% - 131px);
}
.tables {
  min-height: 550px;
  max-height: 550px;
}
.upload-btn {
  margin: 0 15px;
  display: inline-block;
}
</style>
