<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="关键字" prop="keyWord">
        <el-input
          v-model="queryParams.keyWord"
          placeholder="请输入关键词"
          clearable
          @keyup.enter.native="handleQuery"
          maxlength="20"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="施工类型" prop="lineTypes">
        <el-select
          v-model="queryParams.lineTypes"
          placeholder="请选择施工类型"
          multiple
          collapse-tags
          style="width: 240px"
          clearable
          filterable
          @change="handleLineTypeChange"
        >
          <el-option
            v-for="item in lineTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="物资类型" prop="materialType">
        <el-select
          v-model="queryParams.materialType"
          placeholder="请选择物资类型"
          style="width: 240px"
          clearable
          filterable
          @change="handleMaterialTypeChange"
        >
          <el-option
            v-for="item in materialTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="物资名称" prop="typeName">
        <el-select
          v-model="queryParams.typeName"
          placeholder="请选择物资名称"
          style="width: 240px"
          clearable
          filterable
          @change="handleTypeNameChange"
        >
          <el-option
            v-for="item in typeNameOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="规格型号" prop="typeModelName">
        <el-select
          v-model="queryParams.typeModelName"
          placeholder="请选择规格型号"
          style="width: 240px"
          clearable
          filterable
        >
          <el-option
            v-for="item in typeModelNameOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="机具类型" prop="jiJuType">
        <el-select
          v-model="queryParams.jiJuType"
          placeholder="请选择机具类型"
          clearable
          style="width: 240px"
        >
          <el-option label="施工机具" :value="1" />
          <el-option label="安全工器具" :value="2" />
        </el-select>
      </el-form-item>

<!--      <el-form-item prop="materialType">-->
<!--        <el-select v-model="queryParams.materialType" placeholder="请选择物品种类" clearable filterable>-->
<!--          <el-option-->
<!--            v-for="dict in materialTypeList"-->
<!--            :key="dict.value"-->
<!--            :label="dict.label"-->
<!--            :value="dict.label"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->

      <el-form-item label="固定资产" prop="isAssets">
        <el-select v-model="queryParams.isAssets" placeholder="是否固定资产" clearable style="width: 240px">
          <el-option label="是" value="0"></el-option>
          <el-option label="否" value="1"></el-option>
        </el-select>
      </el-form-item>

<!--      <el-form-item prop="materialName">-->
<!--        <el-select-->
<!--          v-model="queryParams.materialName"-->
<!--          placeholder="请选择设备类型"-->
<!--          clearable-->
<!--          filterable-->
<!--          @change="handleMaModel"-->
<!--        >-->
<!--          <el-option-->
<!--            v-for="dict in materialNameList"-->
<!--            :key="dict.value"-->
<!--            :label="dict.label"-->
<!--            :value="dict.label"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->


