<template>
  <div class="equipment-list">

    <div class="search">
  
      <div class="inp-item">
        <div class="i-name">设备编码：</div>
        <div class="i-content">
          <el-input v-model="params.deviceCode" class="x-inp" placeholder="请输入..." />
        </div>
      </div>

      <div class="inp-item">
        <div class="i-name">设备名称：</div>
        <div class="i-content">
          <el-input v-model="params.deviceName" class="x-inp" placeholder="请输入..." />
        </div>
      </div>

      <div class="inp-item">
        <div class="i-name">隧道所：</div>
        <div class="i-content">
          <el-input v-model="params.tunnelgroup" class="x-inp" placeholder="请输入..." />
        </div>
      </div>

      <div class="inp-item">
        <div class="i-name">隧道方向：</div>
        <div class="i-content">
          <AsyncSelect v-model="params.directionUpdown" code="tunnel_direction" />
        </div>
      </div>

      <div class="inp-item">
        <div class="i-name">设备IP：</div>
        <div class="i-content">
          <el-input v-model="params.deviceIp"  class="x-inp" placeholder="请输入..." />
        </div>
      </div>

      <div class="inp-item">
        <div class="i-name">UUID：</div>
        <div class="i-content">
          <el-input v-model="params.deviceUuid" class="x-inp" placeholder="请输入..." />
        </div>
      </div>

      <div class="btns">
        <el-button @click="getEquipments" type="primary">搜索</el-button>
        <el-button @click="clean">重置</el-button>
      </div>

    </div>

    <div class="btns">
      <el-button @click="goCtrls('new')" type="primary">新增</el-button>

      <!--<div>
        <el-upload
          class="import-btn"
          ref="uploadRef"
          :headers="{
            authorization: `Bearer ${getAccessToken()}`,
            'tenant-id': 1
          }"
          :action="UPLOAD_URL"
          :limit="1"
          :show-file-list="false"
          :on-success="e => importHandle(e, 'success')"
          :on-error="e => importHandle(e, 'error')"
          :on-exceed="handleExceed"
          accept=".xls,.xlsx"
        >
          <template #trigger>
            <el-button type="primary">导入</el-button>
          </template>
        
        </el-upload>
      </div>

      <el-button :disabled="outloading" @click="importOut" type="primary">
        导出 {{ outloading ? '中...' : '' }}
      </el-button>-->

      <el-button v-if="selectedIds.length" @click="clearSelected" type="primary">
        清除选中
      </el-button>

      <!--<el-link
        class="xlink"
        :underline="false"
        :href="TEMPLATE_URL + '/excel/全息隧道设备导入模板.xlsx'"
      >
        <el-button>下载导入模板</el-button>
      </el-link>-->
    </div>

    <el-table
      ref="equipmentTable"
      :data="listData"
      :row-class-name="
        ({ rowIndex }) => {
          return rowIndex % 2 === 0 ? 'stripe-row' : ''
        }
      "
      @selection-change="selectChange"
      class="car-table"
      
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="deviceCode" label="设备编码" width="200" />
      <el-table-column prop="deviceName" label="设备名称" />
      <el-table-column prop="module" label="设备小类" width="200" />
      <el-table-column prop="areacenter" label="管理中心" width="150" />
      <el-table-column prop="deptName" label="隧道所" width="150" />
      <el-table-column prop="tunnelname" label="所属设施" width="100" />
      <el-table-column prop="directionName" label="隧道方向" width="100" />
      <el-table-column prop="deviceIp" label="设备IP" width="120" />
      <el-table-column prop="deviceUuid" label="UUID" width="200" />
      <el-table-column align="center" label="操作" width="200">
        <template #default="{ row }">
          <div class="btns">
            <div @click="goCtrls('check', row)" class="def-btn">查看</div>
            <div class="dv-line"></div>
            <div @click="goCtrls('edit', row)" class="def-btn">编辑</div>
            <div class="dv-line"></div>
            <div @click="goCtrls('delete', row)" class="def-btn">删除</div>
          </div>
        </template>
      </el-table-column>

      <template #empty>
        <div class="empty">
          <span v-if="!loading">没有数据</span>
        </div>
      </template>
    </el-table>

    <!-- 分页 -->
    <div class="pages">
      <div class="sum">共 {{ params.total }} 条</div>

      <el-select
        class="page-select"
        :teleported="false"
        @change="getEquipments()"
        v-model="params.pageSize"
      >
        <el-option
          v-for="item in [10, 20, 30, 50]"
          :key="item"
          :label="item + '条/页'"
          :value="item"
        />
      </el-select>

      <el-pagination
        v-if="params.total / params.pageSize > 1"
        :page-size="params.pageSize"
        layout="prev, pager, next"
        :total="params.total"
        class="car-pages"
        @change="getEquipments"
      />
    </div>
  </div>

  <EquipmentModel @update="getEquipments" :facilities ref="equipmentRef" />
