<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="位号" prop="devNo">
        <el-input
          v-model="queryParams.devNo"
          placeholder="请输入位号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="年月" prop="yearMonth">
        <el-date-picker
          v-model="queryParams.yearMonth"
          type="month"
          placeholder="选择年月"
          clearable
          size="small"
          value-format="yyyy-MM"
          style="width: 150px"
          @change="handleYearMonthChange"
        />
      </el-form-item>
      <el-form-item label="巡检计划" prop="planId">
        <el-select
          v-model="queryParams.planId"
          placeholder="请选择巡检计划"
          clearable
          size="small"
          filterable
          @change="handleQuery"
          style="width: 200px"
        >
          <el-option
            v-for="item in planOptions"
            :key="item.id"
            :label="item.planName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ps:patrol:list']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="eyewashList" @selection-change="handleSelectionChange" :height="clientHeight"
              border>
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="位号" align="center" prop="devNo" width="120" :show-overflow-tooltip="true"/>
      <el-table-column label="洗眼器标识醒目并处于良好状况" align="center" prop="signageOk" width="200"
                       :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.inspection_status" :value="scope.row.signageOk"/>
        </template>
      </el-table-column>
      <el-table-column label="洗眼器周围2米内无障碍物，易接近" align="center" prop="accessClear" width="200"
                       :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.inspection_status" :value="scope.row.accessClear"/>
        </template>
      </el-table-column>
      <el-table-column label="所处区域有良好的照明，且没有被遮挡" align="center" prop="lightUnobstructed" width="200"
                       :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.inspection_status" :value="scope.row.lightUnobstructed"/>
        </template>
      </el-table-column>
      <el-table-column label="洗眼器配件没有损坏或丢失，也没有可见的腐蚀" align="center" prop="partsOk" width="220"
                       :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.inspection_status" :value="scope.row.partsOk"/>
        </template>
      </el-table-column>
      <el-table-column label="洗眼器上游手阀处于全开状态，并采取常开保护措施" align="center" prop="valveOpenLocked" width="240"
                       :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.inspection_status" :value="scope.row.valveOpenLocked"/>
        </template>
      </el-table-column>
      <el-table-column label="洗眼器喷头已安装防尘盖，并在启动时防尘盖能够自动打开" align="center" prop="dustcapOk" width="240"
                       :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.inspection_status" :value="scope.row.dustcapOk"/>
        </template>
      </el-table-column>
      <el-table-column label="洗眼器从出水点起高度在10-30厘米并均匀流动" align="center" prop="waterHeight" width="220"
                       :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.inspection_status" :value="scope.row.waterHeight"/>
        </template>
      </el-table-column>
      <el-table-column label="洗眼器出水干净不黑无污染，没有颗粒" align="center" prop="waterClean" width="200"
                       :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.inspection_status" :value="scope.row.waterClean"/>
        </template>
      </el-table-column>
      <el-table-column label="洗眼器出水温度不高于25℃" align="center" prop="waterTemp" width="180" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.inspection_status" :value="scope.row.waterTemp"/>
        </template>
      </el-table-column>
      <el-table-column label="洗眼器手推板、脚踏板及喷淋拉杆灵活，能保持全开" align="center" prop="leversOk" width="240"
                       :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.inspection_status" :value="scope.row.leversOk"/>
        </template>
      </el-table-column>
      <el-table-column label="洗眼器测试前已通知ERC" align="center" prop="ercNotified" width="180" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.inspection_status" :value="scope.row.ercNotified"/>
        </template>
      </el-table-column>
      <el-table-column label="现场声光报警装置工作正常" align="center" prop="localAlarmOk" width="200"
                       :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.inspection_status" :value="scope.row.localAlarmOk"/>
        </template>
      </el-table-column>
      <el-table-column label="ERC接收到洗眼器报警测试信号，报警信号已反馈至DCS和中控室迷你盘" align="center"
                       prop="alarmSignalOk" width="280" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.inspection_status" :value="scope.row.alarmSignalOk"/>
        </template>
      </el-table-column>
      <el-table-column label="确认人" align="center" prop="confirmer" width="120" :show-overflow-tooltip="true"/>
      <el-table-column label="备注" align="center" prop="remarks" width="150" :show-overflow-tooltip="true"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="80">
        <template slot-scope="scope">
          <el-button
            icon="el-icon-picture-outline"
            size="mini"
            type="text"
            @click="openFileDialog(scope.row)"
          >附件
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :close-on-click-modal="false" :visible.sync="file.open" append-to-body title="附件详情" width="50%">
      <el-tabs v-model="tabName" :stretch="true" type="border-card" @tab-click="getFileList">
        <el-tab-pane label="常规附件" name="a">
          <el-empty v-if="file.fileList.length==0" description="如你所见，这里什么都没有"></el-empty>
          <el-image v-for="item in file.fileList" v-else :key="item.fileUrl"
                    :src="getFileUrl(item.fileUrl)"></el-image>
        </el-tab-pane>
        <el-tab-pane label="异常附件" name="b">
          <el-empty v-if="file.fileList.length==0" description="如你所见，这里什么都没有"></el-empty>
          <el-image v-for="item in file.fileList" v-else :key="item.fileUrl"
                    :src="getFileUrl(item.fileUrl)"></el-image>
        </el-tab-pane>
        <el-tab-pane label="异常整改后附件" name="c">
          <el-empty v-if="file.fileList.length==0" description="如你所见，这里什么都没有"></el-empty>
          <el-image v-for="item in file.fileList" v-else :key="item.fileUrl"
                    :src="getFileUrl(item.fileUrl)"></el-image>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
