import type { TableColumn } from '@/components/core/dynamic-table';
import { DictEnum } from '@/enums/dictEnum';
import { MaterialsInOutEnum } from '@/enums/materialsInventoryEnum';
import { useDictStore } from '@/store/modules/dict';
import { formatToDate } from '@/utils/dateUtil';
import { Tag } from 'ant-design-vue';

export type TableListItem = API.MaterialsInOutEntity;
export type TableColumnItem = TableColumn<TableListItem>;
const dictStore = useDictStore();
export const baseColumns: TableColumnItem[] = [
  {
    title: '产品名称',
    width: 180,
    dataIndex: 'product',
  },
  {
    title: '单位',
    width: 60,
    hideInSearch: true,
    dataIndex: 'unit',
    formItemProps: {
      component: 'Select',
      componentProps: {
        options: dictStore
          .getDictItemsByCode(DictEnum.Unit)
          .map(({ label, id }) => ({ value: id, label })),
      },
    },
    customRender: ({ record }) => {
      return dictStore.getDictItemsByCode(DictEnum.Unit)?.length
        ? dictStore.getDictItemsByCode(DictEnum.Unit).find((item) => item.id === record.unit)
            ?.label || ''
        : '';
    },
  },

  {
    title: '入库/出库',
    width: 80,
    dataIndex: 'inOrOut',
    formItemProps: {
      component: 'Select',
      componentProps: {
        options: Object.values(MaterialsInOutEnum)
          .filter((value) => typeof value === 'number')
          .map((item) => formatStatus(item as MaterialsInOutEnum)),
      },
    },
    customRender: ({ record }) => {
      const { color, label } = formatStatus(record.inOrOut);
      return <Tag color={color}>{label}</Tag>;
    },
  },
  {
    title: '时间',
    width: 120,
    align: 'center',
    dataIndex: 'time',
    formItemProps: { component: 'RangePicker' },
    customRender: ({ record }) => {
      return formatToDate(record.time);
    },
  },
  {
    title: '数量',
    hideInSearch: true,
    width: 80,
    dataIndex: 'quantity',
  },
  {
    title: '单价',
    hideInSearch: true,
    width: 80,
    dataIndex: 'unitPrice',
  },
  {
    title: '金额',
    width: 80,
    align: 'center',
    dataIndex: 'amount',
    hideInSearch: true,
  },
  {
    title: '经办人',
    width: 80,
    dataIndex: 'agent',
  },
  {
    title: '领料单号',
    width: 80,
    dataIndex: 'issuanceNumber',
  },
  {
    title: '项目',
    width: 80,
    dataIndex: 'project',
  },
  {
    title: '备注',
    width: 80,
    dataIndex: 'remark',
  },
];

export function formatStatus(status: MaterialsInOutEnum): {
  color: string;
  label: string;
  value: number;
} {
  switch (status) {
    case MaterialsInOutEnum.In:
      return {
        color: 'green',
        label: '入库',
        value: MaterialsInOutEnum.In,
      };
    case MaterialsInOutEnum.Out:
      return {
        color: 'red',
        label: '出库',
        value: MaterialsInOutEnum.Out,
      };
    default:
      return {
        color: 'green',
        label: '入库',
        value: MaterialsInOutEnum.In,
      };
  }
}
