<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 label="所属分路">
          <el-select v-model="searchInfo.shunt" placeholder="所属分路">
            <el-option label="主路" value=1></el-option>
            <el-option label="支路" value=2></el-option>
          </el-select>
        </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="ID" label="#" :width="80"/>
        <el-table-column prop="shunt" label="所属分路" :width="100">
          <template #default="scope">
            {{ scope.row.shunt===1?"主路":scope.row.shunt===2?"支路":"未知" }}
          </template>
        </el-table-column>
        <el-table-column prop="cameraName" label="名称" />
        <el-table-column prop="cameraCode" label="编码">
          <template #default="scope">
            <el-tag effect="light">{{ scope.row.cameraCode }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="cameraBrand" label="品牌" />
        <el-table-column prop="cameraModel" label="型号"/>
        <el-table-column prop="cameraType" label="类型">
          <template #default="scope">
            {{ scope.row.cameraType === 0?'球机':'枪机' }}
          </template>
        </el-table-column>
        <el-table-column prop="GateWay.gatewayName" label="所属网关"/>
        <el-table-column prop="status" label="在线状态">
          <template #default="scope">
            <div class="onlinebox" :style="{'background': scope.row.status===1 ? 'red':'green' }"></div>
            <span :style="{ color: scope.row.status === 1 ? 'red' : 'green' }">{{ scope.row.status === 1 ? '离线' : '在线' }}</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="editCamera(scope.row)"
            >编辑</el-button>
            <el-button
                type="primary"
                link
                icon="delete"
                @click="deleteCamera(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="addCameraDialog" title="摄像头" width="900">
        <el-form
            ref="cameraForm"
            :rules="rules"
            :model="cameraInfo"
            label-width="110px"
            style="padding: 15px"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="摄像头名称：" :inline="false" prop="cameraName">
                <el-input v-model="cameraInfo.cameraName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="编码：" :inline="false">
                <el-input disabled v-model="cameraInfo.cameraCode"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="品牌：" :inline="false" prop="cameraBrand">
                <el-input v-model="cameraInfo.cameraBrand"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="型号：" :inline="false" prop="cameraModel">
                <el-input v-model="cameraInfo.cameraModel"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="ip地址：" :inline="false" prop="ipAddress">
                <el-input v-model="cameraInfo.ipAddress"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属网关：" :inline="false" prop="gatewayId">
                <el-select v-model="cameraInfo.gatewayId" placeholder="所属网关">
                  <el-option v-for=" (item) in gatewayList" :label="item.gatewayName" :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-select v-model="cameraInfo.shunt" placeholder="请选择所属分路">
                  <el-option label="主路" :value=1></el-option>
                  <el-option label="支路" :value=2></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="分路描述：" :inline="false">
                <el-input v-model="cameraInfo.shuntDescribe"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="摄像头类型：" :inline="false">
                <el-select v-model="cameraInfo.cameraType" placeholder="摄像头类型">
                  <el-option label="球机" :value=0></el-option>
                  <el-option label="枪机" :value=1></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="安装时间：" :inline="false">
                <el-date-picker
                    v-model="cameraInfo.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="closeAddCameraDialog">取消</el-button>
            <el-button type="primary" @click="enterAddCameraDialog">
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>

      <el-dialog v-model="viewCameraDialog" title="详情" style="padding: 35px">
        <el-form
            :model="cameraInfo"
            label-width="100px"
            style="padding: 20px"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="摄像头名称：" :inline="false">
                {{cameraInfo.cameraName }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="编码：" :inline="false">
                {{cameraInfo.cameraCode }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="品牌：" :inline="false">
                {{cameraInfo.cameraBrand }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="型号：" :inline="false">
                {{cameraInfo.cameraModel }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="ip地址：" :inline="false">
                {{cameraInfo.ipAddress }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属网关：" :inline="false">
                {{cameraInfo.GateWay.gatewayName }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="所属分路：" :inline="false">
                <el-tag  effect="dark">{{cameraInfo.shunt===1?"主路":cameraInfo.shunt===2?"支路":"未知"}}</el-tag>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="分路描述：" :inline="false">
                {{cameraInfo.shuntDescribe }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="摄像头类型：" :inline="false">
                <el-tag effect="dark" type="success">{{ cameraInfo.cameraType === 0?'球机':'枪机' }}</el-tag>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="在线状态：" :inline="false">
                <div class="onlinebox" :style="{'background': cameraInfo.status===1 ? 'red':'green' }"></div>
                <span :style="{ color: cameraInfo.status === 1 ? 'red' : 'green' }">{{ cameraInfo.status === 1 ? '离线' : '在线' }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="安装时间：" :inline="false">
                {{cameraInfo.installTime }}
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>
<script setup>
import {deleteBaseCamera, getCameraList,getPublicGateway,setCameraInfo,addCamera} from "@/api/camera";
import { ref} from 'vue'
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 cameraInfo = ref({})
const gatewayList = ref([])
const cameraForm = ref(null)
const dialogFlag = ref('add')
const isFlag = ref('')
const addCameraDialog = ref(false)
const viewCameraDialog = ref(false)

const rules = ref({
  cameraName: [
    { required: true, message: '请输入名称',trigger: 'blur'},
    { min: 5, message: '最低5位字符', trigger: 'blur' }
  ],
  cameraBrand: [
    { required: true, message: '请填写品牌',trigger: 'blur'},
  ],
  cameraModel: [
    { required: true, message: '请填写型号',trigger: 'blur'},
  ],
  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'}
  ],
  gatewayId: [
    { required: true,  message:'请选择网关',trigger: 'blur'},
  ]
})

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

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

const tableRowClassName = ({row, rowIndex})=>{
  if ((rowIndex+1) % 2  === 0) {
    return 'success-row';
  }
  return '';
}
const getTableData = async() => {
  const table = await getCameraList({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 getCameraParms = async() => {
  const table = await getPublicGateway()
  if (table.code === 0) {
    gatewayList.value = table.data.pubGateway
  }
}

getCameraParms()
getTableData()

const view = (row)=>{
  viewCameraDialog.value = true
  cameraInfo.value = JSON.parse(JSON.stringify(row))
  cameraInfo.value.installTime = new Date(cameraInfo.value.installTime).toLocaleDateString()
}



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

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

const add = () => {
  cameraInfo.value={GateWay:{},shunt:1,cameraType:0}
  dialogFlag.value = 'add'
  addCameraDialog.value = true
  getNowDay()
  getRandomCode("SXT-")
}

const closeAddCameraDialog = () => {
  cameraForm.value.resetFields()
  addCameraDialog.value = false
  isFlag.value=''
}

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

const enterAddCameraDialog = async() => {
  cameraForm.value.validate(async valid => {
    if (valid) {
      const req = {
        ...cameraInfo.value
      }
      if (dialogFlag.value === 'add') {
        const res = await addCamera(req)
        if (res.code === 0) {
          ElMessage({ type: 'success', message: '创建成功' })
          await getTableData()
          closeAddCameraDialog()
        }
      }
      if (dialogFlag.value === 'edit') {
        const res = await setCameraInfo(req)
        if (res.code === 0) {
          ElMessage({ type: 'success', message: '编辑成功' })
          await getTableData()
          closeAddCameraDialog()
        }
      }
    }
  })
}

const editCamera = (row) => {
  dialogFlag.value = 'edit'
  cameraInfo.value = JSON.parse(JSON.stringify(row))
  addCameraDialog.value = true
}
const deleteCamera = (obj) => {
  ElMessageBox.confirm('您确定要删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(async() => {
        const res = await deleteBaseCamera({ ID:obj.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>
