<template>
  <LayoutVue>
    <div class="flex flex-col w-full h-full">
      <div class="flex items-center">
        <Search v-model="searchValue" placeholder="搜索备案人"></Search>
        <Avatar class="ml-7"></Avatar>
      </div>
      <div
        class="flex items-center justify-between flex-shrink-0"
        style="margin-top: 26px"
      >
        <Title
          :title="[
            { name: '版权列表', routerName: 'copyrightManagement' },
            {
              name: '备案人管理',
            },
          ]"
        ></Title>
        <div class="flex items-center">
          <syButton
            style="width: 113px"
            mode="elementBtn"
            size="large"
            @click="addFilingPersonDailogVisible = true"
            type="primary"
            >添加备案人
          </syButton>
        </div>
      </div>
      <AddFilingPerson
        v-model:visible="addFilingPersonDailogVisible"
        @add-success="handleRefetch"
        ref="AddFilingPersonRef"
      ></AddFilingPerson>
      <div class="flex-grow overflow-hidden mt-4">
        <FilingPersonTable
          ref="FilingPersonTableRef"
          @click-status-filter="handleClickStatusFilter"
          @edit="handleClickEdit"
          @refresh="handleRefetch"
          :data="tableData"
          :loading="loading"
        ></FilingPersonTable>
      </div>
    </div>
  </LayoutVue>
</template>
<script lang="ts" setup>
import LayoutVue from "@/components/Layout.vue";
import { nextTick, ref, watch } from "vue";
import Search from "@/components/Search/index.vue";
import Avatar from "@/components/Avatar/index.vue";
import Title from "@/components/Title.vue";
import { syButton } from "cqk-sy-ui";
import { eStatusOfFilerCertification } from "@/components/ApproveStatus/status";
import { useTableData } from "@/components/Table/hooks";
import { debounce } from "lodash";
import FilingPersonTable from "./components/FilingPersonTable/index.vue";
import AddFilingPerson from "@/views/AddFilingPerson/index.vue";
import { getAuths } from "@/service/copyrightService";
import { iAuth } from "@/types/copyright";

const searchValue = ref("");

const addFilingPersonDailogVisible = ref(false);
const currentStatus = ref(eStatusOfFilerCertification.ALL); // 进行中的表格的状态
const FilingPersonTableRef = ref<InstanceType<typeof FilingPersonTable>>();
const AddFilingPersonRef = ref<InstanceType<typeof AddFilingPerson>>();

const fetchTableData = ({
  page,
  page_size,
  currentStatus,
}: {
  page: number;
  page_size: number;
  currentStatus: eStatusOfFilerCertification;
}) => {
  const list =
    currentStatus === eStatusOfFilerCertification.ALL
      ? [
          eStatusOfFilerCertification.NOT_PASSED,
          eStatusOfFilerCertification.PASSED,
          eStatusOfFilerCertification.WAITING_CHECK,
        ]
      : [currentStatus];
  return getAuths(searchValue.value, list, page, page_size).then((ret) => {
    return {
      data: (ret?.data.results as iAuth[]) || [],
      total: ret?.data.total || 0,
    };
  });
};

const generateFetchTableData = (
  getCurrentStatus: () => eStatusOfFilerCertification
) => {
  return ({ page, page_size }: { page: number; page_size: number }) => {
    return fetchTableData({
      page,
      page_size,
      currentStatus: getCurrentStatus(),
    });
  };
};

const {
  fetchNextPage: fetchNextPage,
  tableData: tableData,
  refetch: refetch,
  loading: loading,
} = useTableData({
  fetchData: generateFetchTableData(() => currentStatus.value),
});

function handleRefetch() {
  FilingPersonTableRef.value?.tableRef?.scrollTo(0, 0);
  refetch();
}

const refetchDebounce = debounce(() => {
  handleRefetch();
}, 500);

const handleClickStatusFilter = (status: eStatusOfFilerCertification) => {
  currentStatus.value = status;
  refetch();
};

const handleClickEdit = ({ id }: { id: number }) => {
  addFilingPersonDailogVisible.value = true;

  nextTick(() => {
    const raw = tableData.value.find((i) => i.id === id);
    AddFilingPersonRef.value!.mode = "edit";
    AddFilingPersonRef.value!.modelOfCert.name = raw!.authentication_name;
    AddFilingPersonRef.value!.modelOfCert.property =
      raw!.authentication_subject_nature;
    AddFilingPersonRef.value!.modelOfCert.idCard =
      raw!.authentication_subject_nature_code;
    AddFilingPersonRef.value!.modelOfCert.unifiedSocialCreditCode =
      raw!.authentication_subject_nature_code;
    AddFilingPersonRef.value!.modelOfCert.powerOfAttorneyImage =
      raw!.authentication_certificate_of_authorization_image;
    AddFilingPersonRef.value!.modelOfCert.authorizationValidityPeriod =
      raw!.authentication_certificate_of_authorization_date;

    AddFilingPersonRef.value!.modelOfContact.name = raw!.contact_person;
    AddFilingPersonRef.value!.modelOfContact.email = raw!.contact_email;
    AddFilingPersonRef.value!.modelOfContact.cellphoneNumber =
      raw!.contact_mobile;
    AddFilingPersonRef.value!.modelOfContact.phoneNumber =
      raw!.contact_telephone;
    AddFilingPersonRef.value!.modelOfContact.postCode = raw!.contact_post_code;
    AddFilingPersonRef.value!.modelOfContact.fax = raw!.contact_fax;
    AddFilingPersonRef.value!.modelOfContact.addr = raw!.contact_address;
    AddFilingPersonRef.value!.modelOfCert.city = [
      raw!.authentication_province,
      raw!.authentication_city,
      raw!.authentication_district,
    ];

    AddFilingPersonRef.value!.modelOfCert.businessLicenseOrCopy =
      raw!.authentication_business_license;
    AddFilingPersonRef.value!.modelOfCert.idCardImg = {
      front: raw!.authentication_held_front_id_card,
      back: raw!.authentication_held_back_id_card,
    };

    AddFilingPersonRef.value!.id = id;
  });
};

watch(searchValue, () => {
  refetchDebounce();
});
</script>
<style lang="scss" scoped></style>
