import { ref } from 'vue';
import {
  CameraShareType,
  CameraShareQueryType,
  getShareCameraList,
  editShareCameraList,
  delShareCameraList,
  addShareCameraList,
} from '@/api/camera/camera-share';

export const useCameraShared = () => {
  const cameraShareList = ref<CameraShareType[]>([]);
  const queryName = ref<string>();
  const queryAccount = ref<string>('');
  const isAddState = ref<boolean | number>(-1);
  const queryCameraId = ref<number | undefined>(-1);
  const queryToTenantId = ref<number>(-1);
  const totalRow = ref(0);
  const page = ref(1);
  const size = ref(100);

  // 条件查询事件
  const conditionSearch = () => {
    const param = {
      pageNumber: page.value,
      pageSize: size.value === 0 ? 1 : size.value,
      cameraId: -1,
      isAdd: -1,
      toTenantId: -1,
    };
    //先获取总数作为
    getShareCameraList(param).then((res) => {
      size.value = res.totalRow === 0 ? 1 : res.totalRow;
      const params: CameraShareQueryType = {
        pageNumber: page.value,
        pageSize: size.value,
        isAdd: isAddState.value,
      };
      if (queryName.value) {
        params.tenantName = queryName.value;
      }

      if (queryAccount.value) {
        params.tenantCode = queryAccount.value;
      }
      if (queryCameraId.value) {
        params.cameraId = queryCameraId.value;
      }
      if (queryToTenantId.value) {
        params.toTenantId = queryToTenantId.value;
      }
      getShareCameraList(params).then((res) => {
        cameraShareList.value = res.records;
        totalRow.value = res.totalRow;
      });
    });
  };

  const handleAdd = (data: CameraShareType) => {
    addShareCameraList(data).then(() => {
      conditionSearch();
    });
  };

  const handleDel = (id: number) => {
    delShareCameraList(id).then(() => {
      conditionSearch();
    });
  };

  const handleEdit = (data: CameraShareType) => {
    editShareCameraList(data).then(() => {
      conditionSearch();
    });
  };

  return {
    cameraShareList,
    totalRow,
    queryName,
    queryAccount,
    isAddState,
    queryCameraId,
    queryToTenantId,
    conditionSearch,
    handleDel,
    handleAdd,
    handleEdit,
  };
};

export default useCameraShared;
