<template>
  <div
    class="device-page grid grid-cols-[auto_1fr] grid-rows-[auto_auto_minmax(0,1fr)] gap-3 gap-x-4 h-[calc(100vh-20px-var(--top-tool-height)-var(--tags-view-height)-var(--app-footer-height))]">
    <!-- 左侧部门树 -->
    <DeptTreeSelect
      class="row-span-3"
      :top-id="rootDeptId"
      :deptId="deptId"
      v-model="queryParams.deptId"
      :init-select="false"
      :show-title="false"
      request-api="getSimpleDeptList"
      @node-click="handleDeptNodeClick" />

    <!-- 搜索工作栏 -->
    <el-form
      ref="queryFormRef"
      :model="queryParams"
      size="default"
      label-width="68px"
      class="bg-white dark:bg-[#1d1e1f] rounded-lg shadow px-8 py-2 flex items-center flex-wrap min-w-0">
      <div class="flex items-center gap-4 flex-wrap">
        <el-form-item :label="t('iotDevice.yfCode')" prop="yfDeviceCode">
          <el-input
            v-model="queryParams.yfDeviceCode"
            :placeholder="t('iotDevice.yfCodeHolder')"
            clearable
            @keyup.enter="handleQuery"
            class="!w-200px" />
        </el-form-item>
        <el-form-item :label="t('iotDevice.code')" prop="deviceCode">
          <el-input
            v-model="queryParams.deviceCode"
            :placeholder="t('iotDevice.codeHolder')"
            clearable
            @keyup.enter="handleQuery"
            class="!w-200px" />
        </el-form-item>
        <el-form-item :label="t('iotDevice.name')" prop="deviceName">
          <el-input
            v-model="queryParams.deviceName"
            :placeholder="t('iotDevice.nameHolder')"
            clearable
            @keyup.enter="handleQuery"
            class="!w-200px" />
        </el-form-item>
        <el-form-item label="车牌号" prop="carNo">
          <el-input
            v-model="queryParams.carNo"
            placeholder="请输入车牌号"
            clearable
            @keyup.enter="handleQuery"
            class="!w-200px" />
        </el-form-item>

        <el-form-item label="设备号" prop="deviceNo">
          <el-input
            v-model="queryParams.deviceNo"
            placeholder="请输入设备号"
            clearable
            @keyup.enter="handleQuery"
            class="!w-200px" />
        </el-form-item>
        <el-form-item :label="t('iotDevice.brand')" prop="brandName">
          <el-input
            v-model="queryParams.brandName"
            :placeholder="t('iotDevice.brandHolder')"
            clearable
            @keyup.enter="handleQuery"
            class="!w-200px" />
        </el-form-item>

        <el-form-item v-show="ifShow" :label="t('iotDevice.status')" prop="deviceStatus">
          <el-select
            v-model="queryParams.deviceStatus"
            :placeholder="t('iotDevice.statusHolder')"
            clearable
            class="!w-200px">
            <el-option
              v-for="dict in getStrDictOptions(DICT_TYPE.PMS_DEVICE_STATUS)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>

        <el-form-item v-show="ifShow" :label="t('iotDevice.assets')" prop="assetProperty">
          <el-select
            v-model="queryParams.assetProperty"
            :placeholder="t('iotDevice.assetsHolder')"
            clearable
            class="!w-200px">
            <el-option
              v-for="dict in getStrDictOptions(DICT_TYPE.PMS_ASSET_PROPERTY)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item
          v-show="ifShow"
          :label="t('deviceForm.category')"
          prop="assetClass"
          style="width: 15vw">
          <el-tree-select
            v-model="queryParams.assetClass"
            :data="productClassifyList"
            :props="defaultProps"
            class="!w-200px"
            check-strictly
            node-key="id"
            :placeholder="t('deviceForm.categoryHolder')"
            filterable />
        </el-form-item>

        <el-form-item>
          <el-button v-if="!ifShow" @click="moreQuery(true)" type="warning">
            <Icon icon="ep:search" class="mr-5px" /> {{ t('iotDevice.moreSearch') }}
          </el-button>
          <el-button v-if="ifShow" @click="moreQuery(false)" type="danger">
            <Icon icon="ep:search" class="mr-5px" /> {{ t('iotDevice.closeSearch') }}
          </el-button>
          <el-button @click="handleQuery">
            <Icon icon="ep:search" class="mr-5px" />{{ t('operationFill.search') }}
          </el-button>
          <el-button @click="resetQuery">
            <Icon icon="ep:refresh" class="mr-5px" /> {{ t('operationFill.reset') }}
          </el-button>
          <el-button
            type="primary"
            plain
            @click="openForm('create', undefined, queryParams.deptId)"
            v-hasPermi="['rq:iot-device:create']">
            <Icon icon="ep:plus" class="mr-5px" /> {{ t('operationFill.add') }}
          </el-button>
          <el-button
            type="success"
            plain
            @click="handleExport"
            :loading="exportLoading"
            v-hasPermi="['rq:iot-device:export']">
            <Icon icon="ep:download" class="mr-5px" /> 导出
          </el-button>
        </el-form-item>
      </div>
    </el-form>

    <div class="device-dashboard-grid min-w-0">
      <DeviceTotalCard :total="dashboardTotal" :loading="dashboardLoading" />
      <DeviceStatusCard :data="dashboardStatus" :loading="dashboardLoading" />
      <DeviceClassifyTopCard :data="dashboardClassify" :loading="dashboardLoading" />
    </div>

    <!-- 列表 -->
    <div class="bg-white dark:bg-[#1d1e1f] shadow rounded-lg flex flex-col p-2 pt-3 min-w-0">
      <div class="flex-1 relative min-h-0">
        <el-auto-resizer class="absolute">
          <template #default="{ width, height }">
            <zm-table
              :loading="loading"
              :data="list"
              :width="width"
              :height="height"
              :max-height="height"
              show-border>
              <zm-table-column
                :label="t('iotDevice.serial')"
                width="70"
                align="center"
                fixed="left"
                hide-in-column-settings>
                <template #default="scope">
                  {{ scope.$index + 1 }}
                </template>
              </zm-table-column>
              <zm-table-column
                :label="t('iotDevice.yfCode')"
                align="center"
                prop="yfDeviceCode"
                width="150"
                fixed="left"
                zm-sortable
                zm-filterable
                :zm-sort-method="handleZmSortChange"
                v-model:filter-model-value="queryParams.yfDeviceCode">
                <template #filter="{ filterModelValue, updateFilterModelValue, close }">
                  <div class="p-2">
                    <el-input
                      :model-value="filterModelValue"
                      placeholder="请输入油服编码"
                      clearable
                      @update:model-value="updateFilterModelValue"
                      @keyup.enter="() => confirmColumnFilter(close)" />
                    <div class="mt-2 flex justify-end gap-2">
                      <el-button
                        size="small"
                        @click="() => clearColumnFilter(updateFilterModelValue, close)">
                        清空
                      </el-button>
                      <el-button
                        size="small"
                        type="primary"
                        :icon="Search"
                        @click="() => confirmColumnFilter(close)">
                        搜索
                      </el-button>
                    </div>
                  </div>
                </template>
              </zm-table-column>
              <zm-table-column
                :label="t('iotDevice.code')"
                align="center"
                prop="deviceCode"
                width="150"
                fixed="left"
                zm-sortable
                zm-filterable
                :zm-sort-method="handleZmSortChange"
                v-model:filter-model-value="queryParams.deviceCode">
                <template #filter="{ filterModelValue, updateFilterModelValue, close }">
                  <div class="p-2">
                    <el-input
                      :model-value="filterModelValue"
                      placeholder="请输入历史编码"
                      clearable
                      @update:model-value="updateFilterModelValue"
                      @keyup.enter="() => confirmColumnFilter(close)" />
                    <div class="mt-2 flex justify-end gap-2">
                      <el-button
                        size="small"
                        @click="() => clearColumnFilter(updateFilterModelValue, close)">
                        清空
                      </el-button>
                      <el-button
                        size="small"
                        type="primary"
                        :icon="Search"
                        @click="() => confirmColumnFilter(close)">
                        搜索
                      </el-button>
                    </div>
                  </div>
                </template>
              </zm-table-column>

              <zm-table-column
                :label="t('iotDevice.name')"
                align="center"
                prop="deviceName"
                min-width="280"
                zm-sortable
                zm-filterable
                :zm-sort-method="handleZmSortChange"
                v-model:filter-model-value="queryParams.deviceName">
                <template #filter="{ filterModelValue, updateFilterModelValue, close }">
                  <div class="p-2">
                    <el-input
                      :model-value="filterModelValue"
                      placeholder="请输入设备名称"
                      clearable
                      @update:model-value="updateFilterModelValue"
                      @keyup.enter="() => confirmColumnFilter(close)" />
                    <div class="mt-2 flex justify-end gap-2">
                      <el-button
                        size="small"
                        @click="() => clearColumnFilter(updateFilterModelValue, close)">
                        清空
                      </el-button>
                      <el-button
                        size="small"
                        type="primary"
                        :icon="Search"
                        @click="() => confirmColumnFilter(close)">
                        搜索
                      </el-button>
                    </div>
                  </div>
                </template>

                <template #default="scope">
                  <el-link :underline="false" type="primary" @click="handleDetail(scope.row.id)">
                    {{ scope.row.deviceName }}
                  </el-link>
                </template>
              </zm-table-column>
              <zm-table-column
                label="设备号"
                align="center"
                prop="deviceNo"
                width="120"
                zm-sortable
                zm-filterable
                :zm-sort-method="handleZmSortChange"
                v-model:filter-model-value="queryParams.deviceNo">
                <template #filter="{ filterModelValue, updateFilterModelValue, close }">
                  <div class="p-2">
                    <el-input
                      :model-value="filterModelValue"
                      placeholder="请输入设备号"
                      clearable
                      @update:model-value="updateFilterModelValue"
                      @keyup.enter="() => confirmColumnFilter(close)" />
                    <div class="mt-2 flex justify-end gap-2">
                      <el-button
                        size="small"
                        @click="() => clearColumnFilter(updateFilterModelValue, close)">
                        清空
                      </el-button>
                      <el-button
                        size="small"
                        type="primary"
                        :icon="Search"
                        @click="() => confirmColumnFilter(close)">
                        搜索
                      </el-button>
                    </div>
                  </div>
                </template>
              </zm-table-column>
              <zm-table-column
                :label="t('iotDevice.dept')"
                align="center"
                prop="deptName"
                min-width="150"
                zm-filterable
                v-model:filter-model-value="queryParams.deptId">
                <template #filter="{ filterModelValue, updateFilterModelValue, close }">
                  <div class="p-2">
                    <el-tree-select
                      :model-value="filterModelValue"
                      :data="deptList"
                      :props="defaultProps"
                      check-strictly
                      node-key="id"
                      filterable
                      placeholder="请选择所在部门"
                      class="w-full"
                      @update:model-value="updateFilterModelValue" />
                    <div class="mt-2 flex justify-end gap-2">
                      <el-button
                        size="small"
                        @click="() => clearColumnFilter(updateFilterModelValue, close)">
                        清空
                      </el-button>
                      <el-button
                        size="small"
                        type="primary"
                        :icon="Search"
                        @click="() => confirmColumnFilter(close)">
                        搜索
                      </el-button>
                    </div>
                  </div>
                </template>
              </zm-table-column>
              <zm-table-column
                :label="t('iotDevice.status')"
                align="center"
                prop="deviceStatus"
                min-width="150"
                zm-filterable
                v-model:filter-model-value="queryParams.deviceStatus">
                <template #filter="{ filterModelValue, updateFilterModelValue, close }">
                  <div class="p-2">
                    <el-select
                      :model-value="filterModelValue"
                      placeholder="请选择设备状态"
                      clearable
                      class="w-full"
                      @update:model-value="updateFilterModelValue">
                      <el-option
                        v-for="item in getStrDictOptions(DICT_TYPE.PMS_DEVICE_STATUS)"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value" />
                    </el-select>
                    <div class="mt-2 flex justify-end gap-2">
                      <el-button
                        size="small"
                        @click="() => clearColumnFilter(updateFilterModelValue, close)">
                        清空
                      </el-button>
                      <el-button
                        size="small"
                        type="primary"
                        :icon="Search"
                        @click="() => confirmColumnFilter(close)">
                        搜索
                      </el-button>
                    </div>
                  </div>
                </template>
                <template #default="scope">
                  <dict-tag :type="DICT_TYPE.PMS_DEVICE_STATUS" :value="scope.row.deviceStatus" />
                </template>
              </zm-table-column>
              <zm-table-column
                :label="t('deviceForm.model')"
                align="center"
                prop="model"
                min-width="170"
                zm-filterable
                v-model:filter-model-value="queryParams.model">
                <template #filter="{ filterModelValue, updateFilterModelValue, close }">
                  <div class="p-2">
                    <el-input
                      :model-value="filterModelValue"
                      placeholder="请输入规格型号"
                      clearable
                      @update:model-value="updateFilterModelValue"
                      @keyup.enter="() => confirmColumnFilter(close)" />
                    <div class="mt-2 flex justify-end gap-2">
                      <el-button
                        size="small"
                        @click="() => clearColumnFilter(updateFilterModelValue, close)">
                        清空
                      </el-button>
                      <el-button
                        size="small"
                        type="primary"
                        :icon="Search"
                        @click="() => confirmColumnFilter(close)">
                        搜索
                      </el-button>
                    </div>
                  </div>
                </template>
              </zm-table-column>

              <zm-table-column
                align="center"
                :label="t('deviceForm.mfg')"
                prop="manufacturer"
                zm-filterable
                v-model:filter-model-value="queryParams.manufacturerId">
                <template #filter="{ filterModelValue, updateFilterModelValue, close }">
                  <div class="p-2">
                    <el-select
                      :model-value="filterModelValue"
                      filterable
                      :teleported="false"
                      :loading="brandList.length === 0"
                      loading-text="数据加载中..."
                      placeholder="请选择制造厂家"
                      class="w-full"
                      @update:model-value="updateFilterModelValue"
                      @visible-change="handleBrandChange">
                      <el-option
                        v-for="item in brandList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id" />
                    </el-select>
                    <div class="mt-2 flex justify-end gap-2">
                      <el-button
                        size="small"
                        @click="() => clearColumnFilter(updateFilterModelValue, close)">
                        清空
                      </el-button>
                      <el-button
                        size="small"
                        type="primary"
                        :icon="Search"
                        @click="() => confirmColumnFilter(close)">
                        搜索
                      </el-button>
                    </div>
                  </div>
                </template>
              </zm-table-column>

              <zm-table-column
                label="车牌号"
                align="center"
                prop="carNo"
                min-width="170"
                zm-filterable
                v-model:filter-model-value="queryParams.carNo">
                <template #filter="{ filterModelValue, updateFilterModelValue, close }">
                  <div class="p-2">
                    <el-input
                      :model-value="filterModelValue"
                      placeholder="请输入车牌号"
                      clearable
                      @update:model-value="updateFilterModelValue"
                      @keyup.enter="() => confirmColumnFilter(close)" />
                    <div class="mt-2 flex justify-end gap-2">
                      <el-button
                        size="small"
                        @click="() => clearColumnFilter(updateFilterModelValue, close)">
                        清空
                      </el-button>
                      <el-button
                        size="small"
                        type="primary"
                        :icon="Search"
                        @click="() => confirmColumnFilter(close)">
                        搜索
                      </el-button>
                    </div>
                  </div>
                </template>
              </zm-table-column>

              <zm-table-column
                :label="t('deviceForm.brand')"
                align="center"
                prop="brandName"
                min-width="150"
                zm-filterable
                v-model:filter-model-value="queryParams.brandName">
                <template #filter="{ filterModelValue, updateFilterModelValue, close }">
                  <div class="p-2">
                    <el-input
                      :model-value="filterModelValue"
                      placeholder="请输入品牌"
                      clearable
                      @update:model-value="updateFilterModelValue"
                      @keyup.enter="() => confirmColumnFilter(close)" />
                    <div class="mt-2 flex justify-end gap-2">
                      <el-button
                        size="small"
                        @click="() => clearColumnFilter(updateFilterModelValue, close)">
                        清空
                      </el-button>
                      <el-button
                        size="small"
                        type="primary"
                        :icon="Search"
                        @click="() => confirmColumnFilter(close)">
                        搜索
                      </el-button>
                    </div>
                  </div>
                </template>
              </zm-table-column>

              <zm-table-column
                :label="t('iotDevice.assetClass')"
                align="center"
                prop="assetClassName"
                min-width="170"
                zm-filterable
                v-model:filter-model-value="queryParams.assetClass">
                <template #filter="{ filterModelValue, updateFilterModelValue, close }">
                  <div class="p-2">
                    <el-tree-select
                      :model-value="filterModelValue"
                      :data="productClassifyList"
                      :props="defaultProps"
                      check-strictly
                      node-key="id"
                      :placeholder="t('deviceForm.categoryHolder')"
                      filterable
                      class="w-full"
                      @update:model-value="updateFilterModelValue" />
                    <div class="mt-2 flex justify-end gap-2">
                      <el-button
                        size="small"
                        @click="() => clearColumnFilter(updateFilterModelValue, close)">
                        清空
                      </el-button>
                      <el-button
                        size="small"
                        type="primary"
                        :icon="Search"
                        @click="() => confirmColumnFilter(close)">
                        搜索
                      </el-button>
                    </div>
                  </div>
                </template>
              </zm-table-column>

              <zm-table-column
                :label="t('iotDevice.assets')"
                align="center"
                prop="assetProperty"
                min-width="110"
                zm-filterable
                v-model:filter-model-value="queryParams.assetProperty">
                <template #filter="{ filterModelValue, updateFilterModelValue, close }">
                  <div class="p-2">
                    <el-select
                      :model-value="filterModelValue"
                      :placeholder="t('iotDevice.assetsHolder')"
                      clearable
                      class="w-full"
                      @update:model-value="updateFilterModelValue">
                      <el-option
                        v-for="item in getStrDictOptions(DICT_TYPE.PMS_ASSET_PROPERTY)"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value" />
                    </el-select>
                    <div class="mt-2 flex justify-end gap-2">
                      <el-button
                        size="small"
                        @click="() => clearColumnFilter(updateFilterModelValue, close)">
                        清空
                      </el-button>
                      <el-button
                        size="small"
                        type="primary"
                        :icon="Search"
                        @click="() => confirmColumnFilter(close)">
                        搜索
                      </el-button>
                    </div>
                  </div>
                </template>
                <template #default="scope">
                  <dict-tag :type="DICT_TYPE.PMS_ASSET_PROPERTY" :value="scope.row.assetProperty" />
                </template>
              </zm-table-column>

              <zm-table-column
                :label="t('devicePerson.rp')"
                align="center"
                prop="chargeName"
                min-width="170"
                zm-filterable
                v-model:filter-model-value="queryParams.chargeName">
                <template #filter="{ filterModelValue, updateFilterModelValue, close }">
                  <div class="p-2">
                    <el-input
                      :model-value="filterModelValue"
                      placeholder="请输入责任人"
                      clearable
                      @update:model-value="updateFilterModelValue"
                      @keyup.enter="() => confirmColumnFilter(close)" />
                    <div class="mt-2 flex justify-end gap-2">
                      <el-button
                        size="small"
                        @click="() => clearColumnFilter(updateFilterModelValue, close)">
                        清空
                      </el-button>
                      <el-button
                        size="small"
                        type="primary"
                        :icon="Search"
                        @click="() => confirmColumnFilter(close)">
                        搜索
                      </el-button>
                    </div>
                  </div>
                </template>
              </zm-table-column>
              <zm-table-column
                :label="t('deviceForm.useProject')"
                align="center"
                prop="useProject"
                min-width="170"
                zm-filterable
                v-model:filter-model-value="queryParams.useProject">
                <template #filter="{ filterModelValue, updateFilterModelValue, close }">
                  <div class="p-2">
                    <el-input
                      :model-value="filterModelValue"
                      placeholder="请输入使用项目"
                      clearable
                      @update:model-value="updateFilterModelValue"
                      @keyup.enter="() => confirmColumnFilter(close)" />
                    <div class="mt-2 flex justify-end gap-2">
                      <el-button
                        size="small"
                        @click="() => clearColumnFilter(updateFilterModelValue, close)">
                        清空
                      </el-button>
                      <el-button
                        size="small"
                        type="primary"
                        :icon="Search"
                        @click="() => confirmColumnFilter(close)">
                        搜索
                      </el-button>
                    </div>
                  </div>
                </template>
              </zm-table-column>
              <zm-table-column
                :label="t('deviceForm.assetOwner')"
                align="center"
                prop="assetOwnership"
                min-width="170"
                zm-filterable
                v-model:filter-model-value="queryParams.assetOwnership">
                <template #filter="{ filterModelValue, updateFilterModelValue, close }">
                  <div class="p-2">
                    <el-input
                      :model-value="filterModelValue"
                      placeholder="请输入资产归属"
                      clearable
                      @update:model-value="updateFilterModelValue"
                      @keyup.enter="() => confirmColumnFilter(close)" />
                    <div class="mt-2 flex justify-end gap-2">
                      <el-button
                        size="small"
                        @click="() => clearColumnFilter(updateFilterModelValue, close)">
                        清空
                      </el-button>
                      <el-button
                        size="small"
                        type="primary"
                        :icon="Search"
                        @click="() => confirmColumnFilter(close)">
                        搜索
                      </el-button>
                    </div>
                  </div>
                </template>
              </zm-table-column>
              <zm-table-column
                label="所在地点"
                min-width="120"
                align="center"
                prop="address"
                zm-filterable
                v-model:filter-model-value="queryParams.address">
                <template #filter="{ filterModelValue, updateFilterModelValue, close }">
                  <div class="p-2">
                    <el-input
                      :model-value="filterModelValue"
                      placeholder="请输入所在地点"
                      clearable
                      @update:model-value="updateFilterModelValue"
                      @keyup.enter="() => confirmColumnFilter(close)" />
                    <div class="mt-2 flex justify-end gap-2">
                      <el-button
                        size="small"
                        @click="() => clearColumnFilter(updateFilterModelValue, close)">
                        清空
                      </el-button>
                      <el-button
                        size="small"
                        type="primary"
                        :icon="Search"
                        @click="() => confirmColumnFilter(close)">
                        搜索
                      </el-button>
                    </div>
                  </div>
                </template>
              </zm-table-column>
              <zm-table-column
                :label="t('operationFill.operation')"
                align="center"
                min-width="150px"
                fixed="right"
                action>
                <template #default="scope">
                  <el-button
                    link
                    type="primary"
                    @click="openForm('update', scope.row.id)"
                    v-hasPermi="['rq:iot-device:update']">
                    {{ t('iotDevice.update') }}
                  </el-button>
                  <el-button
                    link
                    type="danger"
                    @click="handleDelete(scope.row.id)"
                    v-hasPermi="['rq:iot-device:delete']">
                    {{ t('iotDevice.delete') }}
                  </el-button>
                  <!--              <el-button link type="warning" @click="handleUpload(scope.row.id)">-->
                  <!--                {{t('iotDevice.upload')}}-->
                  <!--              </el-button>-->
                </template>
              </zm-table-column>
            </zm-table>
          </template>
        </el-auto-resizer>
      </div>
      <!-- 分页 -->
      <div class="h-8 mt-2 flex items-center justify-end">
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import download from '@/utils/download'
import { IotDeviceApi, IotDeviceVO } from '@/api/pms/device'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import { useUserStore } from '@/store/modules/user'