</template>

<script lang="ts" setup>

import download from '@/utils/download'
import EquipmentModel from '../EquipmentModel/index.vue'
import { importOutTunnelCameras } from '@/api/system'
import { getAccessToken } from '@/utils/auth'

import { genFileId } from 'element-plus'

import { ref, reactive, withDefaults } from 'vue'
import { getEquipmentBasics, equipmentDelete } from '@/api/system'
import AsyncSelect from '@/components/AsyncSelect/index.vue'
import { numToStone } from '@/utils/tunnel'

const UPLOAD_URL = import.meta.env.VITE_TUNNEL_UPLOAD_URL
const TEMPLATE_URL = import.meta.env.VITE_TEMPLATE_BASE

const emits = defineEmits(['equipment-aysnc'])
const uploadRef = ref<any>(null)

const props = withDefaults(defineProps<{
  facilities: any[]
}>(), {
  facilities: () => []
})

const outloading = ref(false) // 导出状态

const facilityMap = computed(() => {
  return Object.fromEntries(props.facilities.map(item => {
    return [item.id, item]
  }))
})


const equipmentRef = ref<any>(null) // 隧道模型弹窗
const equipmentTable = ref<any>(null) // table 实例
const listData = ref<any[]>([])
const loading = ref(true)
const selectMap = ref<any>({})

const params = reactive({
  deviceCode: '',
  deviceName: '',
  tunnelgroup: '',
  directionUpdown: null,
  deviceIp: '',
  deviceUuid: '',
  pageNo: 1,
  pageSize: 10,
  total: 0
})

const clean = () => {
  params.deviceCode = ''
  params.deviceName = ''
  params.tunnelgroup = ''
  params.directionUpdown = null
  params.deviceIp = ''
  params.deviceUuid = ''
  params.pageNo = 1
  getEquipments()
}


const selectedIds = computed(() => {
  return Object.values(selectMap.value).flat()
})

const goCtrls = (type, row?) => {

  if (type === 'delete') {
    ElMessageBox.confirm(
      `确认要删除设施【${row.deviceName}】吗？`,
      '注意',
      {
        confirmButtonText: '确定',
      cancelButtonClass: 'cancelButtonClass',

        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
      equipmentDelete({id: row.id}).then(res => {
        if (res) {
          getEquipments()
        }
      })
    }).catch()
  } else {
    equipmentRef.value.diaOpen(type, row)
  }

}

// 导入处理
const importHandle = (e, type) => {

  if (type === 'success') {
    if (e.msg) {
      ElMessage.error(e.msg)
    }
  }
}

// 导出处理
const importOut = () => {
  if (outloading.value) return
  outloading.value = true
  importOutTunnelCameras({
    ...params,
    ids: selectedIds.value,
  }).then(res => {
    download.excel(res, '设备模型.xls')
    outloading.value = false
  })
}

