<template>
  <div>
    <a-card title="项目数据">
      <div class="count">
        <div class="btn">
          <a-divider type="vertical" class="divider" />
          <div
            @click="onTab(undefined)"
            :class="active == undefined ? 'active' : ''"
          >
            {{ `全部项目(${projectData.totalNum})` }}
          </div>
        </div>
        <div class="btn">
          <a-divider type="vertical" class="divider" />
          <div
            @click="onTab('建设中')"
            :class="active == '建设中' ? 'active' : ''"
          >
            {{ `建设中(${projectData.startedNum})` }}
          </div>
        </div>
        <div class="btn">
          <a-divider type="vertical" class="divider" />
          <div
            @click="onTab('未开工')"
            :class="active == '未开工' ? 'active' : ''"
          >
            {{ `未开工(${projectData.notStartNum})` }}
          </div>
        </div>
        <div class="btn">
          <a-divider type="vertical" class="divider" />
          <div
            @click="onTab('已完成')"
            :class="active == '已完成' ? 'active' : ''"
          >
            {{ `已完成(${projectData.okNum})` }}
          </div>
        </div>
        <div class="btn">
          <a-divider type="vertical" class="divider" />
          <div
            @click="onTab('停工中')"
            :class="active == '停工中' ? 'active' : ''"
          >
            {{ `停工中(${projectData.notStartNum2})` }}
          </div>
        </div>
        <div class="btn">
          <a-divider type="vertical" class="divider" />
          <div
            @click="onTab('停工已拆机')"
            :class="active == '停工已拆机' ? 'active' : ''"
          >
            {{ `停工已拆机(${projectData.notStartNum3})` }}
          </div>
        </div>
        <div class="btn">
          <a-divider type="vertical" class="divider" />
          <div
            @click="onTab('完工未拆机')"
            :class="active == '完工未拆机' ? 'active' : ''"
          >
            {{ `完工未拆机(${projectData.notStartNum4})` }}
          </div>
        </div>
      </div>
      <!--      <a-row :gutter="10">-->
      <!--        <a-col :span="4">-->
      <!--          <span></span>-->
      <!--        </a-col>-->
      <!--        <a-col :span="4">-->
      <!--          <span>已开工总数:{{ projectData.startedNum }}</span>-->
      <!--        </a-col>-->
      <!--        <a-col :span="4">-->
      <!--          <span>未开工:{{ projectData.notStartNum }}</span>-->
      <!--        </a-col>-->
      <!--      </a-row>-->
    </a-card>
    <div class="page">
      <div class="ele-body">
        <a-card :bordered="false">
          <!-- 表格 -->
          <ele-pro-table
            ref="tableRef"
            row-key="projectId"
            :columns="columns"
            :datasource="datasource"
            v-model:selection="selection"
            :customRow="customRow"
            :height="tableHeight"
            :full-height="fixedHeight ? 'calc(100vh - 100px)' : void 0"
            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"
              />
            </template>
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'nickname'">
                {{ record.nickname }}
              </template>
              <template v-if="column.key === 'orders'">
                {{ record.orders.length > 0 ? record.orders[0].comments : '' }}
              </template>
              <template v-if="column.key === 'createTime'">
                {{ record.createTime }}
              </template>
              <template v-if="column.key === 'action'">
                <a-space>
                  <a @click="openEdit(record)">修改</a>
                  <a-divider type="vertical" />
                  <a @click="openEdit(record)">库存查看</a>
                </a-space>
              </template>
            </template>
          </ele-pro-table>
        </a-card>
      </div>
      <!-- 编辑弹窗 -->
      <ProjectEdit v-model:visible="showEdit" :data="current" @done="reload" />
      <!-- 订单详情 -->
      <order-info v-model:visible="showInfo" :data="current" @done="reload" />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { createVNode, computed, ref, reactive } 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 Search from './components/search.vue';
  import ProjectEdit from './components/project-edit.vue';
  import OrderInfo from './components/order-info.vue';
  import {
    pageProject,
    removeBatchProject,
    removeProject,
    towerProjectData
  } from '@/api/tower/project';
  import { Project, ProjectParam } from '@/api/tower/project/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: 'projectStatus',
      key: 'projectStatus'
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
      key: 'projectName'
    },
    // {
    //   title: '具体标地',
    //   // dataIndex: 'projectCity',
    //   key: 'orders'
    // },
    {
      title: '承租单位',
      dataIndex: 'customerName',
      key: 'customerName'
    },
    {
      title: '项目所属主管部门',
      dataIndex: 'competentDepartment'
    },
    {
      title: '关联设备数',
      dataIndex: 'equipmentNum'
    },
    {
      title: '项目管理员',
      dataIndex: 'director'
    },
    // {
    //   title: '检查次数',
    //   dataIndex: 'companyId',
    //   key: 'companyId'
    // },
    // {
    //   title: '保养次数',
    //   dataIndex: 'companyId',
    //   key: 'companyId'
    // },
    {
      title: '创建时间',
      dataIndex: 'createTime'
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      align: 'center',
      hideInSetting: true
    }
  ]);

  // 表格选中数据
  const selection = ref<Project[]>([]);
  // 当前编辑数据
  const current = ref<Project | null>(null);
  // 是否显示资产详情
  const showInfo = ref(false);
  // 是否显示编辑弹窗
  const showEdit = ref(false);
  // 表格固定高度
  const fixedHeight = ref(true);
  const active = ref<any>(undefined);
  // 表格高度
  const tableHeight = computed(() => {
    return fixedHeight.value ? 'calc(100vh - 308px)' : void 0;
  });

  // 表格数据源
  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 pageProject({
      ...where,
      ...orders,
      page,
      limit
    });
  };

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

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

  /* 打开用户详情弹窗 */
  const openInfo = (row?: Project) => {
    current.value = row ?? null;
    showInfo.value = true;
  };

  let projectData = reactive({
    totalNum: 0,
    startedNum: 0,
    notStartNum: 0,
    okNum: 0,
    notStartNum2: 0,
    notStartNum3: 0,
    notStartNum4: 0
  });
  const getData = async () => {
    const res = await towerProjectData();
    for (let key in projectData) projectData[key] = res[key];
  };

  const onTab = (type: any) => {
    active.value = type;
    reload({ projectStatus: active.value });
  };

  /* 删除单个 */
  const remove = (row: Project) => {
    const hide = message.loading('请求中..', 0);
    removeProject(row.projectId)
      .then((msg) => {
        hide();
        message.success(msg);
        reload();
      })
      .catch((e) => {
        hide();
        message.error(e.message);
      });
  };

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

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

  reload();
</script>

<script lang="ts">
  export default {
    name: 'ProjectIndex'
  };
</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;
  }
  .count {
    display: flex;
    .btn {
      margin: 0 12px;
      padding: 6px 18px;
      background-color: #f3f3f3;
      border-radius: 4px;
      cursor: pointer;
      display: flex;
      align-items: center;
      font-size: 16px;
      .divider {
        width: 4px;
        height: 15px;
        border-radius: 8px;
        margin-right: 8px;
        background-color: #16a90b;
      }
      .active {
        color: #16a90b;
      }
    }
  }
</style>
