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

    <el-table
      :data="listData"
      :row-class-name="
        ({ rowIndex }) => {
          return rowIndex % 2 === 0 ? 'stripe-row' : ''
        }
      "
      class="car-table"
    >
      <el-table-column prop="tunnelCode" label="设施编号" width="200" />
      <el-table-column prop="tunnelName" label="设施名称" />
      <el-table-column prop="road" label="所属路段" width="200" />
      <el-table-column prop="deptName" label="隧道所" width="200" />
      <el-table-column prop="tunnelTypeName" label="隧道类型" width="200" />

      <el-table-column prop="tunnelDept" label="应用状态" width="200">
        <template #default="{ row }">
          <el-switch
            class="x-switch"
            v-model="row.enable"
            :loading="row.useLoading"
            inline-prompt
            active-text="启用"
            inactive-text="关闭"
            :active-value="1"
            :inactive-value="0"
            :before-change="() => stateChange(row)"
          />
        </template>
      </el-table-column>

      <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>

            <template v-if="!row.useEnable">
              <div class="dv-line"></div>
              <div @click="goCtrls('delete', row)" class="def-btn">删除</div>
            </template>
          </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"
        @change="getTunnelBasicsAct()"
        v-model="params.pageSize"
        :teleported="false"
      >
        <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="getTunnelBasicsAct"
      />
    </div>
  </div>

  <FacilityModel @update="onTunnelUpdate" ref="newRef" />
</template>

<script lang="ts" setup>
import FacilityModel from '../FacilityModel/index.vue'
import { TUNNEL_TYPES } from '@/config/dict'
import { ElMessageBox } from 'element-plus'
import { sleep } from '@/utils'
import bus from '@/utils/eventBus'

import { ref, reactive } from 'vue'
import { getTunnelBasics, tunnelDelete, enableFacility, disEnableFacility } from '@/api/system'

const newRef = ref<any>(null) // 隧道模型弹窗
const listData = ref<any[]>([])
const loading = ref(true)

const emits = defineEmits(['facility-async'])

const params = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0
})

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

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

// 获取列表
const getTunnelBasicsAct = (x?: number) => {
  params.pageNo = x || 1

  loading.value = true
  getTunnelBasics(params).then((res) => {
    listData.value = res.list.map((item) => {
      return {
        ...item,
        useEnable: item.enable === 1,
        useLoading: false
      }
    })
    params.total = res.total
    emits('facility-async', res)
  })
}

const onTunnelUpdate = () => {
  getTunnelBasicsAct()
  bus.emit('tunnel-updated')
}

// 隧道停启用
const stateChange = (row) => {

  function checkSingleEnable(data) {
    let enableCount = 0

    for (let item of data) {
      if (item.enable === 1) {
        enableCount++
      }
      if (enableCount > 1) {
        return false
      }
    }
    return enableCount === 1
  }


  // if (row.enable) {
  //   ElMessage.warning('必须有一个隧道启用！')
  //   return Promise.resolve(false)
  // }

  row.useLoading = true

  return new Promise(async (resolve) => {
    const act = listData.value.find(item => item.enable)

    if (act) {
      await disEnableFacility({ id: act.id })
    }

    await enableFacility({ id: row.id })


    ElMessage.success('启用成功！')

    if (act) {
      act.enable = 0
    }

    row.useLoading = false
    resolve(true)

    await sleep(1000)
    window.location.reload()
  })
}

onBeforeMount(() => {
  getTunnelBasicsAct()
})
</script>

<style lang="scss" scoped>
.faciility-list {
  margin: 16px 40px 0;
  .btns {
    margin: 10px 0;
  }
  .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 {
    .x-switch {
      :deep(.el-switch__core) {
        height: 26px;
        width: 52px;
        border-radius: 26px;
      }
    }
  }
}
</style>