<!--      <el-form-item prop="materialModel">-->
<!--        <el-select v-model="queryParams.materialModel" placeholder="请选择规格型号" clearable filterable>-->
<!--          <el-option-->
<!--            v-for="dict in materialModelList"-->
<!--            :key="dict.value"-->
<!--            :label="dict.label"-->
<!--            :value="dict.label"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->

      <el-form-item label="设备状态" prop="maStatus">
        <el-select v-model="queryParams.maStatus" placeholder="请选择设备状态" clearable filterable style="width: 240px">
          <el-option
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
            v-for="dict in dict.type.ma_machine_status"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button
          type="success"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          :disabled="selectList.length === 0"
        >
          批量更改检验时间
          <span v-if="selectList.length > 0" style="margin-left: 5px">({{ selectList.length }})</span>
        </el-button>
        <span v-if="selectList.length > 0" style="margin-left: 10px; color: #67c23a">
          已选择 {{ selectList.length }} 条需更改数据
        </span>
        <el-button icon="el-icon-upload2" size="mini" @click="handleSynch">检验报告同步</el-button>
        <el-button icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="deviceList" ref="multipleTable" @selection-change="handleSelectionChange" row-key="maId" :max-height="650">
      <el-table-column type="selection" align="center" />
      <el-table-column label="序号" align="center" width="80" type="index">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="物品类型" align="center" prop="materialType" sortable show-overflow-tooltip />
      <el-table-column label="设备类型" align="center" prop="materialName" sortable show-overflow-tooltip />
      <el-table-column label="规格型号" align="center" prop="materialModel" sortable show-overflow-tooltip />
      <el-table-column label="设备编号" align="center" prop="maCode" />
      <el-table-column label="机具类型" align="center" prop="jiJuTypeStr" sortable show-overflow-tooltip />
      <el-table-column label="设备状态" align="center" prop="statusName" sortable show-overflow-tooltip />
      <el-table-column label="固定资产编号" align="center" prop="assetsCode" width="200px" sortable
                       show-overflow-tooltip
      >
        <template slot-scope="scope">
          <div style="display: flex; align-items: center; justify-content: center;">
            <el-input
              v-model="scope.row.assetsCode"
              placeholder="请输入"
              size="small"
              style="width: 80%; margin-right: 5px;"
            />
            <el-button type="text" icon="el-icon-check" @click="handleAssetsCodeChange(scope.row)"></el-button>
          </div>

        </template>
      </el-table-column>
      <!-- <el-table-column label="设备原值" align="center" prop="buyPrice" sortable show-overflow-tooltip /> -->
      <el-table-column label="购置批次" align="center" prop="buyTask" sortable show-overflow-tooltip>
        <template slot-scope="{ row }">
            <span style="color:blue; cursor: pointer" @click="handleViewBuyTask(row)">
              {{ row.buyTask }}
            </span>
        </template>
      </el-table-column>
      <el-table-column label="绑定标签" align="center" prop="qrCode" sortable show-overflow-tooltip>
        <template slot-scope="scope">
            <span v-if="scope.row.qrCode!=null" style="color:blue; cursor: pointer"
                  @click="handleViewQrCode(scope.row)"
            >
              {{ '查看' }}
            </span>
          <span v-if="scope.row.qrCode!=null" style="color:blue; cursor: pointer;margin-left: 10px" @click="downloadQrCode(scope.row)">
              {{ '下载' }}
            </span>
          <span v-else>
              {{ '暂无' }}
            </span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="所在仓库" align="center" prop="ownHouse" sortable  show-overflow-tooltip/> -->
      <el-table-column label="操作" align="center" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-zoom-in"
            @click="handleView(scope.row)"
          >
            查看
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ma:machine:edit']"
          >
            编辑
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdateStatus(scope.row)"
            v-hasPermi="['ma:machine:change']"
          >
            修改状态
          </el-button>
          <!-- <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
                 v-hasPermi="['ma:machine:remove']"
          >
              删除
          </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 :title="title" :visible.sync="showHouse" width="1300px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="24">
          <el-col :span="7">
            <el-form-item label="物品种类" prop="materialType">
              <el-select v-model="form.materialType" placeholder="请选择物品种类" clearable style="width: 100%;"
                         disabled
              >
                <el-option
                  v-for="dict in keeperDataRange"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="设备类型" prop="materialName">
              <el-select v-model="form.materialName" placeholder="请选择设备类型" clearable style="width: 100%;"
                         disabled
              >
                <el-option
                  v-for="dict in keeperDataRange"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="规格型号" prop="materialModel">
              <el-input v-model="form.materialModel" placeholder="请输入" maxlength="20" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="7">
            <el-form-item label="设备编号" prop="maCode">
              <el-input v-model="form.maCode" placeholder="请输入" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="设备状态" prop="statusName">
              <el-input v-model="form.statusName" placeholder="请输入" maxlength="20" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="固定资产编号" prop="assetsCode">
              <el-input v-model="form.assetsCode" placeholder="请输入" maxlength="20" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="7">
            <el-form-item label="设备原编号" prop="preCode">
              <el-input v-model="form.preCode" placeholder="请输入" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="购置批次" prop="buyTask">
              <el-input v-model="form.buyTask" placeholder="请输入" maxlength="20" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="绑定标签" prop="qrCode">
              <div id="qrcode" v-if="form.qrCode" style="display: flex;align-items: center;justify-content: center;"
                   ref="codeItemTwo"
              ></div>
              <span v-else>暂无</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="7">
            <el-form-item label="所在仓库" prop="ownHouse">
              <el-input v-model="form.ownHouse" placeholder="请输入" maxlength="20" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="本次检验人员" prop="checkMan">
              <el-input v-model="form.checkMan" placeholder="请输入" maxlength="20" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="本次检验时间" prop="thisCheckTime">
              <el-date-picker type="date" placeholder="选择日期" v-model="form.thisCheckTime" style="width: 100%;"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="7">
            <el-form-item label="下次检验时间" prop="nextCheckTime">
              <el-date-picker type="date" placeholder="选择日期" v-model="form.nextCheckTime" style="width: 100%;"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="资产属性" prop="assetsId">
              <el-select v-model="form.assetsId" placeholder="请选择资产属性" clearable style="width: 100%;" >
                <el-option
                  v-for="dict in ZichanTypeList"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="出厂时间" prop="outFacTime">
              <el-date-picker type="date" placeholder="选择日期" v-model="form.outFacTime" style="width: 100%;"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="7">
            <el-form-item label="出厂编号" prop="outFacCode">
              <el-input v-model="form.outFacCode" placeholder="请输入" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="出入库次数" prop="inOutNum">
              <el-input v-model="form.inOutNum" placeholder="请输入" maxlength="20" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="库管员">
              <el-select
                v-model="form.keeperArr"
                filterable multiple
                placeholder="请选择库管员"
                style="width: 100%"
                disabled
              >
                <el-option
                  v-for="keeper in KeeperOptions"
                  :key="keeper.userId+''"
                  :label="keeper.nickName"
                  :value="keeper.userId+''"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维修员">
              <el-select
                v-model="form.repairerArr"
                filterable multiple
                placeholder="请选择维修员"
                style="width: 100%"
                disabled
              >
                <el-option
                  v-for="keeper in repairerOptions"
                  :key="keeper.userId"
                  :label="keeper.nickName"
                  :value="keeper.userId+''"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="20">
            <el-form-item label="备注" prop="remark">
              <el-input
                type="textarea"
                :rows="5"
                placeholder="请输入备注"
                v-model="form.remark"
                maxlength="100"
                show-word-limit
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <template>
          <el-button v-if="this.title=='修改'" type="primary" @click="submitForm">确 定</el-button>
        </template>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 设备状态修改对话框 -->
    <el-dialog title="修改设备状态" :visible.sync="statusUpdateOpen" width="500px" append-to-body>
      <el-form ref="statusFormRef" :model="statusForm" :rules="statusRules" label-width="80px">
        <el-form-item label="设备状态" prop="maStatus">
          <el-select v-model="statusForm.maStatus" placeholder="请选择设备状态" style="width: 100%">
            <el-option
              v-for="dict in dict.type.ma_machine_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelStatusUpdate">取 消</el-button>
        <el-button type="primary" @click="submitStatusUpdate">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 二维码下载对话框 -->
    <el-dialog title="二维码查看" :visible.sync="uploadOpen" width="450px" append-to-body :close-on-click-modal="false">
      <div style="text-align: center" ref="codeQr" v-if="uploadOpen">
        <div class="uploadImg">
          <div id="qrcode" class="qrcode" ref="codeItem"></div>
        </div>
        <div class="boxCode">{{ rowObj.maCode }}</div>
      </div>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="downloadQrCode(rowObj)">下 载</el-button>
      </div>
    </el-dialog>

    <!-- 检验报告同步对话框 -->
    <el-dialog :title="titleSynch" :visible.sync="openSynch" width="500px" append-to-body @close="cancelSynch">
      <el-form ref="formSynchParams" :model="formSynchParams" :inline="true">
        <el-form-item prop="reportCode">
          <el-input v-model="formSynchParams.reportCode" placeholder="请输入报告编号" maxlength="20"
                    style="width: 340px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuerySynch">查询</el-button>
        </el-form-item>
        <div style="margin-top: 10px; height: 100px;  text-align: center; ">
          <img v-if="formSynchParams.pdf" src="../../../../assets/img/pdf.png" alt="暂无图片" @click="downloadPdf"
               style="max-width: 100%; max-height: 100%;"
          />
        </div>

      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: right">
        <el-button type="primary" @click="synchSubmit">同步</el-button>
        <el-button @click="cancelSynch">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="dialogTitle" :visible.sync="authDialogVisible" width="25%" append-to-body>
      <el-form :model="authForm" ref="authFormRef" label-width="120px" class="auth-dialog-form">

        <!-- 本次检验时间 -->
        <el-form-item label="本次检验时间：" prop="currentCheckDate">
          <el-date-picker
            v-model="authForm.currentCheckDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
          :picker-options="{
          disabledDate(time) {
          return time.getTime() > Date.now();
          }
          }"
            :clearable="false"
          @change="handleCurrentCheckDateChange"
          />
        </el-form-item>

        <!-- 下次检验时间 -->
        <el-form-item label="下次检验时间：" prop="nextCheckDate">
          <el-date-picker
            v-model="authForm.nextCheckDate"
            type="date"
            placeholder="请选择日期"
            value-format="yyyy-MM-dd"
            :picker-options="{
          disabledDate: (time) => {
            if (!authForm.currentCheckDate) {
              return false; // 没有选择本次检验时间时，不限制
            }
            return time.getTime() < new Date(authForm.currentCheckDate).getTime();
          }
        }"
            :clearable="false"
          />
        </el-form-item>


      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="authDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForms">保存</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  getListDevice,
  getDeviceDetail,
  editDevice,
  editMachineStatus,
  addDevice,
  editDeviceBatch,
  delDevice,
  getDeviceType,
  getZichanType,
  getSynchReportCode,
  synchReport,
  editAssetsCode
} from '@/api/ma/device'
import { getKeeperIds } from '@/api/ma/typeConfigKeeper'
import { getRepairIds } from '@/api/ma/typeConfigRepair'
import {
  getUserTypeList
} from '@/api/ma/base'
import { downloadFile, downloadFileData } from '@/utils/download'
import { getToken } from '@/utils/auth'
import QRCode from 'qrcodejs2'
import html2canvas from 'html2canvas'
import { formatTime } from '@/utils/bonus'
import {getLintTypeList, getMaterialTypeList} from "@/api/stquery/stquery";

