<template>
  <div class="page">
    <div class="ele-body">
      <a-card :bordered="false">
        <!-- 表格 -->
        <ele-pro-table
          ref="tableRef"
          row-key="equipmentId"
          :columns="columns"
          :datasource="datasource"
          v-model:selection="selection"
          :customRow="customRow"
          tool-class="ele-toolbar-form"
          :scroll="{ x: 1200 }"
          class="sys-org-table"
          :striped="true"
        >
          <template #toolbar>
            <search
              @search="reload"
              :selection="selection"
              @add="openEdit"
              @remove="removeBatch"
              @update="handleStatus"
            />
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'nickname'">
              {{ record.nickname }}
            </template>
            <template v-if="column.key === 'createTime'">
              {{ record.createTime }}
            </template>
            <template v-if="column.key === 'status'">
              <a-tag v-if="record.status === 0" color="green">闲置</a-tag>
              <a-tag v-if="record.status === 1" color="red">报废</a-tag>
              <a-tag v-if="record.status === 2" color="purple">注销</a-tag>
              <a-tag v-if="record.status === 3" color="orange">转卖</a-tag>
            </template>
            <template v-if="column.key === 'action'">
              <a-space>
                <a>一机一档</a>
              </a-space>
            </template>
          </template>
        </ele-pro-table>
      </a-card>
    </div>
    <!-- 编辑弹窗 -->
    <EquipmentEdit v-model:visible="showEdit" :data="current" @done="reload" />
  </div>
</template>

<script lang="ts" setup>
  import { createVNode, ref } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import type { EleProTable } from 'ele-admin-pro';
  import type {
    DatasourceFunction,
    ColumnItem
  } from 'ele-admin-pro/es/ele-pro-table/types';
  import { toDateString } from 'ele-admin-pro';
  import Search from './components/search.vue';
  import EquipmentEdit from './components/equipment-edit.vue';
  import {
    pageTowerEquipment,
    removeBatchTowerEquipment,
    statusBatchTowerEquipment, updateBatchTowerEquipment,
    updateTowerEquipment
  } from "@/api/tower/equipment";
  import {
    TowerEquipment,
    TowerEquipmentParam
  } from '@/api/tower/equipment/model';

  defineProps<{
    activeKey?: boolean;
    data?: any;
  }>();

  // 表格实例
  const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);

  // 表格列配置
  const columns = ref<ColumnItem[]>([
    {
      key: 'index',
      width: 48,
      align: 'center',
      fixed: 'left',
      hideInSetting: true,
      customRender: ({ index }) => index + (tableRef.value?.tableIndex ?? 0)
    },
    {
      title: '设备状态',
      dataIndex: 'status',
      key: 'status',
      customRender: ({ text }) => ['闲置', '报废', '注销', '转卖'][text]
    },
    {
      title: '设备名称',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '设备型号',
      dataIndex: 'model',
      key: 'model'
    },
    {
      title: '制造厂商',
      dataIndex: 'manufactor',
      key: 'manufactor'
    },
    {
      title: '当前位置',
      dataIndex: 'currentLocation',
      key: 'currentLocation'
    },
    {
      title: '产权单位(个人)',
      dataIndex: 'company',
      key: 'company'
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center',
      sorter: true,
      customRender: ({ text }) => toDateString(text)
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      align: 'center',
      hideInSetting: true
    }
  ]);

  // 表格选中数据
  const selection = ref<TowerEquipment[]>([]);
  // 当前编辑数据
  const current = ref<TowerEquipment | null>(null);
  // 是否显示编辑弹窗
  const showEdit = ref(false);

  // 表格数据源
  const datasource: DatasourceFunction = ({
    page,
    limit,
    where,
    orders,
    filters
  }) => {
    // 搜索条件
    if (filters.payMethod) {
      where.payMethod = filters.payMethod;
    }
    if (filters.deliveryType) {
      where.deliveryType = filters.deliveryType;
    }
    if (filters.payStatus) {
      where.payStatus = filters.payStatus;
    }
    if (filters.orderSource) {
      where.orderSource = filters.orderSource;
    }
    where.tenantId = localStorage.getItem('tenantId');
    where.payStatus = 20;
    return pageTowerEquipment({
      ...where,
      ...orders,
      page,
      limit
    });
  };

  /* 搜索 */
  const reload = (where?: TowerEquipmentParam) => {
    selection.value = [];
    tableRef?.value?.reload({ where: where });
  };

  /* 打开编辑弹窗 */
  const openEdit = (row?: TowerEquipment) => {
    current.value = row ?? null;
    showEdit.value = true;
  };

  /* 批量修改 */
  const handleStatus = (status) => {
    if (!selection.value.length) {
      message.error('请至少选择一条数据');
      return;
    }
    const data = selection.value.map((d) => {
      return {
        equipmentId: d.equipmentId,
        status
      };
    });
    console.log(data);
    updateBatchTowerEquipment(data).then((msg) => {
      message.success(msg);
      reload();
    });
  };

  /* 批量删除 */
  const removeBatch = () => {
    if (!selection.value.length) {
      message.error('请至少选择一条数据');
      return;
    }
    Modal.confirm({
      title: '提示',
      content: '确定要删除选中的记录吗?',
      icon: createVNode(ExclamationCircleOutlined),
      maskClosable: true,
      onOk: () => {
        const hide = message.loading('请求中..', 0);
        removeBatchTowerEquipment(selection.value.map((d) => d.equipmentId))
          .then((msg) => {
            hide();
            message.success(msg);
            reload();
          })
          .catch((e) => {
            hide();
            message.error(e.message);
          });
      }
    });
  };

  /* 自定义行属性 */
  const customRow = (record: TowerEquipment) => {
    return {
      // 行点击事件
      onClick: () => {
        // console.log(record);
      },
      // 行双击事件
      onDblclick: () => {
        openEdit(record);
      }
    };
  };

  reload();
</script>

<script lang="ts">
  export default {
    name: 'TowerEquipmentIndex'
  };
</script>

<style lang="less" scoped>
  p {
    line-height: 0.8;
  }
  .sys-org-table :deep(.ant-table-body) {
    overflow: auto !important;
    overflow: overlay !important;
  }

  .sys-org-table :deep(.ant-table-pagination.ant-pagination) {
    padding: 0 4px;
    margin-bottom: 0;
  }
  .price-edit {
    padding-right: 5px;
  }
  .comments {
    max-width: 200px;
  }
</style>
