<template>
  <div>
    <div class="gva-search-box">
      <el-form
          ref="searchForm"
          :inline="true"
          :model="searchInfo"
      >
        <el-form-item label="名称或编码">
          <el-input
              v-model="searchInfo.keyword"
              placeholder="搜索名称或编码"
          />
        </el-form-item>
        <el-form-item>
          <el-button
              type="primary"
              icon="search"
              @click="onSubmit"
          >查询</el-button>
          <el-button
              icon="refresh"
              @click="onReset"
          >重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button
            type="primary"
            icon="plus"
            @click="add()"
        >新增</el-button>
      </div>
      <el-table
          :data="tableData"
          style="width: 100%; margin-bottom: 20px"
          row-key="id"
          border
          :table-layout="'fixed'"
          :row-class-name="tableRowClassName"
      >
        <el-table-column prop="gateway.id" label="#" :width="80"/>
        <el-table-column prop="gateway.gatewayName" label="网关名称" />
        <el-table-column prop="gateway.gatewayCode" label="编码">
          <template #default="scope">
            <el-tag effect="light">{{ scope.row.gateway.gatewayCode }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="gateway.gatewayBrand" label="品牌" />
        <el-table-column prop="gateway.gatewayModel" label="型号"/>
        <el-table-column prop="gateway.Intersect.intersectName" label="所属路口"/>
        <el-table-column prop="gateway.status" label="在线状态">
          <template #default="scope">
            <div class="onlinebox" :style="{'background': scope.row.gateway.status===0 ? 'red':'green' }"></div>
            <span :style="{ color: scope.row.gateway.status === 0 ? 'red' : 'green' }">{{ scope.row.gateway.status === 0 ? '离线' : '在线' }}</span>
          </template>
        </el-table-column>
        <el-table-column
            align="left"
            fixed="right"
            label="操作"
            :width="300"
        >
          <template #default="scope">
            <el-button
                type="primary"
                link
                icon="view"
                @click="view(scope.row)"
            >查看</el-button>
            <el-button
                type="primary"
                link
                icon="edit"
                @click="editGateway(scope.row)"
            >编辑</el-button>
            <el-button
                type="primary"
                link
                icon="delete"
                @click="deleteGateway(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10, 30, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
        />
      </div>

      <el-dialog v-model="addGatewayDialog" title="智慧网关" width="900">
        <el-form
            ref="gatewayForm"
            :rules="rules"
            :model="gatewayInfo"
            label-width="100px"
            style="padding: 15px"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="网关名称：" :inline="false" prop="gateway.gatewayName">
                <el-input v-model="gatewayInfo.gateway.gatewayName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="编码：" :inline="false">
                <el-input disabled v-model="gatewayInfo.gateway.gatewayCode"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="品牌：" :inline="false" prop="gateway.gatewayBrand">
                <el-input v-model="gatewayInfo.gateway.gatewayBrand"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="型号：" :inline="false" prop="gateway.gatewayModel">
                <el-input v-model="gatewayInfo.gateway.gatewayModel"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="ip地址：" :inline="false" prop="gateway.ipAddress">
                <el-input v-model="gatewayInfo.gateway.ipAddress"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属路口：" :inline="false" prop="gateway.intersectId">
                <el-select v-model="gatewayInfo.gateway.intersectId" placeholder="请选择所属路口">
                  <el-option v-for=" (item) in intersectList" :label="item.intersectName" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="安装时间：" :inline="false">
                <el-date-picker
                    v-model="gatewayInfo.gateway.installTime"
                    type="date"
                    placeholder="Pick a day"
                    size="default"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="closeAddGatewayDialog">取消</el-button>
            <el-button type="primary" @click="enterAddGatewayDialog">
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>

      <el-dialog v-model="viewGatewayDialog" title="详情" style="padding: 35px">
        <el-form
            :model="gatewayInfo"
            label-width="110px"
            style="padding: 20px"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="网关名称：" :inline="false">
                {{gatewayInfo.gateway.gatewayName }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="编码：" :inline="false">
                {{gatewayInfo.gateway.gatewayCode }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="品牌：" :inline="false">
                {{gatewayInfo.gateway.gatewayBrand }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="型号：" :inline="false">
                {{gatewayInfo.gateway.gatewayModel }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="ip地址：" :inline="false">
                {{gatewayInfo.gateway.ipAddress }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属路口：" :inline="false">
                {{gatewayInfo.gateway.Intersect.intersectName }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="安装时间：" :inline="false">
                {{gatewayInfo.gateway.installTime }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所在地址：" :inline="false">
                {{gatewayInfo.gateway.Intersect.address}}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="最近在线时间：" :inline="false">
                {{gatewayInfo.gateway.recentOnline === "0001-01-01 08:05:43"?'——':gatewayInfo.gateway.recentOnline}}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="在线状态：" :inline="false">
                <div class="onlinebox" :style="{'background': gatewayInfo.gateway.status===0 ? 'red':'green' }"></div>
                <span :style="{ color: gatewayInfo.gateway.status === 0 ? 'red' : 'green' }">{{ gatewayInfo.gateway.status === 0 ? '离线' : '在线' }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div style="padding: 20px 0px;font-weight: bolder; border-top: solid 1px #e8eaec">关联设备：</div>
        <el-tabs type="border-card" v-model="activeName">
          <el-tab-pane :label="'摄像机【'+cameracount+'】'" name="camera">
            <el-table :data="gatewayInfo.relationDev.cameraList" style="width: 100%" >
              <el-table-column fixed prop="shunt" label="所属分路" width="80px">
                <template #default="scope">
                  {{ scope.row.shunt==1?'主路':'支路' }}
                </template>
              </el-table-column>
              <el-table-column prop="cameraName" label="名称" width="150px"/>
              <el-table-column prop="cameraBrand" label="品牌" width="100px"/>
              <el-table-column prop="cameraModel" label="型号" width="250px"/>
              <el-table-column prop="ipAddress" label="ip地址" width="150px"/>
              <el-table-column prop="shuntDescribe" label="分路描述" width="200px"/>
              <el-table-column prop="status" fixed="right" label="状态" width="80px">
                <template #default="scope">
                  <div class="onlinebox" :style="{'background': scope.row.status===0 ? 'red':'green' }"></div>
                  <span :style="{ color: scope.row.status === 0 ? 'red' : 'green' }">{{ scope.row.status === 0 ? '离线' : '在线' }}</span>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane :label="'LED信息屏【'+screenscount+'】'" name="screens">
            <el-table :data="gatewayInfo.relationDev.screensList" style="width: 100%" :table-layout="'fixed'">
              <el-table-column fixed prop="shunt" label="所属分路" width="80px">
                <template #default="scope">
                  {{ scope.row.shunt==1?'主路':'支路' }}
                </template>
              </el-table-column>
              <el-table-column prop="screensName" label="名称" width="150px"/>
              <el-table-column prop="screensBrand" label="品牌" width="100px"/>
              <el-table-column prop="screensModel" label="型号" width="250px"/>
              <el-table-column prop="ipAddress" label="ip地址" width="150px"/>
              <el-table-column prop="shuntDescribe" label="分路描述" width="200px"/>
              <el-table-column prop="status" fixed="right" label="状态" width="80px">
                <template #default="scope">
                  <div class="onlinebox" :style="{'background': scope.row.status===0 ? 'red':'green' }"></div>
                  <span :style="{ color: scope.row.status === 0 ? 'red' : 'green' }">{{ scope.row.status === 0 ? '离线' : '在线' }}</span>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane :label="'雷达【'+radarcount+'】'" name="radar">
            <el-table :data="gatewayInfo.relationDev.radarList" style="width: 100%" :table-layout="'fixed'">
              <el-table-column fixed prop="shunt" label="所属分路" width="80px">
                <template #default="scope">
                  {{ scope.row.shunt==1?'主路':'支路' }}
                </template>
              </el-table-column>
              <el-table-column prop="radarName" label="名称" width="150px"/>
              <el-table-column prop="radarBrand" label="品牌" width="100px"/>
              <el-table-column prop="radarModel" label="型号" width="250px"/>
              <el-table-column prop="ipAddress" label="ip地址" width="150px"/>
              <el-table-column prop="shuntDescribe" label="分路描述" width="200px"/>
<!--              <el-table-column prop="status" fixed="right" label="状态" width="80px">-->
<!--                <template #default="scope">-->
<!--                  <div class="onlinebox" :style="{'background': scope.row.status===0 ? 'red':'green' }"></div>-->
<!--                  <span :style="{ color: scope.row.status === 0 ? 'red' : 'green' }">{{ scope.row.status === 0 ? '离线' : '在线' }}</span>-->
<!--                </template>-->
<!--              </el-table-column>-->
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-dialog>
    </div>
  </div>
</template>
<script setup>
import {addGateway, deleteBaseGateway, getGatewayList, getPublicIntersect, setGatewayInfo} from "@/api/gateway";
import {ref} from 'vue'
import {format,parseISO} from "date-fns";
import {ElMessage, ElMessageBox} from "element-plus";

const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({})
const gatewayInfo = ref({
  gateway:{}
})
const intersectList = ref([])

const gatewayForm = ref(null)
const dialogFlag = ref('add')
const isFlag = ref('')
const addGatewayDialog = ref(false)
const viewGatewayDialog = ref(false)
const rules = ref({
  "gateway.gatewayName": [
    { required: true, message: '请输入网关名称',trigger: 'blur'},
    { min: 5, message: '最低5位字符', trigger: 'blur' }
  ],
  "gateway.gatewayBrand": [
    { required: true, message: '请填写品牌',trigger: 'blur'},
  ],
    "gateway.gatewayModel": [
    { required: true, message: '请填写型号',trigger: 'blur'},
  ],
    "gateway.ipAddress": [
    { required: true,  message:'请输入ip地址',trigger: 'blur'},
    { pattern:/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/,message: '请输入正确的ip地址',trigger: 'blur'}
  ],
  "gateway.intersectId":[
    {required: true, message: '请选择路口',trigger: 'blur'}
  ]
})

const getNowDay = ()=>{
  let timestamp = Date.now(); // 获取当前时间戳，单位是毫秒
  gatewayInfo.value.gateway.installTime = new Date(timestamp)
}

const getRandomCode = (prex)=>{
  let str1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  let arr1 = str1.split("");
  gatewayInfo.value.gateway.gatewayCode = prex
  for(let i = 0; i < 10;i++){
    let n = Math.round(Math.random()*(arr1.length -1));
    gatewayInfo.value.gateway.gatewayCode += arr1[n]
  }
}

const tableRowClassName = ({row, rowIndex})=>{
  if ((rowIndex+1) % 2  === 0) {
    return 'success-row';
  }
  return '';
}
const getTableData = async() => {
  const table = await getGatewayList({page: page.value, pageSize: pageSize.value,...searchInfo.value})
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}
const getIntersect = async ()=>{
  const table = await getPublicIntersect();
  if (table.code === 0) {
    intersectList.value = table.data.pubIntersect
  }
}
getIntersect()
getTableData()

const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

// 标签页的一些声明
const activeName = ref('camera')
const cameracount = ref(0)
const screenscount = ref(0)
const radarcount = ref(0)
const add = () => {
  gatewayInfo.value={gateway:{Intersect:{}},relationDev:{}}
  dialogFlag.value = 'add'
  addGatewayDialog.value = true
  getNowDay()
  getRandomCode("ZHWG-")
}

const closeAddGatewayDialog = () => {
  gatewayForm.value.resetFields()
  addGatewayDialog.value = false
  isFlag.value=''
}

// 弹窗相关
const onSubmit = () => {
  page.value = 1
  pageSize.value = 10
  getTableData()
}
const onReset = () => {
  searchInfo.value = {}
}

const view = (row)=>{
  activeName.value = 'camera'
  viewGatewayDialog.value = true
  gatewayInfo.value = JSON.parse(JSON.stringify(row))
  gatewayInfo.value.gateway.installTime = new Date(gatewayInfo.value.gateway.installTime).toLocaleDateString()
  gatewayInfo.value.gateway.recentOnline = format(parseISO(gatewayInfo.value.gateway.recentOnline),'yyyy-MM-dd HH:mm:ss')
  cameracount.value=gatewayInfo.value.relationDev.cameraList.length
  screenscount.value=gatewayInfo.value.relationDev.screensList.length
  radarcount.value=gatewayInfo.value.relationDev.radarList.length
}

const enterAddGatewayDialog = async() => {
  gatewayForm.value.validate(async valid => {
    if (valid) {
      const req = {
        ...gatewayInfo.value.gateway
      }
      if (dialogFlag.value === 'add') {
        const res = await addGateway(req)
        if (res.code === 0) {
          ElMessage({ type: 'success', message: '创建成功' })
          await getTableData()
          closeAddGatewayDialog()
        }
      }
      if (dialogFlag.value === 'edit') {
        const res = await setGatewayInfo(req)
        if (res.code === 0) {
          ElMessage({ type: 'success', message: '编辑成功' })
          await getTableData()
          closeAddGatewayDialog()
        }
      }
    }
  })
}

const editGateway = (row) => {
  dialogFlag.value = 'edit'
  gatewayInfo.value = JSON.parse(JSON.stringify(row))
  addGatewayDialog.value = true
}
const deleteGateway = (obj) => {
  for (let prop in obj.relationDev) {
    if (Array.isArray(obj.relationDev[prop])) {
      if (obj.relationDev[prop].length !== 0) {
        ElMessage({
          type: 'warning',
          message: '请先移除关联的设备',
        })
        return
        break;
      }
    }
  }
  ElMessageBox.confirm('您确定要删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(async() => {
        const res = await deleteBaseGateway({ ID:obj.gateway.id })
        if (res.code === 0) {
          ElMessage({
            type: 'success',
            message: '删除成功!',
          })
          getTableData()
        }
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消删除',
        })
      })
}

</script>
<style>
.el-table .success-row {
  background: #f3fdef;
}

.onlinebox{
  width: 12px; height: 12px;border-radius: 50%; display: inline-block; margin-right: 4px; position: relative; top: 1px;
}

.el-dialog__header{
  border-bottom: 1px solid #e8eaec;
}
.el-dialog__footer {
  border-top: 1px solid #e8eaec;
}
</style>