import { defaultProps, handleTree } from '@/utils/tree'
import * as ProductClassifyApi from '@/api/pms/productclassify'
import { useRefreshStore } from '@/store/modules/pms/refreshStore'
import { Search } from '@element-plus/icons-vue'
import * as DeptApi from '@/api/system/dept'
import { useTableComponents } from '@/components/ZmTable/useTableComponents'
import DeviceTotalCard from './components/dashboard/DeviceTotalCard.vue'
import DeviceStatusCard from './components/dashboard/DeviceStatusCard.vue'
import DeviceClassifyTopCard from './components/dashboard/DeviceClassifyTopCard.vue'
const { ZmTable, ZmTableColumn } = useTableComponents()

/** 设备台账 列表 */
defineOptions({ name: 'IotDevicePms' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const { push } = useRouter() // 路由跳转
const deptList = ref<Tree[]>([]) // 树形结构
const route = useRoute()
const rootDeptId = 156
const deptId = useUserStore().getUser.deptId || rootDeptId

const refreshStore = useRefreshStore()
const loading = ref(true) // 列表的加载中
const ifShow = ref(false)
const list = ref<IotDeviceVO[]>([]) // 列表的数据
const productClassifyList = ref<Tree[]>([]) // 树形结构
const total = ref(0) // 列表的总页数
const queryParams = reactive<any>({
  pageNo: 1,
  pageSize: 10,
  useProject: undefined,
  assetOwnership: undefined,
  address: undefined,
  deviceCode: undefined,
  deviceName: undefined,
  brand: undefined,
  brandName: undefined,
  model: undefined,
  deptId: undefined,
  deviceStatus: undefined,
  assetProperty: undefined,
  picUrl: undefined,
  remark: undefined,
  manufacturerId: undefined,
  supplierId: undefined,
  manDate: [],
  nameplate: undefined,
  expires: undefined,
  plPrice: undefined,
  plDate: [],
  plYear: undefined,
  plStartDate: [],
  plMonthed: undefined,
  plAmounted: undefined,
  remainAmount: undefined,
  infoId: undefined,
  infoType: undefined,
  infoName: undefined,
  infoRemark: undefined,
  infoUrl: undefined,
  templateJson: undefined,
  creator: undefined,
  sortingFields: [],
  assetClass: undefined,
  yfDeviceCode: undefined,
  carNo: undefined,
  deviceNo: undefined,
  manufacturer: undefined,
  chargeName: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const brandList = ref<any[]>([])
const dashboardLoading = ref(false)
const dashboardTotal = ref(0)
const dashboardStatus = ref<any[]>([])
const dashboardClassify = ref<any[]>([])

const dashboardQueryParams = reactive({
  deptId: undefined as number | undefined,
  yfDeviceCode: undefined as string | undefined,
  deviceCode: undefined as string | undefined,
  deviceName: undefined as string | undefined,
  carNo: undefined as string | undefined,
  deviceNo: undefined as string | undefined,
  brandName: undefined as string | undefined,
  deviceStatus: undefined as string | undefined,
  assetProperty: undefined as string | undefined,
  assetClass: undefined as number | string | undefined
})

const handleZmSortChange = (prop: string, order: 'asc' | 'desc' | null) => {
  queryParams.sortingFields = order ? [{ field: prop, order }] : []
  getList()
}

const confirmColumnFilter = (close?: () => void) => {
  handleQuery()
  close?.()
}

const clearColumnFilter = (updateFilterModelValue: (value: any) => void, close?: () => void) => {
  updateFilterModelValue(undefined)
  confirmColumnFilter(close)
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await IotDeviceApi.getIotDevicePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const syncDashboardQuery = () => {
  dashboardQueryParams.deptId = queryParams.deptId
  dashboardQueryParams.yfDeviceCode = queryParams.yfDeviceCode
  dashboardQueryParams.deviceCode = queryParams.deviceCode
  dashboardQueryParams.deviceName = queryParams.deviceName
  dashboardQueryParams.carNo = queryParams.carNo
  dashboardQueryParams.deviceNo = queryParams.deviceNo
  dashboardQueryParams.brandName = queryParams.brandName
  dashboardQueryParams.deviceStatus = queryParams.deviceStatus
  dashboardQueryParams.assetProperty = queryParams.assetProperty
  dashboardQueryParams.assetClass = queryParams.assetClass
}

const getDashboardData = async () => {
  dashboardLoading.value = true
  syncDashboardQuery()
  try {
    const [count, status, classify] = await Promise.all([
      IotDeviceApi.getIotDeviceCount(dashboardQueryParams),
      IotDeviceApi.getIotDeviceStatus(dashboardQueryParams),
      IotDeviceApi.getIotDeviceClassify(dashboardQueryParams)
    ])
    dashboardTotal.value = Number(count ?? 0)
    dashboardStatus.value = Array.isArray(status) ? status : []
    dashboardClassify.value = Array.isArray(classify) ? classify : []
  } finally {
    dashboardLoading.value = false
  }
}

/** 处理部门被点击 */
const syncRouteCodeQuery = () => {
  queryParams.yfClass = route.query.code ? String(route.query.code) : undefined
}

const handleDeptNodeClick = async (row) => {
  queryParams.deptId = row.id
  await Promise.all([getList(), getDashboardData()])
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}
const moreQuery = (show) => {
  ifShow.value = show
}
/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.chargeName = undefined
  queryParams.address = undefined
  queryParams.manufacturer = undefined
  queryParams.useProject = undefined
  queryParams.model = undefined
  queryParams.assetOwnership = undefined
  queryParams.manufacturerId = undefined
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const openForm = (type: string, id?: number, deptId?: number) => {
  //修改
  if (typeof id === 'number') {
    push({
      name: 'DeviceDetailForm',
      query: { source: 'devicerouter', type, id, deptId }
    })
    return
  }
  // 新增
  if (deptId) {
    push({
      name: 'DeviceDetailForm',
      query: { source: 'devicerouter', type, deptId }
    })
  } else {
    push({ name: 'DeviceDetailForm', query: { source: 'devicerouter', type } })
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await IotDeviceApi.deleteIotDevice(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

const handleDetail = (id: number) => {
  push({ name: 'DeviceDetailInfo', params: { id } })
}

const handleBrandChange = async (visible) => {
  if (visible && brandList.value.length === 0) {
    brandList.value = await IotDeviceApi.getDeviceBrand()
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await IotDeviceApi.exportIotDevice(queryParams)
    download.excel(data, '设备台账.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(async () => {
  syncRouteCodeQuery()
  productClassifyList.value = handleTree(
    await ProductClassifyApi.IotProductClassifyApi.getSimpleProductClassifyList()
  )

  // brandList.value = await IotDeviceApi.getDeviceBrand()
  const sort = {
    field: 'sortColumn',
    order: 'asc'
  }
  queryParams.sortingFields.push(sort)
  await Promise.all([getList(), getDashboardData()])
  refreshStore.registerCallback('devicerouter', () => {
    Promise.all([getList(), getDashboardData()])
  })

  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
})

watch(
  () => route.query.code,
  async () => {
    syncRouteCodeQuery()
    await Promise.all([getList(), getDashboardData()])
  }
)
</script>
<style scoped lang="scss">
@media (width <= 1440px) {
  .device-dashboard-grid {
    grid-template-columns: minmax(180px, 0.7fr) minmax(390px, 1fr) minmax(360px, 1.35fr);
  }
}

:deep(.el-form-item) {
  margin-bottom: 0;
}

.device-dashboard-grid {
  display: grid;
  grid-template-columns: minmax(190px, 0.55fr) minmax(430px, 1.18fr) minmax(420px, 1.42fr);
  gap: 12px;
  min-height: 164px;
}

::v-deep .el-table__header-wrapper {
  position: sticky !important;
  top: 0;
  z-index: 2000;
  width: 100%;
}

::v-deep .el-tooltip__trigger {
  border: none !important;
  outline: none !important;
}

::v-deep .el-table__header-wrapper {
  position: sticky !important;
  top: 0;
  z-index: 2000;
  width: 100%;
}

::v-deep .el-tooltip__trigger {
  border: none !important;
  outline: none !important;
}

/* 表头对齐样式 */
.table-header-flex {
  display: flex !important;
  width: 100% !important;
  height: 100% !important;
  padding: 0 !important;
  align-items: center !important;
  justify-content: center !important;
}

.table-header-text {
  font-size: 12px;
  color: #606266;
  text-align: center;
  flex: 1;
}

.header-arrow-icon {
  margin-left: 4px;
  font-size: 12px;
  color: #ad9399;
  cursor: pointer;
}

.popover-content-flex {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 修复单元格对齐 */
::v-deep .el-table th,
::v-deep .el-table td {
  padding: 6px 0 !important;
}

::v-deep .el-table th .cell,
::v-deep .el-table td .cell {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 0 8px;
}
</style>