export default {
  name: 'Device',
  dicts: ['ma_machine_status'],
  data() {
    return {
      // 遮罩层
      loading: false,

      loadingTwo: false,

      // 是否显示项目部Id
      showName: false,

      // 是否显示施工预警信息
      showWarn: false,

      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,

      // 显示搜索条件
      showSearch: true,
      showHouse: false,

      // 总条数
      total: 0,
      totalTwo: 0,
      // 施工记录表格数据
      deviceList: [],
      materialTypeList: [],
      ZichanTypeList: [],
      materialNameList: [],
      materialModelList: [],
      maxLength: 100,//已选列表上限，防止数据过多请求报错
      keeperDataRange: [],
      // 班组人员表格数据
      teamList: [],
      teamTempList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      selectList: [], //          列表选中数据
      selectedItems: [], // 批量修改时选择的申请单
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyWord: undefined,
        isAssets: undefined,
        maStatus: null,
        typeName: null, //物资名称
        typeModelName: null, //规格型号
        lineTypes: [], //线路类型多选数组
        materialType: null,
        jiJuType:null
      },
      lineTypeOptions: [], // 线路类型选项
      materialTypeOptions: [], // 物资类型选项
      typeNameOptions:[],
      typeModelNameOptions:[],
      // 查询参数
      queryTeam: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        sex: undefined,
        teamId: undefined
      },

      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/material/engineering/excelUpload'
      },
      statusUpdateOpen: false, // 状态修改对话框显示控制
      statusForm: { // 状态修改表单
        maId: null,
        maStatus: null
      },
      statusRules: { // 状态修改表单验证规则
        maStatus: [{ required: true, message: '请选择设备状态', trigger: 'change' }]
      },
      // 表单参数
      form: {
        qrCode: '',
        keeperArr: [],
        repairerArr: [],
        keeperNameArr: [],
        repairerNameArr: []
      },
      // 表单校验
      rules: {},
      uploadOpen: false,
      rowObj: {},
      qrCode: '',
      qrcodeUrl: '',
      KeeperOptions: [],
      sortedKeeperOptions: [],
      repairerOptions: [],
      sortedRepairerOptions: [],
      authDialogVisible: false,
      dialogTitle: "检验时间设置",
      authForm: {
        currentCheckDate: null,
        nextCheckDate: null,
      },
      titleSynch: '', //检验报告同步标题
      openSynch: false, //检验报告同步
      synchLoading: false, //检验报告同步loading
      formSynchParams: { //检验报告同步表单
        reportCode: '', //检验报告编号
        pdf: '', //检验报告pdf
        pdfName: '' //检验报告pdf名称
      },
      dataSynch: {} //检验报告同步数据
    }
  },
  created() {
    this.getZichanType()
    // this.getDeviceType()
    this.getKeeperData()
    this.getRepairerData()
    this.getList()
    //线路类型下拉
    this.getLintTypeList()
    this.getMaterialTypeList()
    this.getDeviceType()
  },
  // watch: {
  //   // 监听 form.qrCode 的变化，如果有值就生成二维码
  //   'form.qrCode': function (newValue) {
  //         if (newValue) {
  //           this.generateQRCode(newValue);
  //         } else {
  //           this.qrcodeUrl = '';  // 清空二维码 URL
  //         }
  //       },

  // },
  methods: {
    async getLintTypeList() {
      try {
        const res = await getLintTypeList()
        if (res.code === 200 && res.data) {
          // 根据后端返回的数据结构进行调整
          this.lineTypeOptions = res.data.map(item => {
            // 如果返回的是对象数组，根据实际字段调整
            return {
              value: item.typeId,
              label: item.typeName
            }
          })
        } else {
          this.$message.error('获取施工类型下拉失败')
          this.lineTypeOptions = [] // 失败时设置为空数组
        }
      } catch (error) {
        console.error('获取施工类型下拉列表失败:', error)
        this.$message.error('获取施工类型下拉列表失败')
        this.lineTypeOptions = [] // 异常时设置为空数组
      }
    },
    // 线路类型变化处理
    async handleLineTypeChange(selectedLineTypes) {
      // 清空物资类型选择
      this.queryParams.materialType = null
      this.materialTypeOptions=[]
      this.queryParams.typeName=null
      this.typeNameOptions=[]
      this.queryParams.typeModelName=null
      this.typeModelNameOptions=[]

      if (!selectedLineTypes || selectedLineTypes.length === 0) {
        this.materialTypeOptions = []
      }

      // 获取物资类型数据
      await this.getMaterialTypeList(selectedLineTypes)
    },
    async getMaterialTypeList(lineTypes) {
      const params = {
        constructionType:lineTypes
      }
      try {
        // 调用接口获取物资类型数据
        const res = await getMaterialTypeList(params)

        if (res.code === 200 && res.data) {
          // 处理返回的物资类型数据
          const materialTypes = res.data.map(item => ({
            value: item.typeId,
            label: item.typeName
          }))

          // 更新选项并缓存
          this.materialTypeOptions = materialTypes
        } else {
          this.$message.error('获取物资类型失败')
          this.materialTypeOptions = []
        }
      } catch (error) {
        console.error('获取物资类型列表失败:', error)
        this.$message.error('获取物资类型列表失败')
        this.materialTypeOptions = []
      }
    },
    async handleMaterialTypeChange(e){
      this.queryParams.typeName=null
      this.typeNameOptions=[]
      this.queryParams.typeModelName=null
      this.typeModelNameOptions=[]
      getDeviceType({ level: 3, typeId:e }).then(response => {
        let matNameRes = response.data
        this.typeNameOptions = matNameRes.map((item) => {
          return {
            label: item.typeName,
            value: item.typeId
          }
        })
      })
    },
    async handleTypeNameChange(e){
      this.queryParams.typeModelName=null
      this.typeModelNameOptions=[]
      getDeviceType({ level: 4, typeId:e }).then(response => {
        let matNameRes = response.data
        this.typeModelNameOptions = matNameRes.map((item) => {
          return {
            label: item.typeName,
            value: item.typeId
          }
        })
      })
    },
    getDeviceType() {
      getDeviceType({ level: 3 }).then(response => {
        let matNameRes = response.data
        this.typeNameOptions = matNameRes.map((item) => {
          return {
            label: item.typeName,
            value: item.typeId
          }
        })
      })
      getDeviceType({ level: 4 }).then(response => {
        let matModelRes = response.data
        this.typeModelNameOptions = matModelRes.map((item) => {
          return {
            label: item.typeName,
            value: item.typeId
          }
        })
      })
    },
    async getKeeperData() {
      const itemName = 'ku_guan_role_ids'
      let roleIdsTemp = []
      await getKeeperIds(itemName).then((response) => {
        const roleIds = response.rows[response.rows.length - 1].itemValue
          .split(',')
          .map((item) => Number(item))
        roleIdsTemp = roleIds
      })
      await getUserTypeList(roleIdsTemp.join(',')).then((response) => {
        this.KeeperOptions = response.rows
      })
    },
    // 添加 handleUpdateStatus 方法
    handleUpdateStatus(row) {
      this.statusForm = {
        maId: row.maId,
        maStatus: row.maStatus
      }
      this.statusUpdateOpen = true
    },

    // 添加状态修改提交方法
    submitStatusUpdate() {
      this.$refs['statusFormRef'].validate(valid => {
        if (valid) {
          // 调用API更新设备状态
          editMachineStatus(this.statusForm).then(response => {
            this.$modal.msgSuccess('状态更新成功')
            this.statusUpdateOpen = false
            this.getList() // 刷新列表
          }).catch(error => {
            this.$modal.msgError('状态更新失败')
          })
        }
      })
    },

    // 添加取消状态修改方法
    cancelStatusUpdate() {
      this.statusUpdateOpen = false
      this.$refs['statusFormRef'].resetFields()
    },

    async getRepairerData() {
      const itemName = 'wei_xiu_role_ids'
      let roleIdsTemp = []
      await getRepairIds(itemName).then((response) => {
        const roleIds = response.rows[response.rows.length - 1].itemValue
          .split(',')
          .map((item) => Number(item))
        roleIdsTemp = roleIds
      })
      await getUserTypeList(roleIdsTemp.join(',')).then((response) => {
        this.repairerOptions = response.rows
        console.log('4444', this.repairerOptions)
      })
    },

    // getDeviceType() {
    //   getDeviceType({ level: 2, skipPermission: 1 }).then(response => {
    //     let matTypeRes = response.data
    //     this.materialTypeList = matTypeRes.map((item) => {
    //       return {
    //         label: item.typeName,
    //         value: item.typeId
    //       }
    //     })
    //   })
    //   getDeviceType({ level: 3, skipPermission: 1 }).then(response => {
    //     let matNameRes = response.data
    //     this.materialNameList = matNameRes.map((item) => {
    //       return {
    //         label: item.typeName,
    //         value: item.typeId
    //       }
    //     })
    //   })
    //   getDeviceType({ level: 4, skipPermission: 1 }).then(response => {
    //     let matModelRes = response.data
    //     this.materialModelList = matModelRes.map((item) => {
    //       return {
    //         label: item.typeName,
    //         value: item.typeId
    //       }
    //     })
    //   })
    // },

    // change设备类型
    handleMaModel(e) {
      let typeId = null
      if (!e) {
        typeId = null
      } else {
        typeId = this.materialNameList.find(item => item.label == e).value
      }
      console.log('🚀 ~ handleMaModel ~ typeId:', typeId)
      getDeviceType({ level: 4, skipPermission: 1, typeId }).then(response => {
        let matModelRes = response.data
        this.materialModelList = matModelRes.map((item) => {
          return {
            label: item.typeName,
            value: item.typeId
          }
        })
      })
    },

    //查询资产属性下拉框
    getZichanType() {
      getZichanType({ isAll: 1 }).then(response => {
        let matTypeRes = response.data
        this.ZichanTypeList = matTypeRes.map((item) => {
          return {
            label: item.assetName,
            value: item.id
          }
        })
      })
    },

    /** 查询岗位列表 */
    getList() {
      this.loading = true
      const params = {
        isAssets:this.queryParams.isAssets,
        maStatus:this.queryParams.maStatus,
        keyWord: this.queryParams.keyWord,
        typeNameId: this.queryParams.typeName,
        typeModelNameId: this.queryParams.typeModelName,
        constructionTypes:this.queryParams.lineTypes,
        materialTypeId:this.queryParams.materialType,
        jiJuTypeStr:this.queryParams.jiJuType,
        pageSize: this.queryParams.pageSize,
        pageNum: this.queryParams.pageNum
      }
      getListDevice(params).then(response => {
        this.deviceList = response.rows
        this.total = response.total
        this.loading = false

        this.$nextTick(() => {
          this.selectList = []
        })
      })
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 固定资产录入
    handleAssetsCodeChange(row) {
      if (!row.assetsCode) {
        this.$message.error('请输入资产编号')
      } else {
        editAssetsCode(row).then(response => {
          this.$message.success('固定资产录入成功')
          this.getList()
        })
      }
    },

    handleUpdate(row) {
      this.reset()
      const maId = row.maId
      getDeviceDetail(maId).then((response) => {
        this.form = response.data
        this.form.assetsId = this.form.assetsId ? Number(this.form.assetsId) : ''
        if (response.data.keeperId) {
          const keeperIds = response.data.keeperId.split(',')
          // 根据 keeperIds 从 KeeperOptions 中获取对应的 keeper 对象
          const keepers = keeperIds.map((id) =>
            this.KeeperOptions.find((keeper) => keeper.userId + '' === id)
          ).filter(Boolean) // 过滤掉可能不存在的 keeper

          // 根据 keeperName 中文排序
          keepers.sort((a, b) =>
            a.nickName.localeCompare(b.nickName, 'zh-CN')
          )

          // 提取排序后的 keeperId
          this.form.keeperArr = keepers.map((keeper) => keeper.userId + '')
        } else {
          this.form.keeperArr = [] // 如果不存在，设置为空数组
        }
        if (response.data.repairId) {
          const repairerIds = response.data.repairId.split(',')
          // 根据 keeperIds 从 KeeperOptions 中获取对应的 keeper 对象
          const repairers = repairerIds.map((id) =>
            this.repairerOptions.find((repairer) => repairer.userId + '' === id)
          ).filter(Boolean) // 过滤掉可能不存在的 keeper

          // 根据 keeperName 中文排序
          repairers.sort((a, b) =>
            a.nickName.localeCompare(b.nickName, 'zh-CN')
          )

          // 提取排序后的 keeperId
          this.form.repairerArr = repairers.map((repairer) => repairer.userId + '')
        } else {
          this.form.repairerArr = [] // 如果不存在，设置为空数组
        }
        if (this.form.qrCode) {
          this.generateQRCode(this.form.qrCode)
          // 将生成的二维码转换为图片URL
        } else {
          this.qrcodeUrl = ''
        }
        this.showHouse = true
        this.title = '修改'
      })
    },

    handleView(row) {
      this.reset()
      const maId = row.maId
      getDeviceDetail(maId).then((response) => {
        this.form = response.data
        this.form.assetsId = this.form.assetsId ? Number(this.form.assetsId) : ''
        if (response.data.keeperId) {
          const keeperIds = response.data.keeperId.split(',')
          // 根据 keeperIds 从 KeeperOptions 中获取对应的 keeper 对象
          const keepers = keeperIds.map((id) =>
            this.KeeperOptions.find((keeper) => keeper.userId + '' === id)
          ).filter(Boolean) // 过滤掉可能不存在的 keeper

          // 根据 keeperName 中文排序
          keepers.sort((a, b) =>
            a.nickName.localeCompare(b.nickName, 'zh-CN')
          )

          // 提取排序后的 keeperId
          this.form.keeperArr = keepers.map((keeper) => keeper.userId + '')
        } else {
          this.form.keeperArr = [] // 如果不存在，设置为空数组
        }
        if (response.data.repairId) {
          const repairerIds = response.data.repairId.split(',')
          // 根据 keeperIds 从 KeeperOptions 中获取对应的 keeper 对象
          const repairers = repairerIds.map((id) =>
            this.repairerOptions.find((repairer) => repairer.userId + '' === id)
          ).filter(Boolean) // 过滤掉可能不存在的 keeper

          // 根据 keeperName 中文排序
          repairers.sort((a, b) =>
            a.nickName.localeCompare(b.nickName, 'zh-CN')
          )

          // 提取排序后的 keeperId
          this.form.repairerArr = repairers.map((repairer) => repairer.userId + '')
        } else {
          this.form.repairerArr = [] // 如果不存在，设置为空数组
        }
        if (this.form.qrCode) {
          this.generateQRCode(this.form.qrCode)
          // 将生成的二维码转换为图片URL
        } else {
          this.qrcodeUrl = ''
        }
        this.showHouse = true
        this.title = '查看'
      })
    },

    // 生成二维码的方法
    generateQRCode(value) {
      this.$nextTick(() => {
        this.$refs.codeItemTwo.innerHTML = ''
        var qrcode = new QRCode(this.$refs.codeItemTwo, {
          text: value, //二维码内容
          width: 55,
          height: 55,
          colorDark: '#000000',
          colorLight: '#ffffff',
          correctLevel: QRCode.CorrectLevel.H
        })
      }, 500)
    },
    // 表单重置
    reset() {
      this.form = {}
      this.resetForm('form')
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.queryParams.keyWord = null
      this.queryParams.maStatus = null
      this.handleQuery()
    },

    //** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.maId != undefined) {
            editDevice(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.showHouse = false
              this.getList()
            })
          }
        }
      })
    },

    // 取消按钮
    cancel() {
      this.showHouse = false
      this.reset()
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const maId = row.maId
      this.$modal
        .confirm('是否确认删除数据项？')
        .then(function() {
          return delDevice(maId)
        })
        .then(() => {
          this.$modal.msgSuccess('删除成功')
          this.getList()
        })
        .catch(() => {
        })
    },

    // 二维码查看
    handleViewQrCode(row) {
      console.log('🚀 ~ handleViewQrCode ~ row:', row)
      this.rowObj = row
      this.uploadOpen = true
      this.qrCode = row.qrCode
      let str = 'http://ahjj.jypxks.com:9988/imw/backstage/machine/qrCodePage?qrcode=' + row.qrCode
      console.log('🚀 ~ handleViewQrCode ~ str:', str)
      this.$nextTick(() => {
        this.$refs.codeItem.innerHTML = ''
        var qrcode = new QRCode(this.$refs.codeItem, {
          text: str, //二维码内容
          width: 256,
          height: 256,
          colorDark: '#000000',
          colorLight: '#ffffff',
          correctLevel: QRCode.CorrectLevel.H
        })
      }, 500)

    },
    downloadQrCode(row) {
      const qrContainer = document.createElement('div')
      document.body.appendChild(qrContainer)

      const qrSize = 512 // 放大二维码
      const padding = 20 // 边距也放大
      const fontSize = 68 // 放大文字
      const maxTextWidth = qrSize

      const qrcode = new QRCode(qrContainer, {
        text: 'http://ahjj.jypxks.com:9988/imw/backstage/machine/qrCodePage?qrcode=' + row.qrCode,
        width: qrSize,
        height: qrSize,
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.H
      })

      setTimeout(() => {
        const img = qrContainer.querySelector('img') || qrContainer.querySelector('canvas')
        const text = row.maCode || ''

        // 计算换行
        const ctxMeasure = document.createElement('canvas').getContext('2d')
        ctxMeasure.font = `${fontSize}px Arial`
        const words = text.split('')
        let line = ''
        const lines = []
        for (let i = 0; i < words.length; i++) {
          const testLine = line + words[i]
          if (ctxMeasure.measureText(testLine).width > maxTextWidth) {
            lines.push(line)
            line = words[i]
          } else {
            line = testLine
          }
        }
        lines.push(line)

        // 动态计算画布高度
        const lineHeight = fontSize + 10
        const qrCanvas = document.createElement('canvas')
        qrCanvas.width = qrSize + padding * 2
        qrCanvas.height = qrSize + padding * 2 + lines.length * lineHeight

        const ctx = qrCanvas.getContext('2d')
        ctx.fillStyle = '#fff'
        ctx.fillRect(0, 0, qrCanvas.width, qrCanvas.height)

        ctx.drawImage(img, padding, padding, qrSize, qrSize)

        // 绘制文字
        ctx.fillStyle = '#000'
        ctx.font = `${fontSize}px Arial`
        ctx.textAlign = 'center'
        lines.forEach((ln, index) => {
          ctx.fillText(ln, qrCanvas.width / 2, qrSize + padding + fontSize / 1.2 + index * lineHeight)
        })

        // 下载
        const a = document.createElement('a')
        a.href = qrCanvas.toDataURL('image/png')
        a.download = text + '.png'
        a.click()

        document.body.removeChild(qrContainer)
      }, 500)
    },

    //二维码下载
    // downloadCode(e) {
    //   if (document.getElementById('qrcode').childNodes[0]) {
    //     let element = this.$refs.codeQr
    //     html2canvas(element).then((canvas) => {
    //       // 将canvas转换为图片URL
    //       const image = canvas.toDataURL('image/png')
    //       const alink = document.createElement('a')
    //       alink.href = image
    //       alink.download = this.qrCode
    //       alink.click()
    //     })
    //   }
    // },
    handleViewBuyTask(row) {
      this.$router.push({
        path: '/purchase/goodsEntry',
        query: {
          buyTask: row.buyTask
        }
      })
    },

    //检验报告同步
    handleSynch() {
      this.titleSynch = '检验报告同步'
      this.openSynch = true
    },

    handleQuerySynch() {
      const params = {
        reportCode: this.formSynchParams.reportCode
      }
      getSynchReportCode(params).then((response) => {
        let data = response.data
        this.dataSynch = data
        if (data.pdf) {
          this.formSynchParams.pdf = data.pdf
          this.formSynchParams.pdfName = data.reportName
        } else {
          this.formSynchParams.pdf = ''
          this.formSynchParams.pdfName = ''
          this.$message.error('该报告编号暂无文件')
        }
      })
    },

    downloadPdf() {
      if (this.formSynchParams.pdf) {
        const link = document.createElement('a')
        link.href = this.formSynchParams.pdf
        // 从 URL 中提取文件名，如果无法提取则使用默认文件名
        const fileName = this.formSynchParams.pdfName
        link.download = fileName
        // 设置在新页面打开
        link.target = '_blank'
        // 将链接添加到文档中
        document.body.appendChild(link)
        link.click()
        // 移除链接
        document.body.removeChild(link)
      }

    },

    cancelSynch() {
      this.openSynch = false
      this.formSynchParams = { //检验报告同步表单
        reportCode: '', //检验报告编号
        pdf: '', //检验报告pdf
        pdfName: '' //检验报告pdf名称
      }
      this.dataSynch = {}
    },

    //同步
    synchSubmit() {
      const loading = this.$loading({ text: '同步中...' })
      const params = {
        checkTimeSynch: this.dataSynch.checkTimeSynch,
        nextCheckTimeSynch: this.dataSynch.nextCheckTimeSynch,
        pdf: this.dataSynch.pdf,
        reportName: this.dataSynch.reportName,
        reportNum: this.dataSynch.reportNum,
        samples: this.dataSynch.samples
      }

      synchReport(params).then((response) => {
        if (response.code == 200) {
          this.$modal.msgSuccess(response.msg)
          this.openSynch = false
          this.formSynchParams = {
            reportCode: '',
            pdf: '',
            pdfName: ''
          }
          this.dataSynch = {}
          loading.close()
        }
      })
        .finally(() => {
          // 4. 无论成功或失败，最后都要关闭 loading
          loading.close();
          // 5. 刷新列表
          this.getList();
        });
    },
    // 导出
    handleExport() {
      try {
        let fileName = `设备管理_${formatTime(new Date())}.xLsx`
        let url = '/material/ma_machine/export'
        const params = {
          isAssets:this.queryParams.isAssets,
          maStatus:this.queryParams.maStatus,
          keyWord: this.queryParams.keyWord,
          typeNameId: this.queryParams.typeName,
          typeModelNameId: this.queryParams.typeModelName,
          constructionTypes:this.queryParams.lineTypes,
          materialTypeId:this.queryParams.materialType,
          jiJuTypeStr:this.queryParams.jiJuType,
          pageSize: this.queryParams.pageSize,
          pageNum: this.queryParams.pageNum
        }
        console.log('🚀 ~ 导出 ~ params:', params)
        this.download(url, params, fileName)
      } catch (error) {
        console.log('导出数据失败', error)
      }
    },
    // 列表复选框
    handleSelectionChange(validSelection) {
      this.selectList = validSelection;
    },
    formatDate(date) {
      if (!date) return null;
      const y = date.getFullYear();
      const m = String(date.getMonth() + 1).padStart(2, "0");
      const d = String(date.getDate()).padStart(2, "0");
      return `${y}-${m}-${d}`;
    },
    // 批量更新时间
    handleAdd() {
      if (this.selectList.length === 0) {
        this.$message.warning("请先选择要修改的数据");
        return;
      }
      const today = new Date();
      this.authForm.currentCheckDate = this.formatDate(today);
      this.calculateNextCheckDate(today);
      this.authDialogVisible = true;
    },
    // 本次检验时间变化时
    handleCurrentCheckDateChange(val) {
      if (val) {
        this.calculateNextCheckDate(new Date(val));
      } else {
        this.authForm.nextCheckDate = null;
      }
    },

    // 计算下次检验时间
    calculateNextCheckDate(date) {
      let nextDate = new Date(date);
      nextDate.setFullYear(nextDate.getFullYear() + 1);
      nextDate.setDate(nextDate.getDate() - 1);
      this.authForm.nextCheckDate = this.formatDate(nextDate);
    },
    // 提交批量修改
    async submitForms() {
      if (!this.authForm.currentCheckDate) {
        this.$message.error("请选择本次检验时间");
        return;
      }
      if (this.selectList.length === 0) {
        this.$message.warning("没有选择任何设备");
        return;
      }

      // 拼接参数
      const params = {
        maIds: this.selectList.map(item => item.maId),
        thisCheckTime: this.authForm.currentCheckDate,
        nextCheckTime: this.authForm.nextCheckDate
      };
      console.log(params)
      try {
        await editDeviceBatch(params);
        this.$message.success("批量更新成功");
        this.authDialogVisible = false;
        this.getList();
      } catch (e) {
        this.$message.error("批量更新失败");
      }
    },
  }
}
</script>
<style lang="scss" scoped>
::v-deep.el-table .fixed-width .el-button--mini {
  width: 60px !important;
  margin-bottom: 10px;
}

//隐藏图片上传框的css
::v-deep.disabled {
  .el-upload--picture-card {
    display: none;
  }
}

.uploadImg {
  padding-top: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.boxCode {
  margin-top: 10px;
  padding-bottom: 20px;
  font-size: 33px;
  font-weight: bold;
  color: #000;
}

.qrcode-container img {
  width: 100px; /* 设置二维码的大小，调整为你需要的尺寸 */
  height: 100px;
}
</style>
