<template>
  <div id="custom-container" ref="customContainer" class="custom-modal-container" >
    <PageWrapper dense contentFullHeight fixedHeight contentClass="flex"  >

      <!-- 搜索、表格、分页 -->
      <BasicTable @register="registerTable" :searchInfo="searchInfo">
        <template #toolbar>
          <PermissionBtn @btn-event="onBtnClicked" />
        </template>
        <template #bodyCell="{ column, record }">

          <template v-if="column.key === 'model'">
            {{ cameraTypes[record.model] }}
          </template>

          <template v-if="column.key === 'action'">
            <TableAction
              :actions="[
                {
                  // icon: 'ant-design:ellipsis-outlined',
                  label: '详情',
                  onClick: viewDetail.bind(null, record),
                },
              ]"
            />
          </template>
        </template>
      </BasicTable>
  
      <!-- 添加 & 编辑-->
      <a-modal
        v-model:visible="addModelVisible"
        title="摄像头信息"
        width="70%"
        @ok="handleOk"
        :get-container="getContainer"
        wrap-class-name="modal"
        :mask="true"  
        :keyboard="false"
      >
        <AddModal  ref="AddModalRef" />
      </a-modal>
  
      <!-- 详情 -->
      <a-modal
        v-model:visible="detailModelVisible"
        :get-container="getContainer"
        title="摄像头信息"
        wrap-class-name="modal"
        width="70%"
        :footer="null"
        :mask="true"  
        :keyboard="false"
      >
        <Detail  :detailInfo="detailInfo" @close="closeDetail" />
      </a-modal>
    </PageWrapper>
  </div>
  
</template>
<script lang="ts" setup>
  import { reactive, ref, onMounted } from 'vue';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { getOrgList,GetCameraInfoPageList, deleteDept } from '@/api/demo/system';
  import { PageWrapper } from '@/components/Page';
  import { useMessage } from '@/hooks/web/useMessage';

  import { AddModal, Detail } from './page';
  import { PermissionBtn } from '@/components/PermissionBtn/index';
  import { columns, searchFormSchema } from './data';
  import axios from 'axios';
  import { getAppEnvConfig } from '@/utils/env';
  let { VITE_GLOB_API_URL } = getAppEnvConfig();


  defineOptions({ name: 'DeptManagement' });
  const { createConfirm, createMessage } = useMessage();
  const AddModalRef = ref();
  const searchInfo = reactive<Recordable>({});
  const addModelVisible = ref(false);
  const detailModelVisible = ref(false);
  const modalContainer = ref(null)

  const customContainer = ref(null)

  const getContainer = () => {
      console.log('getContainer called')
      
      // 方法1：使用ref（推荐）
      // if (customContainer.value) {
      //   console.log('使用ref获取容器:', customContainer.value)
      //   return customContainer.value
      // }
      
      // 方法2：使用ID选择器
      const container = document.getElementById('custom-container')
      if (container) {
        console.log('使用ID获取容器:', container)
        return container
      }
      
      // 方法3：使用querySelector
      const queryContainer = document.querySelector('.custom-modal-container')
      if (queryContainer) {
        console.log('使用class获取容器:', queryContainer)
        return queryContainer
      }
      
      console.warn('未找到自定义容器，使用body作为fallback')
      return document.body
    }



  const [registerTable, { reload, getSelectRows, clearSelectedRowKeys }] = useTable({
    // 表格名称
    title: '摄像头列表',
    // 获取数据的接口
    api: GetCameraInfoPageList,
    // 表单列信息 BasicColumn[]
    columns,
    rowKey: 'id',
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
    },
    // 使用搜索表单
    useSearchForm: true,
    // 显示表格设置工具
    showTableSetting: true,
    // 是否显示表格边框
    bordered: true,
    // 序号列
    showIndexColumn: false,
    // 勾选列
    rowSelection: {
      //多选框
      // type: 'checkbox',
      type: 'radio',
    },
    // 搜索
    handleSearchInfoFn(info) {
      return info;
    },
    actionColumn: {
      width: 80,
      title: '操作',
      dataIndex: 'action',
      // slots: { customRender: 'action' },
      fixed: undefined,
    },
  });
  const childRef = ref<any>();

  function handleCreate() {
    addModelVisible.value = true;
  }

  function handleEdit() {
    let rows = getSelectRows();
    if (rows.length == 0) {
      return createMessage.warn('请选择一个站点进行编辑');
    }
    const record = rows[0];
    addModelVisible.value = true;
  }
  function onBtnClicked(domId) {
    switch (domId) {
      case 'btnAdd':
        handleCreate();
        break;
      case 'btnEdit':
        handleEdit();
        break;
      case 'btnDelete':
        handleDelete();
        break;
      case 'btnExport':
        break;
      default:
        break;
    }
  }
  function handleSuccess() {
    clearSelectedRowKeys();
    childRef.value.fetch();
    reload();
  }
  const handleOk = () => {
    AddModalRef.value.validateForm();
    const params = AddModalRef.value.createSite();
    addApi(params);
    
  };

  async function handleDelete() {
    let rows = getSelectRows();
    if (rows.length == 0) {
      return createMessage.warn('请勾选一条数据进行删除');
    }
    const query = [rows[0].id];
    
    createConfirm({
      iconType: 'info',
      title: '删除',
      content: '确定要删除当前数据吗',
      onOk: async () => {
        // const data = await DeleteInterphoneInfo(query);
        
        axios.delete(`${VITE_GLOB_API_URL}/api/Camera/Delete/${rows[0].id}`).then(res => {
          if (res) {
            handleSuccess();
            createMessage.success('删除成功');
          } else {
            createMessage.error('删除失败');
          }
        })

        
      },
    });
  }

  const addApi = (params) => {
    let url = "/api/Camera/Add";
    axios({
      method: "post",
      url: VITE_GLOB_API_URL + url,
      data: params,
      headers: {
        'X-Token': localStorage.getItem("X-Token")
      }
    }).then(res=>{
      if(res){
        addModelVisible.value = false;
      }
    })
  }

  const detailInfo = ref(null);

  const viewDetail = (record: any) => {
    detailInfo.value = record;
    detailModelVisible.value = true;
  };
  
  const closeDetail = () => {
    detailModelVisible.value = false;
  };


  const cameraTypes = ref({});
  const getCameraType  = () => {
    let url = "/api/SysDataItemDetail/Load";
    let querys = {
      code:"FMCamera"
    }

    axios({
      method: "get",
      url: VITE_GLOB_API_URL + url,
      params: querys,
      headers: {
        'X-Token': localStorage.getItem("X-Token")
      }
    }).then(res=>{
        // cameraTypes.value = 
        res.data.result?.forEach((item,index)=>{
          cameraTypes.value[item.itemValue] = item.itemName
        })
    })

  }

  getCameraType();



</script>

<style lang="less">
  .full-modal {
    .ant-modal {
      max-width: 80%;
    }

    .ant-modal-content {
      height: calc(80vh);
    }

    .ant-modal-body {
      height: 100%;
    }
  }
</style>
