<template>
  <a-spin :spinning="loading">
    <a-space style="margin-bottom: 10px">
      <TowerPlaceSelect :placeholder="`选择保养部位`" @done="choosePlace" />
      <span>设备名称</span>
      <div style="width: 200px">
        <TowerEquipmentType
          v-model:value="searchText"
          valueField="label"
          placeholder="请选择设备名称"
          class="ele-fluid"
          @change="onSearch"
        />
      </div>
    </a-space>
    <a-table
      size="middle"
      row-key="id"
      :pagination="false"
      :data-source="list"
      :columns="columns"
    >
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.key === 'action'">
          <a-space>
            <a class="ele-text-danger" @click="remove(record, index)">移除</a>
          </a-space>
        </template>
      </template>
    </a-table>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import type { ColumnsType } from 'ant-design-vue/es/table';
  import { ProjectOrder } from '@/api/tower/project/order/model';
  import { removeProjectPlace } from '@/api/tower/project/place';
  import { message } from 'ant-design-vue';

  const props = withDefaults(
    defineProps<{
      value?: ProjectOrder[];
      projectId?: number;
      placeholder?: string;
    }>(),
    {
      placeholder: '请选择数据'
    }
  );

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'search', text): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  // 已添加成员
  const list = ref<ProjectOrder[]>([]);
  // 请求状态
  const loading = ref(false);
  // 搜索内容
  const searchText = ref(undefined);

  // 列
  const columns = reactive<ColumnsType>([
    {
      key: 'index',
      title: '序号',
      align: 'center',
      width: 48,
      customRender: ({ index }) => index + 1,
      fixed: 'left'
    },
    {
      title: '部位编码',
      align: 'center',
      dataIndex: 'placeCode',
      key: 'placeCode'
    },
    {
      title: '设备名称',
      align: 'center',
      dataIndex: 'equipmentType',
      key: 'equipmentType'
    },
    {
      title: '保养部位',
      align: 'center',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      width: 100
    }
  ]);

  const choosePlace = (data) => {
    data.projectId = props.projectId;
    list.value.push(data);
  };

  const onSearch = () => {
    emit('search', searchText.value);
  };

  /* 删除 */
  const remove = (_row: any, index: number) => {
    removeProjectPlace(_row.id).then((msg) => {
      message.success(msg);
    });
    list.value.splice(index, 1);
  };

  watch(
    () => props.value,
    (value) => {
      if (value) {
        list.value = value;
      }
    },
    { immediate: true }
  );
</script>
