<script setup lang="ts">
import { onMounted, ref } from "vue";
import { PlusOutlined } from "@ant-design/icons-vue";
import PageHeader from "@/components/PageHeader.vue";
import QueryBox from "./components/report-list/QueryBox.vue";
import type { FieldType } from "./components/report-list/QueryBox.vue";
import CompanySelect from "./components/report-list/CompanySelect.vue";
import ReportItem from "./components/report-list/ReportItem.vue";
import * as reportService from "@/services/report.service";
import * as reportsService from "@/services/reports.service";
import { CompLog } from "@/libs/log.lib";
import type { ReportBasic } from "@/types/report.types";
import { routeToReportEditor } from "@/router";
import SpinComponent from "@/components/SpinComponent.vue";
import TemplateSelect from "./components/TemplateSelect.vue";
import { message } from "ant-design-vue";

const _componentName = "ReportListView";
const logError = CompLog.logErr(_componentName);

const currentPage = ref(1);

const reportStatus = ref([
  {
    label: "全部",
    value: undefined,
  },
  {
    label: "编写中",
    value: 0,
  },
  {
    label: "已完成",
    value: 1,
  },
]);

const status = ref(undefined);

interface CompanyAggProp {
  id?: number;
  label: string;
  tail: number;
  checked: boolean;
}
// 我服务的企业名录列表
const companies = ref<CompanyAggProp[]>([]);
// 报告总数
const total = ref(0);
// 当前面报告列表
const reports = ref<ReportBasic[]>([]);
// 加载状态
const spinning = ref(true);
// 查询字段
const field = ref<FieldType>("title");
// 查询关键词
const keyword = ref("");
// 过滤栏选择的企业id
const companyIdSelected = ref<Array<number>>([]);
// 模板选择器ref
const templateSelect = ref<InstanceType<typeof TemplateSelect> | null>(null);

function fetchReports(
  companyIds?: Array<number>,
  page?: number,
  field?: string,
  keyword?: string
) {
  spinning.value = true;
  reportsService
    .query(page, companyIds, field, keyword, status.value)
    .then((resp) => {
      total.value = resp.total;
      reports.value = resp.reports;
      spinning.value = false;
    })
    .catch((err) => {
      // logError(err);
      spinning.value = false;
    });
}

// function onCompanySelectChange(event: {index: number, checked: boolean}) {
//   console.log('company select change', event);
//   const company = companies.value[event.index];
//   company.checked = event.checked;

//   if (company.id || company.id == 0) {
//     if (!event.checked) {
//       companyIdSelected.value.splice(companyIdSelected.value.indexOf(company.id), 1);
//     } else {
//       companyIdSelected.value.push(company.id);
//     }
//   }

//   if (companyIdSelected.value) {
//     if (companyIdSelected.value.length > 0) {
//       fetchReports(companyIdSelected.value)
//     } else {
//       fetchReports()
//     }
//   }
// }

function onQuery(queryData: { field: string; keyword: string }) {
  currentPage.value = 1;
  fetchReports(
    companyIdSelected.value,
    currentPage.value,
    queryData.field,
    queryData.keyword
  );
}

function onPaginationChange(page: number) {
  fetchReports(companyIdSelected.value, page, field.value, keyword.value)
}

function onCreateReport() {
  templateSelect.value?.show();
}

// function onTemplateSelected(templateId: number | null) {
//   reportService.create({templateId}).then((id) => {
//     // routeToReportEditor(id);
//   }).catch(logError);
// }

function onFilterChange() {
  currentPage.value = 1;
  fetchReports(companyIdSelected.value, currentPage.value);
}

function onReportDelete(id: number) {
  reportService
    .remove(id)
    .then((ok) => {
      if (ok) {
        message.success("删除报告成功");
        currentPage.value =
          reports.value.length === 1 ? currentPage.value - 1 : currentPage.value;
        fetchReports(
          companyIdSelected.value,
          currentPage.value,
          field.value,
          keyword.value
        );
      } else {
        message.success("删除报告失败");
      }
    })
    .catch(() => {
      message.success("删除报告失败");
    });
}

function serialNumber(index: number) {
  index += 1;
  return (currentPage.value - 1) * 10 + index;
}

onMounted(() => {
  fetchReports();
  // 左侧企业名录统计;
  // reportsService
  //   .agg()
  //   .then((aggs) => {
  //     companies.value = aggs
  //       .filter((agg) => agg.count > 0)
  //       .map((agg) => {
  //         return {
  //           id: agg.companyId,
  //           label: agg.name,
  //           tail: agg.count,
  //           checked: false,
  //         };
  //       });
  //   })
  //   .catch(logError);
});
</script>

<template>
  <div class="reports-wrap">
    <PageHeader title="全部报告">
      <a-button type="primary" @click="onCreateReport"
        ><plus-outlined />新建报告</a-button
      >
    </PageHeader>

    <div class="query-box-wrap">
      <QueryBox v-model:field="field" v-model:keyword="keyword" @search="onQuery" />
    </div>

    <div class="filter-box-wrap">
      <a-radio-group
        :options="reportStatus"
        v-model:value="status"
        @change="onFilterChange()"
      />
    </div>

    <a-row class="main-content" :gutter="24">
      <!-- <a-col :xxl="5" :xl="6" :lg="7" :span="8" class="company-filter-wrap">
        <h3>我所服务的企业  <span>【{{ companies.length }}】</span></h3>
        <CompanySelect :data="companies" @change="onCompanySelectChange" />
      </a-col> -->

      <a-col :xxl="24" :xl="24" :lg="24" :span="24">
        <SpinComponent :spinning="spinning">
          <ReportItem
            v-for="(report, index) in reports"
            :data="report"
            :key="index"
            :serialNumber="serialNumber(index)"
            class="report-item"
            @delete="onReportDelete"
          />
        </SpinComponent>
      </a-col>
    </a-row>
    <div class="pagination-wrap">
      <a-pagination
        v-model:current="currentPage"
        :total="total"
        @change="onPaginationChange"
      />
    </div>
  </div>
  <!-- <TemplateSelect ref="templateSelect" @ok="onTemplateSelected" /> -->
</template>

<style scoped lang="scss">
@import "@/assets/base.scss";

.reports-wrap {
  .query-box-wrap {
    width: 80%;
    margin: 0 auto;
  }

  .filter-box-wrap {
    display: flex;
    margin: 1.5em 21.1%;
  }
  .main-content {
    margin-top: 1.5em;

    .company-filter-wrap {
      border: 1px solid $border-color-primary;
      padding: 20px 16px;

      > h3 > span {
        color: red;
      }
    }

    .report-item {
      margin-top: 16px;

      &:first-child {
        margin-top: 0;
      }
    }

    :deep(.ant-card) {
      background-color: #f5f5f5;

      .ant-card-head-title {
        font-size: 1.2em;
      }

      .ant-card-body p {
        margin-bottom: 0.5em;
      }

      &.ant-card-bordered {
        border: 1px solid #d0d0d0;
      }
    }
  }

  .pagination-wrap {
    margin-top: 1em;
    text-align: right;
  }
}
</style>
