import { ref, watch } from 'vue';
import { defineStore } from 'pinia';
import { addPoint, addPolyLine, addTrajectory, playTrajectory } from '@/utils/map/mapOperation.js';
import { useMapStore } from './mapStore';
export const useDrawPointStore = defineStore('drawPointStore', () => {
  const mapStore = useMapStore();
  //当前患者绘制点位列表
  const currentDrawPointList = ref([]);

  //当前选中点id,code,name(名称)
  const currentSelectId = ref('');
  const currentSelectCode = ref('');
  const currentSelectName = ref('');
  //是否开始标会
  const drawStartStatus = ref(false);
  const openBiddingTable = ref(false);

  //是否在修改或新增轨迹点位
  const modifyTrail = ref(false);
  //信息框当前展示点位index
  const infoBoxIndex = ref(0);

  //修改当前展示点位index
  const setInfoBoxIndex = (index) => {
    infoBoxIndex.value = index;
  };

  //修改是否开始绘制状态
  const setDrawStartStatus = (value) => {
    drawStartStatus.value = value;
  };

  const pushCurrentDrawPointList = (point) => {
    currentDrawPointList.value.push(point);
  };

  const modifyCurrentDrawPointList = (key, value) => {
    if (currentDrawPointList.value[infoBoxIndex.value]) {
      currentDrawPointList.value[infoBoxIndex.value][key] = value;
    }
  };

  const renderPersonPoint = () => {
    const pointList = currentDrawPointList.value
      .filter((item) => {
        return item.x && item.y;
      })
      .sort((pre, next) => new Date(pre.date) - new Date(next.date));
    if (pointList?.length > 0) {
      addPoint(pointList, 'drawPoint');
      addTrajectory(pointList, 'drawLine');
      setTimeout(() => {
        playTrajectory('drawLine', 160, mapStore.mapTheme == 'light' ? 'green' : 'red');
      }, 1000);
    }
  };

  watch(
    () => currentDrawPointList.value,
    () => {
      renderPersonPoint();
    },
    {
      deep: true
    }
  );

  return {
    currentDrawPointList,
    infoBoxIndex,
    currentSelectId,
    currentSelectCode,
    currentSelectName,
    setInfoBoxIndex,
    drawStartStatus,
    openBiddingTable,
    modifyTrail,
    pushCurrentDrawPointList,
    setDrawStartStatus,
    modifyCurrentDrawPointList,
    renderPersonPoint
  };
});