// 获取列表
const getEquipments = (x?: number) => {

  params.pageNo = x || 1

  loading.value = true
  getEquipmentBasics(params).then(res => {

    listData.value = res.list
    params.total = res.total
    emits('equipment-aysnc', res.total)

    const selecteds = selectMap.value[params.pageNo] || []

    nextTick(() => {
      res.list.forEach(item => {
        if (selecteds.includes(item.id)) {
          equipmentTable.value!.toggleRowSelection(item, true)
        }
      })
    })
  })

}

// 导入超限处理
const handleExceed = (files) => {
  uploadRef.value!.clearFiles()
  const file = files[0] as any
  file.uid = genFileId()
  uploadRef.value!.handleStart(file)
  uploadRef.value!.submit()
}

// 导出选择处理
const selectChange = (e) => {
  selectMap.value[params.pageNo] = e.map(item => item.id)
}

// 清除选中
const clearSelected = () => {
  selectMap.value = {}
  equipmentTable.value!.clearSelection()
}

onBeforeMount(() => {
  getEquipments()
})


</script>

<style lang="scss" scoped>

.search {
  margin: 20px 0;
  display: flex;
  flex-wrap: wrap;
  color: white;
  background: rgba(69, 116, 182, 0.2);
  box-shadow: 0px 2px 12px 0px rgba(0, 0, 0, 0.1);
  padding: 18px 48px;
  border-radius: 8px;
  
  .inp-item {
    display: flex;
    align-items: center;
    margin-right: 60px;
    .i-name {
      font-size: 14px;
      width: 72px;
    }
    .i-content {
      display: flex;
      align-items: center;
      color: white;
      & > span {
        white-space: nowrap;
      }
      :deep(.el-select) {
        width: 300px;
      }
    }
  }
  .x-inp {
    width: 300px;
  }
  .num-inp {
    width: 126px;
    margin: 0 5px;
  }
  .btns {
    display: flex;
    align-items: center;
    :deep(.el-button) {
      &:first-child {
        background: rgba(18, 112, 255, 1);
      }
      &:last-child {
        background: rgba(0, 125, 250, 0.15);
        color: white;
        border: 1px solid rgba(255, 255, 255, 0.29);
        &:hover {
          border-color: rgba(255, 255, 255, 0.5);
        }
      }
    }
  }
}

.equipment-list {
  margin: 16px 40px 0;
  .btns {
    margin: 10px 0;
    .import-btn {
      margin: 0 10px;
    }
    .xlink {
      display: block;
      height: 100%;
      margin-left: 10px;
    }
  }
  .empty {
    color: rgba(240, 245, 255, 0.45);
    height: 300px;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .btns {
    display: inline-flex;
    align-items: center;
    justify-content: space-between;
    .def-btn {
      cursor: pointer;
      color: #00AEFF;
      font-weight: 600;
      margin: 0 8px;
    }
    .dv-line {
      height: 12px;
      width: 1px;
      background: rgba(240, 245, 255, 0.45);
      margin: 0 8px;
    }
    .deal-btn {
      box-sizing: border-box;
      background: #1270FF;
      height: 24px;
      color: white;
      border-radius: 2px;
      padding: 0 8px;
      border: 1px solid rgba(155, 193, 255, 0.2);
      margin: 0 8px;
      cursor: pointer;
      &:hover {
        border: 1px solid rgba(155, 193, 255, 1);
      }
    }
  }

  .pages {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    color: white;
    .sum {
      margin-right: 20px;
    }
    .page-select {
      width: 128px;
      margin-right: 20px;
      :deep(.el-select__wrapper) {
        border-radius: 0;
        background: rgba(32, 58, 96, 0.6);
        border: 1px solid rgba(32, 58, 96, 0.6);
        box-shadow: 0 0 0;
        
        .el-select__placeholder {

          color: white;
        } 
      }
    }
  }
}

.car-table {
  :deep(.el-checkbox__inner) {
    background: transparent;
  }
}

</style>
