import type { TableColumn } from '@/components/core/dynamic-table';
import { ContractStatusEnum } from '@/enums/contractEnum';
import { formatToDate } from '@/utils/dateUtil';
import { Tag } from 'ant-design-vue';

export type TableListItem = API.ContractEntity;
export type TableColumnItem = TableColumn<TableListItem>;

export const baseColumns = (ctx: { contractTypes: API.DictItemEntity[] }): TableColumnItem[] => {
  const { contractTypes } = ctx;
  return [
    {
      title: '合同编号',
      width: 120,
      dataIndex: 'contractNumber',
    },
    {
      title: '合同标题',
      width: 200,
      dataIndex: 'title',
    },
    {
      title: '合同类型',
      width: 80,
      formItemProps: {
        component: 'Select',
        componentProps: {
          options: contractTypes.map(({ label, id }) => ({ value: id, label })),
        },
      },
      dataIndex: 'type',
      customRender: ({ record }) => {
        return contractTypes?.length
          ? contractTypes.find((item) => item.id === record.type)?.label || ''
          : '';
      },
    },
    {
      title: '甲方',
      width: 150,
      dataIndex: 'partyA',
    },
    {
      title: '乙方',
      width: 150,
      dataIndex: 'partyB',
    },
    {
      title: '签订时间',
      width: 100,
      hideInSearch: true,
      dataIndex: 'signingDate',
      customRender: ({ record }) => {
        return formatToDate(record.signingDate);
      },
    },
    {
      title: '交付期限',
      width: 100,
      hideInSearch: true,
      dataIndex: 'deliveryDeadline',
      customRender: ({ record }) => {
        return formatToDate(record.deliveryDeadline);
      },
    },
    {
      title: '审核结果',
      dataIndex: 'status',
      maxWidth: 60,
      width: 60,
      formItemProps: {
        component: 'Select',
        componentProps: {
          options: Object.values(ContractStatusEnum)
          .filter((value) => typeof value === 'number')
          .map((item) => formatStatus(item as ContractStatusEnum)),
        },
      },
      customRender: ({ record }) => {
        const { color, label } = formatStatus(record.status);
        return <Tag color={color}>{label}</Tag>;
      },
    },
  ];
};

export function formatStatus(status: ContractStatusEnum): {
  color: string;
  label: string;
  value: number;
} {
  switch (status) {
    case ContractStatusEnum.Pending:
      return {
        color: '#ccc',
        label: '待审核',
        value: ContractStatusEnum.Pending,
      };
    case ContractStatusEnum.Approved:
      return {
        color: 'green',
        label: '已通过',
        value: ContractStatusEnum.Approved,
      };
    case ContractStatusEnum.Rejected:
      return {
        color: 'red',
        label: '已拒绝',
        value: ContractStatusEnum.Rejected,
      };
    default:
      return {
        color: '#ccc',
        label: '待审核',
        value: ContractStatusEnum.Pending,
      };
  }
}