import {
  exportEyewash,
  listEyewash
} from "@/api/ps/inspection/eyewash";
import {treeselect} from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {allFileList} from "@/api/common/commonfile";
import {listPlan} from "@/api/ps/patrol/plan";

export default {
  name: "Eyewash",
  dicts: ['inspection_status'],
  components: {Treeselect},
  data() {
    return {
      tabName: 'a',
      file: {
        open: false,
        fileList: [],
        queryParams: {
          pId: null,
          pType: 'ps-eyewash',
          pValue: ''
        },
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 洗眼器巡检记录表格数据
      eyewashList: [],

      // 部门树选项
      deptOptions: undefined,
      // 巡检计划选项
      planOptions: [],
      clientHeight: 300,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        devNo: null,
        signageOk: null,
        accessClear: null,
        partsOk: null,
        valveOpenLocked: null,
        dustcapOk: null,
        waterHeight: null,
        waterClean: null,
        waterTemp: null,
        leversOk: null,
        ercNotified: null,
        localAlarmOk: null,
        alarmSignalOk: null,
        confirmer: null,
        checkStatus: null,
        checkDate: null,
        month: String(new Date().getMonth() + 1).padStart(2, '0'),
        year: String(new Date().getFullYear()),
        yearMonth: new Date().getFullYear() + '-' + String(new Date().getMonth() + 1).padStart(2, '0'),
        createrCode: null,
        createdate: null,
        updaterCode: null,
        updatedate: null,
        remarks: null,
        deptId: null,
        planId: null,
        issuesStatus: null,
        issuesFlag: null
           }
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    if (this.$route.query.planId) {
      this.queryParams.planId = parseInt(this.$route.query.planId)
    }
    if (this.$route.query.id) {
      this.queryParams.id = parseInt(this.$route.query.id)
      this.queryParams.issuesFlag = '1';
    }
    //设置表格高度对应屏幕高度
    this.$nextTick(() => {
      this.clientHeight = document.body.clientHeight - 250
    })
    this.getPlanList();
    this.getTreeselect();
  },
  methods: {
    openFileDialog(row) {
      this.file.queryParams.pId = row.id;
      this.tabName = 'a'
      this.file.open = true;
      this.getFileList({})
    },
    getFileList(tab) {
      this.file.fileList = [];
      let value = 'regular';
      if (tab.name == 'a') {
        value = 'regular';
      } else if (tab.name == 'b') {
        value = 'issue';
      } else if (tab.name == 'c') {
        value = 'repair';
      }
      this.file.queryParams.pValue = value;
      allFileList(this.file.queryParams).then(response => {
        this.file.fileList = response;
      })
    },
    getFileUrl(url) {
      return process.env.VUE_APP_BASE_API + url;
    },
/** 查询洗眼器巡检记录列表 */
    getList() {
      this.loading = true;
      listEyewash(this.queryParams).then(response => {
        this.eyewashList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 查询巡检计划列表 */
    getPlanList() {
      const now = new Date();
      const currentYear = now.getFullYear();
      const currentMonth = now.getMonth() + 1;

      const query = {
        planYear: currentYear,
        planMonth: currentMonth,
        patrolType: '7'
      };

      listPlan(query).then(response => {
        this.planOptions = response.rows || [];

        // 如果没有从路由参数传入planId，则默认选择当月最后一个计划
        if (!this.$route.query.planId && this.planOptions.length > 0) {
          // 按创建时间降序排序，取第一个（最新的）
          const sortedPlans = [...this.planOptions].sort((a, b) => {
            const dateA = new Date(a.createdate);
            const dateB = new Date(b.createdate);
            return dateB - dateA;
          });

          // 选择当月最后一个计划（创建时间最新的）
          this.queryParams.planId = sortedPlans[0].id;
        }

        // 获取计划列表后再查询数据
        this.getList();
      }).catch(() => {
        // 如果获取计划列表失败，仍然查询数据
        this.getList();
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleYearMonthChange(this.queryParams.yearMonth);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有洗眼器巡检记录数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return exportEyewash(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    },
    /** 年月选择器变化事件 */
    handleYearMonthChange(val) {
      if (val) {
        this.queryParams.year = val.substring(0, 4);
        this.queryParams.month = val.substring(5, 7);
      } else {
        this.queryParams.year = null;
        this.queryParams.month = null;
      }
    }

  }
};
</script>
