import { computed, ref } from 'vue';
import { defineStore } from 'pinia';
import { CameraSharedItem } from '../constant';
import { ElMessage } from 'element-plus';

export const useCameraShare = defineStore('camera-share', () => {
  const cameraCompleted = ref<CameraSharedItem[]>([
    {
      cameraIp: '172.13.25.0000',
      cameraType: 'haikang',
      cameraPort: '11',
      companyAccount: 111,
      companyName: '1111',
      code: 'C919-140',
      workshopName: 'C919车间',
      workspaceName: '东侧',
      shareState: 'complete',
      password: '11',
      username: '22',
    },
  ]);

  const cameraIncompleted = ref<CameraSharedItem[]>([
    {
      cameraIp: '172.13.25.0011',
      cameraType: 'haikang',
      cameraPort: '11',
      companyAccount: 111,
      companyName: '1111',
      code: 'C919-141',
      workshopName: 'C919车间',
      workspaceName: '西侧',
      shareState: 'incomplete',
      password: '11',
      username: '22',
    },
    {
      cameraIp: '172.13.25.0009',
      cameraType: 'haikang',
      cameraPort: '11',
      companyAccount: 111,
      companyName: '1111',
      code: 'C919-142',
      workshopName: 'C919车间',
      workspaceName: '北侧',
      shareState: 'incomplete',
      password: '11',
      username: '22',
    },
  ]);

  const queryName = ref<string>();
  const queryAccount = ref<string>();

  const unAddlength = computed(() => {
    return cameraIncompleted.value.length;
  });

  const handleAdd = (row, addCameraType) => {
    if (addCameraType === 'complete') return;
    const currentData = cameraIncompleted.value.find((item) => (item.cameraIp = row.cameraIp));
    const indexToRemove = cameraIncompleted.value.findIndex(
      (item) => item.cameraIp === row.cameraIp,
    );
    if (indexToRemove !== -1) {
      cameraIncompleted.value.splice(indexToRemove, 1);
    }
    if (currentData) {
      cameraCompleted.value.push(currentData!);
    }
    ElMessage({
      message: '添加成功',
      type: 'success',
    });
  };

  const handleDelete = (row, addCameraType) => {
    if (addCameraType === 'complete') {
      const indexToRemove = cameraCompleted.value.findIndex(
        (item) => item.cameraIp === row.cameraIp,
      );
      cameraCompleted.value.splice(indexToRemove, 1);
    } else {
      const indexToRemove = cameraIncompleted.value.findIndex(
        (item) => item.cameraIp === row.cameraIp,
      );
      cameraIncompleted.value.splice(indexToRemove, 1);
    }
  };

  const resetSearch = () => {
    queryName.value = '';
    queryAccount.value = '';
  };

  return {
    queryName,
    queryAccount,
    cameraCompleted,
    cameraIncompleted,
    unAddlength,
    handleAdd,
    handleDelete,
    resetSearch,
  };
});

export default useCameraShare;
