import { ref } from "vue";
import { delObjectProperty } from "@pureadmin/utils";

import Location from "@/model/location.js";

export function useLocationColumns() {
  const locationEditMap = ref({});
  const locationDataList = ref([]);
  const locationColumns: TableColumnList = [
    {
      label: "ID",
      prop: "id",
      width: 100,
      cellRenderer: ({ row, index }) => (
        <>
          {locationEditMap.value[index]?.editable ? (
            <el-input v-model={row.id} />
          ) : (
            <p>{row.id}</p>
          )}
        </>
      )
    },
    {
      label: "名称",
      prop: "name",
      width: 170,
      cellRenderer: ({ row, index }) => (
        <>
          {locationEditMap.value[index]?.editable ? (
            <el-input v-model={row.name} />
          ) : (
            <p>{row.name}</p>
          )}
        </>
      )
    },
    {
      label: "中心坐标",
      prop: "center",
      cellRenderer: ({ row, index }) => (
        <>
          {locationEditMap.value[index]?.editable ? (
            <div>
              <span>经度:</span>
              <el-input style="width: 150px;" v-model={row.center.x} >
              </el-input>
              <span>纬度:</span>
              <el-input style="width: 150px;" v-model={row.center.y} >
              </el-input>
            </div>
          ) : (
            <p>{'经度:[' + row.center.x + '],纬度:[' + row.center.y + ']'}</p>
          )}
        </>
      )
    },
    {
      label: "操作",
      fixed: "right",
      width: 140,
      slot: "operation"
    }
  ];

  function onEditLocation(row, index) {
    locationEditMap.value[index] = Object.assign({ ...row, editable: true });
  }

  function onSaveLocation(index) {
    locationEditMap.value[index].editable = false;
  }

  function onCancelLocation(index) {
    locationEditMap.value[index].editable = false;
    locationDataList.value[index] = delObjectProperty(locationEditMap.value[index], "editable");
  }

  function onAddLocation() {
    const v = new Location();
    v.id = locationDataList.value.length + 1;
    locationDataList.value.push(v);
  }

  function onDelLocation(row) {
    const index = locationDataList.value.indexOf(row);
    if (index !== -1) locationDataList.value.splice(index, 1);
  }

  return {
    locationEditMap,
    locationColumns,
    locationDataList,
    onAddLocation,
    onDelLocation,
    onEditLocation,
    onSaveLocation,
    onCancelLocation
  };
}
