<template>
  <PageWrapper dense fixedHeight contentFullHeight>
    <CollectionInfo :id="recordId" @return-page="returnPage" v-if="isShowPage" />
    <BasicTable @register="registerTable" v-else>
      <template #toolbar>
        <a-button type="primary" v-auth="'collection:add'" @click="handleCreate">
          {{ t('新增') }}
        </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex == 'overDay'">
          <span :style="{ color: `${Number(record.overDay) > 0 ? '#F56C6C' : ''}` }">
            {{ record.overDay }}
          </span>
        </template>
        <template v-if="column.dataIndex == 'state'">
          <a-tag :color="getState(record.state, false)">
            {{ getState(record.state, true) }}
          </a-tag>
        </template>
        <template v-if="column.dataIndex == 'action'">
          <TableAction
            :actions="[
              {
                label: '回款记录',
                onClick: showPage.bind(null, record),
              },
              {
                label: '编辑',
                onClick: handleEdit.bind(null, record),
              },
              {
                label: '删除',
                color: 'error',
                onClick: handleDelete.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <CollectionModal @register="registerModal" @success="reload" />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { createVNode, ref } from 'vue';
  import { BasicTable, useTable, BasicColumn, FormSchema, TableAction } from '/@/components/Table';

  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { PageWrapper } from '/@/components/Page';
  import { getCollectionPageList, deleteCollection } from '/@/api/erp/customer/collection';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import CollectionModal from './components/CollectionModal.vue';
  import CollectionInfo from './components/CollectionInfo.vue';
  import { usePermission } from '/@/hooks/web/usePermission';

  const { t } = useI18n();
  const columns: BasicColumn[] = [
    {
      title: '客户名称',
      dataIndex: 'name',
      width: 100,
      resizable: true,
    },
    {
      title: '计划回款金额',
      dataIndex: 'waitAmount',
      width: 100,
      resizable: true,
    },
    {
      title: '已回款金额',
      dataIndex: 'alreadyAmount',
      width: 100,
      resizable: true,
    },
    {
      title: '未回款金额',
      dataIndex: 'unpaidAmount',
      width: 100,
      resizable: true,
    },
    {
      title: '计划回款日期',
      dataIndex: 'receivedDate',
      width: 100,
      resizable: true,
    },
    {
      title: '最迟回款日期',
      dataIndex: 'finallyDate',
      width: 100,
      resizable: true,
    },
    {
      title: '逾期天数',
      dataIndex: 'overDay',
      width: 80,
      resizable: true,
    },
    {
      title: '合同标题',
      dataIndex: 'title',
      width: 100,
      resizable: true,
    },
    {
      title: '合同负责人',
      dataIndex: 'principalNames',
      width: 100,
      resizable: true,
    },
    {
      title: '创建日期',
      dataIndex: 'createDate',
      width: 100,
      resizable: true,
    },
    {
      title: '创建人',
      dataIndex: 'createUserName',
      width: 100,
      resizable: true,
    },
    {
      title: '状态',
      dataIndex: 'state',
      width: 80,
      resizable: true,
    },
  ];

  const searchFormSchema: FormSchema[] = [
    {
      field: 'keyword',
      label: '关键字',
      component: 'Input',
      colProps: { span: 8 },
      componentProps: {
        placeholder: '请输入关键字',
      },
    },
    {
      field: 'receivedDate',
      label: '计划回款时间',
      component: 'RangePicker',
      colProps: { span: 8 },
      componentProps: {
        format: 'YYYY-MM-DD',
        getPopupContainer: () => document.body,
      },
    },
    {
      field: 'finallyDate',
      label: '最迟回款时间',
      component: 'RangePicker',
      colProps: { span: 8 },
      componentProps: {
        format: 'YYYY-MM-DD',
        getPopupContainer: () => document.body,
      },
    },
  ];

  const { notification } = useMessage();
  const { hasPermission } = usePermission();

  const [registerModal, { openModal }] = useModal();

  const recordId = ref('');
  const isShowPage = ref<boolean>(false);

  const [registerTable, { reload }] = useTable({
    title: '回款列表',
    api: getCollectionPageList,
    rowKey: 'id',
    columns,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: searchFormSchema,
      fieldMapToTime: [
        ['receivedDate', ['receivedStartTime', 'receivedEndTime'], 'YYYY-MM-DD', true],
        ['finallyDate', ['finallyStartTime', 'finallyEndTime'], 'YYYY-MM-DD', true],
      ],
      showResetButton: false,
    },
    beforeFetch: (params) => {
      return { ...params, state: 0 };
    },
    useSearchForm: true,
    showTableSetting: true,
    striped: false,
    actionColumn: {
      width: 160,
      title: t('操作'),
      dataIndex: 'action',
    },
    customRow: (record) => {
      return {
        ondblclick: () => {
          if (hasPermission('collection:edit')) {
            handleEdit(record);
          }
        },
      };
    },
    tableSetting: {
      size: false,
    },
  });

  const getState = (state, isText) => {
    switch (state) {
      case -1:
        return isText ? '未开始' : 'error';
      case 0:
        return isText ? '进行中' : 'processing';
      case 1:
        return isText ? '已完成' : 'success';
    }
  };

  const handleCreate = () => {
    openModal(true, {
      state: 0,
      isUpdate: false,
    });
  };

  const handleEdit = (record) => {
    openModal(true, {
      state: 0,
      id: record.id,
      isUpdate: true,
    });
  };

  const handleDelete = (record) => {
    Modal.confirm({
      title: t('提示信息'),
      icon: createVNode(ExclamationCircleOutlined),
      content: t('是否确认删除？'),
      okText: t('确认'),
      cancelText: t('取消'),
      async onOk() {
        await deleteCollection(record.id);
        notification.success({
          message: t('提示'),
          description: t('删除成功'),
        });
        reload();
      },
      onCancel() {},
    });
  };

  const showPage = (record) => {
    isShowPage.value = true;
    recordId.value = record.id;
  };

  const returnPage = () => {
    isShowPage.value = false;
    reload();
  };
</script>
<style lang="less" scoped>
  .actionTxt {
    padding: 4px 2px;

    &:last-child {
      color: #f56c6c;
    }
  }
</style>
