<template>
  <div class="system-ys7Devices-container">
    <el-card shadow="hover">
      <div class="system-ys7Devices-search mb8">
        <el-form :model="tableData.param" ref="queryRef" :inline="true" label-width="100px">
          <el-row>
            <el-col :span="8" class="colBlock">
              <el-form-item label="设备名称" prop="deviceName">
                <el-input v-model="tableData.param.deviceName" placeholder="请输入设备名称" clearable @keyup.enter.native="ys7DevicesList" />
              </el-form-item>
            </el-col>
            <el-col :span="8" class="colBlock">
              <el-form-item label="设备类型" prop="deviceType">
                <el-input v-model="tableData.param.deviceType" placeholder="请输入设备类型" clearable @keyup.enter.native="ys7DevicesList" />
              </el-form-item>
            </el-col>
            <el-col :span="8" :class="!showAll ? 'colBlock' : 'colNone'">
              <el-form-item>
                <el-button type="primary" @click="ys7DevicesList"
                  ><el-icon><Search /></el-icon>搜索</el-button
                >
                <el-button @click="resetQuery(queryRef)"
                  ><el-icon><Refresh /></el-icon>重置</el-button
                >
                <el-button type="primary" link @click="toggleSearch">
                  {{ word }}
                  <el-icon v-show="showAll"><ArrowUp /></el-icon>
                  <el-icon v-show="!showAll"><ArrowDown /></el-icon>
                </el-button>
              </el-form-item>
            </el-col>
            <el-col :span="8" :class="showAll ? 'colBlock' : 'colNone'">
              <el-form-item label="设备序列号" prop="deviceSerial">
                <el-input v-model="tableData.param.deviceSerial" placeholder="请输入设备串号" clearable @keyup.enter.native="ys7DevicesList" />
              </el-form-item>
            </el-col>
            <el-col :span="8" :class="showAll ? 'colBlock' : 'colNone'">
              <el-form-item label="状态" prop="status">
                <el-select v-model="tableData.param.status" placeholder="请选择设备状态" clearable>
                  <el-option label="在线" :value="1" />
                  <el-option label="离线" :value="0" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8" :class="showAll ? 'colBlock' : 'colNone'">
              <el-form-item label="设备版本" prop="deviceVersion">
                <el-input v-model="tableData.param.deviceVersion" placeholder="请输入设备版本" clearable @keyup.enter.native="ys7DevicesList" />
              </el-form-item>
            </el-col>
            <el-col :span="8" :class="showAll ? 'colBlock' : 'colNone'">
              <el-form-item label="所属项目" prop="projectId">
                <el-select v-model="tableData.param.projectId" placeholder="请选择所属项目" clearable filterable>
                  <el-option v-for="item in projectList" class="device_row" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8" :class="showAll ? 'colBlock' : 'colNone'">
              <el-form-item>
                <el-button type="primary" @click="ys7DevicesList"
                  ><el-icon><Search /></el-icon>搜索</el-button
                >
                <el-button @click="resetQuery(queryRef)"
                  ><el-icon><Refresh /></el-icon>重置</el-button
                >
                <el-button type="primary" link @click="toggleSearch">
                  {{ word }}
                  <el-icon v-show="showAll"><ArrowUp /></el-icon>
                  <el-icon v-show="!showAll"><ArrowDown /></el-icon>
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <!-- <el-col :span="1.5">
						<el-button type="primary" @click="handleAdd" v-auth="'api/v1/system/ys7Devices/add'"
							><el-icon><Plus /></el-icon>新增</el-button
						>
					</el-col> -->
          <el-col :span="1.5">
            <el-button type="success" :disabled="single" @click="handleUpdate(null)" v-auth="'api/v1/system/ys7Devices/edit'"
              ><el-icon><Edit /></el-icon>修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" :disabled="multiple" @click="handleDelete(null)" v-auth="'api/v1/system/ys7Devices/delete'"
              ><el-icon><Delete /></el-icon>删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" :disabled="multiple" @click="onLinkProject(null)" v-auth="'api/v1/system/ys7Devices/add'"
              ><el-icon><Link /></el-icon>设备分配</el-button
            >
          </el-col>
        </el-row>
      </div>
      <el-table v-loading="loading" :data="tableData.data" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="设备序列号" align="center" prop="deviceSerial" min-width="100px" />
        <el-table-column label="设备名称" align="center" prop="deviceName" min-width="100px" />
        <el-table-column label="设备类型" align="center" prop="deviceType" min-width="100px" />
        <el-table-column label="状态" align="center" prop="status" min-width="100px">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.status === 1">在线</el-tag>
            <el-tag type="danger" v-if="scope.row.status === 0">离线</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="视频加密" align="center" prop="videoEncrypted" min-width="100px">
          <template #default="scope">
            <el-switch
              v-model="scope.row.videoEncrypted"
              class="ml-2"
              :active-value="1"
              :inactive-value="0"
              :loading="scope.row.enctyptLoading"
              @change="encryptChange(scope.row)"
              inline-prompt
              active-text="开启"
              inactive-text="关闭"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
            />
          </template>
        </el-table-column>
        <!-- <el-table-column label="" align="center" prop="defence" min-width="100px" /> -->
        <el-table-column label="设备版本" align="center" prop="deviceVersion" min-width="100px" />
        <el-table-column label="所属项目" align="center" prop="projectId" min-width="100px">
          <template #default="scope">
            {{ scope.row.projectName ? scope.row.projectName : '未分配' }}
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" min-width="100px" />
        <el-table-column label="创建时间" align="center" prop="deviceCreateTime" min-width="100px">
          <template #default="scope">
            <span>{{ proxy.parseTime(scope.row.deviceCreateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding" min-width="160px" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleUpdate(scope.row)" v-auth="'api/v1/system/ys7Devices/edit'"
              ><el-icon><EditPen /></el-icon>修改</el-button
            >
            <el-button type="primary" link @click="handleDelete(scope.row)" v-auth="'api/v1/system/ys7Devices/delete'"
              ><el-icon><DeleteFilled /></el-icon>删除</el-button
            >
            <el-button type="primary" link @click="onLinkProject(scope.row)" v-auth="'api/v1/system/ys7Devices/delete'"
              ><el-icon><Link /></el-icon>设备分配</el-button
            >
            <el-button type="primary" link @click="addPreset(scope.row)"
              ><el-icon><Plus /></el-icon>添加预置位</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="tableData.total > 0"
        :total="tableData.total"
        v-model:page="tableData.param.pageNum"
        v-model:limit="tableData.param.pageSize"
        @pagination="ys7DevicesList"
      />
    </el-card>
    <!-- <apiV1SystemYs7DevicesAdd ref="addRef" @ys7DevicesList="ys7DevicesList"></apiV1SystemYs7DevicesAdd>
    <apiV1SystemYs7DevicesEdit ref="editRef" @ys7DevicesList="ys7DevicesList"></apiV1SystemYs7DevicesEdit>
    <apiV1SystemYs7DevicesDetail ref="detailRef" @ys7DevicesList="ys7DevicesList"></apiV1SystemYs7DevicesDetail> -->
    <bindPro ref="bindProRef" :projectList="projectList" @ys7DevicesList="ys7DevicesList"></bindPro>
    <!-- <presetAdd ref="presetAddRef" @busPresettingBitList="busPresettingBitList"></presetAdd> -->
  </div>
</template>
<script setup lang="ts">
// import { ref, reactive, onMounted, computed, toRefs, getCurrentInstance, toRaw } from 'vue';
import { ElMessageBox, ElMessage, FormInstance } from 'element-plus';
import { listYs7Device, delYs7Device, toggleEncrypt } from '@/api/other/ys7Device';
// import { Ys7DeviceVO, Ys7DevicesInfoData, Ys7DevicesTableDataState } from './component/model';
import { Ys7DeviceVO, Ys7DeviceForm, Ys7DeviceQuery } from '@/api/other/ys7Device/types';
import { useUserStoreHook } from '@/store/modules/user';
// import apiV1SystemYs7DevicesAdd from './component/add.vue';
// import apiV1SystemYs7DevicesEdit from './component/edit.vue';
// import apiV1SystemYs7DevicesDetail from './component/detail.vue';
import bindPro from './component/bindPro.vue';
import presetAdd from './component/presetAdd.vue';

// proxy 获取
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
// ref 定义
const loading = ref(false);
const queryRef = ref<FormInstance>();
const addRef = ref();
const editRef = ref();
const detailRef = ref();
const bindProRef = ref();
const presetAddRef = ref();

// 展开/收起搜索项
const showAll = ref(false);
const word = computed(() => (showAll.value ? '收起搜索' : '展开搜索'));

// 多选控制
const single = ref(true);
const multiple = ref(true);

// 获取用户 store
const userStore = useUserStoreHook();
// 从 store 中获取项目列表和当前选中的项目
const currentProject = computed(() => userStore.selectedProject);
const projects = computed(() => userStore.projects);

// 状态管理
const state = reactive<any>({
  ids: [],
  serials: [],
  tableData: {
    data: [],
    total: 0,
    loading: false,
    param: {
      pageNum: 1,
      pageSize: 10,
      id: undefined,
      createdAt: undefined,
      deviceSerial: undefined,
      deviceName: undefined,
      deviceType: undefined,
      status: undefined,
      defence: undefined,
      deviceVersion: undefined,
      projectId: currentProject.value?.id,
      dateRange: [],
      isFront: false
    }
  },
  projectList: projects.value
});

// 初始化
const initTableData = () => {
  ys7DevicesList();
  // sysProjectList();
};

// 搜索重置
const resetQuery = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  ys7DevicesList();
};

// 获取设备列表
const ys7DevicesList = () => {
  loading.value = true;
  listYs7Device(state.tableData.param).then((res: any) => {
    let list = res.rows ?? [];
    state.tableData.data = list.map((item) => {
      item.enctyptLoading = false;
      return item;
    });
    state.tableData.total = res.total;
    loading.value = false;
  });
};

// 展开/收起搜索项
const toggleSearch = () => {
  showAll.value = !showAll.value;
};

// 多选事件
const handleSelectionChange = (selection: any[]) => {
  state.ids = selection.map((item) => item.id);
  state.serials = selection.map((item) => item.deviceSerial);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

// 新增
const handleAdd = () => {
  addRef.value.openDialog();
};

// 编辑
const handleUpdate = (row?: Ys7DeviceVO) => {
  if (!row) {
    row = state.tableData.data.find((item) => item.id === state.ids[0])!;
  }
  editRef.value.openDialog(toRaw(row));
};

// 删除
const handleDelete = (row?: Ys7DeviceVO) => {
  let msg = row ? `此操作将永久删除数据，是否继续?` : '你确定要删除所选数据？';
  let id = row ? [row.id] : state.ids;

  if (id.length === 0) {
    ElMessage.error('请选择要删除的数据。');
    return;
  }

  ElMessageBox.confirm(msg, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      delYs7Device(id).then(() => {
        ElMessage.success('删除成功');
        ys7DevicesList();
      });
    })
    .catch(() => {});
};

// 查看详情
const handleView = (row: Ys7DeviceVO) => {
  detailRef.value.openDialog(toRaw(row));
};

// 绑定项目
const onLinkProject = (row?: Ys7DeviceVO) => {
  let serials = row ? [row.deviceSerial] : state.serials;
  if (serials.length === 0) {
    ElMessage.error('请选择要绑定项目的设备');
    return;
  }
  let info = { serials, row };
  bindProRef.value.openDialog(toRaw(info));
};

// 添加预置位
const addPreset = (row: any) => {
  presetAddRef.value.openDialog(row);
};

// 开关加密
const encryptChange = (row: Ys7DeviceVO | any) => {
  row.enctyptLoading = true;
  // const action = row.videoEncrypted === 0 ? 1 : 0;
  console.log(row.videoEncrypted);

  toggleEncrypt({ videoEncrypted: row.videoEncrypted, id: row.id })
    .then(() => {
      proxy?.$modal.msgSuccess(row.videoEncrypted === 0 ? '关闭成功' : '开启成功');
    })
    .finally(() => {
      row.enctyptLoading = false;
      ys7DevicesList();
    });
};

//监听项目id刷新数据
const listeningProject = watch(
  () => currentProject.value.id,
  (nid, oid) => {
    tableData.value.param.projectId = nid;
    initTableData();
  }
);

// 页面加载
onMounted(() => {
  initTableData();
});

onUnmounted(() => {
  listeningProject();
});

// 暴露变量
const { tableData, projectList } = toRefs(state);
</script>
<style lang="scss" scoped>
.colBlock {
  display: block;
}
.colNone {
  display: none;
}
</style>
