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

import Person from "@/model/person.js";

export function usePersonColumns() {
  const personEditMap = ref({});
  const personDataList = ref([]);
  const personColumns: TableColumnList = [
    {
      label: "ID",
      prop: "id",
      cellRenderer: ({ row, index }) => (
        <>
          {personEditMap.value[index]?.editable ? (
            <el-input v-model={row.id} />
          ) : (
            <p>{row.id}</p>
          )}
        </>
      )
    },
    {
      label: "名称",
      prop: "name",
      cellRenderer: ({ row, index }) => (
        <>
          {personEditMap.value[index]?.editable ? (
            <el-input v-model={row.name} />
          ) : (
            <p>{row.name}</p>
          )}
        </>
      )
    },
    {
      label: "职位",
      prop: "job",
      cellRenderer: ({ row, index }) => (
        <>
          {personEditMap.value[index]?.editable ? (
            <el-input v-model={row.job} />
          ) : (
            <p>{row.job}</p>
          )}
        </>
      )
    },
    {
      label: "电话",
      prop: "phone",
      cellRenderer: ({ row, index }) => (
        <>
          {personEditMap.value[index]?.editable ? (
            <el-input v-model={row.phone} />
          ) : (
            <p>{row.phone}</p>
          )}
        </>
      )
    },
    {
      label: "所属区域",
      prop: "locId",
      cellRenderer: ({ row, index }) => (
        <>
          {personEditMap.value[index]?.editable ? (
            <el-input v-model={row.locId} />
          ) : (
            <p>{row.locId}</p>
          )}
        </>
      )
    },
    {
      label: "标签ID",
      prop: "tagId",
      cellRenderer: ({ row, index }) => (
        <>
          {personEditMap.value[index]?.editable ? (
            <el-input v-model={row.tagId} />
          ) : (
            <p>{row.tagId}</p>
          )}
        </>
      )
    },

    {
      label: "操作",
      fixed: "right",
      width: 140,
      slot: "operation"
    }
  ];

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

  function onSavePerson(index) {
    personEditMap.value[index].editable = false;
  }

  function onCancelPerson(index) {
    personEditMap.value[index].editable = false;
    personDataList.value[index] = delObjectProperty(personEditMap.value[index], "editable");
  }

  function onAddPerson() {
    const v = new Person();
    v.id = personDataList.value.length + 1;
    personDataList.value.push(v);
  }

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

  return {
    personEditMap,
    personColumns,
    personDataList,
    onAddPerson,
    onDelPerson,
    onEditPerson,
    onSavePerson,
    onCancelPerson
  };
}
