<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="位置" prop="position">
        <el-input
          v-model="queryParams.position"
          placeholder="请输入位置"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="型号" prop="modelNo">
        <el-input
          v-model="queryParams.modelNo"
          placeholder="请输入型号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="编号" prop="boxNo">
        <el-input
          v-model="queryParams.boxNo"
          placeholder="请输入编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="月度" prop="month">
        <el-input
          v-model="queryParams.month"
          placeholder="请输入月度"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="年度" prop="year">
        <el-input
          v-model="queryParams.year"
          placeholder="请输入年度"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </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="cabinetList" @selection-change="handleSelectionChange" :height="clientHeight"
              border>
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="位置" align="center" prop="position" :show-overflow-tooltip="true"/>
      <el-table-column label="型号" align="center" prop="modelNo" :show-overflow-tooltip="true"/>
      <el-table-column label="编号" align="center" prop="boxNo" :show-overflow-tooltip="true"/>
      <el-table-column label="阀门类型" align="center" prop="valveType" :show-overflow-tooltip="true"/>
      <el-table-column label="阀门规格" align="center" prop="valveSpecification" :show-overflow-tooltip="true"/>
      <el-table-column label="阀门长度" align="center" prop="valveLength" :show-overflow-tooltip="true"/>
      <el-table-column label="螺栓点距" align="center" prop="boltPointDistance" :show-overflow-tooltip="true"/>
      <el-table-column label="螺栓孔数" align="center" prop="boltHoleCount" :show-overflow-tooltip="true"/>
      <el-table-column label="外观" align="center" prop="appearance" :show-overflow-tooltip="true"/>
      <el-table-column label="内物品" align="center" prop="internalItems" :show-overflow-tooltip="true"/>
      <el-table-column label="阀门" align="center" prop="valve" :show-overflow-tooltip="true"/>
      <el-table-column label="通道" align="center" prop="passage" :show-overflow-tooltip="true"/>
      <el-table-column label="确认人" align="center" prop="confirmer" :show-overflow-tooltip="true"/>
      <el-table-column label="备注" align="center" prop="remarks" :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 {
  exportCabinet,
  listCabinet
} from "@/api/ps/inspection/cabinet";
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: "Cabinet",
  components: {Treeselect},
  data() {
    return {
      tabName: 'a',
      file: {
        open: false,
        fileList: [],
        queryParams: {
          pId: null,
          pType: 'ps-cabinet',
          pValue: ''
        },
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 玻璃门消火栓箱和泡沫栓箱检查记录表格数据
      cabinetList: [],
      
      // 部门树选项
      deptOptions: undefined,
      // 巡检计划选项
      planOptions: [],
      clientHeight: 300,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        position: null,
        modelNo: null,
        boxNo: null,
        appearance: null,
        internalItems: null,
        valve: null,
        passage: null,
        confirmer: null,
        checkStatus: null,
        checkDate: null,
        month: null,
        year: null,
        createrCode: null,
        createdate: null,
        updaterCode: null,
        updatedate: null,
        remarks: null,
        deptId: null,
        planId: null,
        issuesStatus: null,
        issuesFlag: null,
        valveType: null,
        valveSpecification: null,
        valveLength: null,
        boltPointDistance: null,
        boltHoleCount: 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;
      listCabinet(this.queryParams).then(response => {
        this.cabinetList = 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: '2'
      };
      
      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.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 exportCabinet(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    },

  }
};
</script>
