import type { VxeGridProps } from '#/adapter/vxe-table';

import { message } from 'ant-design-vue';

import { getWarehouseProductTypeOptions } from '#/views/business/warehouse-drug-management/admin/api';

import {
  getStoreDrugsByTypeApi,
  updateStoreDrugPricesApi,
} from '../api';

export interface DrugItem {
  id: number;
  drug_id: number;
  drug_name: string;
  image?: string;
  price: number;
  buy_price: number;
}

export interface ProductTypeOption {
  label: string;
  value: number;
}

const TCM_PLACEHOLDER_IMAGE =
  'https://xiaokang88.oss-cn-hangzhou.aliyuncs.com/xk_upload_20250510/cd470ebf97e31c4048ba502ba71b66a3.jpg';

export async function fetchProductTypeOptions(): Promise<ProductTypeOption[]> {
  const data = await getWarehouseProductTypeOptions();
  return Array.isArray(data) ? data : [];
}

/**
 * 单行保存函数
 */
export const handleSaveRow = async (
  row: DrugItem,
  storeId: number,
  gridApi: any,
) => {
  if (!storeId) {
    message.error('门店ID不能为空');
    return;
  }

  try {
    const tableData = gridApi?.grid?.getTableData?.();
    const fullData = tableData?.fullData || [];
    const currentRow = fullData.find((item: DrugItem) => item.id === row.id);

    if (!currentRow) {
      message.error('未找到该行数据');
      return;
    }

    const drugs = [
      {
        id: currentRow.id,
        price: parseFloat(String(currentRow.price)) || 0,
        buy_price: parseFloat(String(currentRow.buy_price)) || 0,
      },
    ];

    for (const drug of drugs) {
      if (drug.price < 0 || drug.buy_price < 0) {
        message.error('价格不能为负数');
        return;
      }
      if (isNaN(drug.price) || isNaN(drug.buy_price)) {
        message.error('价格格式不正确');
        return;
      }
    }

    await updateStoreDrugPricesApi({
      store_id: storeId,
      drugs,
    });

    message.success('保存成功');
    gridApi?.reload?.();
  } catch (error: any) {
    message.error(error?.message || '保存失败');
  }
};

/**
 * 批量保存函数（只保存修改的数据）
 */
export const handleBatchSave = async (gridApi: any, storeId: number) => {
  if (!storeId) {
    message.error('门店ID不能为空');
    return;
  }

  try {
    const recordset = gridApi?.grid?.getRecordset?.();
    const updateRecords = recordset?.updateRecords || [];

    if (updateRecords.length === 0) {
      const tableData = gridApi?.grid?.getTableData?.();
      const fullData = tableData?.fullData || [];

      if (fullData.length === 0) {
        message.warning('没有可保存的数据');
        return;
      }

      const drugs = fullData.map((row: DrugItem) => ({
        id: row.id,
        price: parseFloat(String(row.price)) || 0,
        buy_price: parseFloat(String(row.buy_price)) || 0,
      }));

      for (const drug of drugs) {
        if (drug.price < 0 || drug.buy_price < 0) {
          message.error('价格不能为负数');
          return;
        }
        if (isNaN(drug.price) || isNaN(drug.buy_price)) {
          message.error('价格格式不正确');
          return;
        }
      }

      await updateStoreDrugPricesApi({
        store_id: storeId,
        drugs,
      });

      message.success('保存成功');
      gridApi?.reload?.();
      return;
    }

    const drugs = updateRecords.map((row: DrugItem) => ({
      id: row.id,
      price: parseFloat(String(row.price)) || 0,
      buy_price: parseFloat(String(row.buy_price)) || 0,
    }));

    for (const drug of drugs) {
      if (drug.price < 0 || drug.buy_price < 0) {
        message.error('价格不能为负数');
        return;
      }
      if (isNaN(drug.price) || isNaN(drug.buy_price)) {
        message.error('价格格式不正确');
        return;
      }
    }

    await updateStoreDrugPricesApi({
      store_id: storeId,
      drugs,
    });

    message.success('保存成功');
    gridApi?.reload?.();
  } catch (error: any) {
    message.error(error?.message || '保存失败');
  }
};

/**
 * 按 ProductTypeEnum 获取改价表格配置
 */
export const getDrugPriceGridOptions = (
  getStoreId: () => number,
  getProductType: () => number,
  onSaveRow: (row: DrugItem) => Promise<void>,
): VxeGridProps<DrugItem> => {
  const showImage = getProductType() !== 1;

  const columns: VxeGridProps<DrugItem>['columns'] = [
    { type: 'seq', width: 60, title: '序号' },
    { field: 'drug_name', title: '药品名称' },
  ];

  if (showImage) {
    columns.push({
      field: 'image',
      title: '图片',
      slots: { default: 'drug-image' },
    });
  }

  columns.push(
    {
      field: 'price',
      title: '零售价',
      editRender: { name: 'input', props: { type: 'number', step: 0.01, min: 0 } },
      formatter: ({ cellValue }) => {
        if (cellValue === null || cellValue === undefined || cellValue === '') {
          return '0.00';
        }
        const num = parseFloat(String(cellValue));
        return isNaN(num) ? '0.00' : num.toFixed(2);
      },
    },
    {
      field: 'buy_price',
      title: '供货价',
      editRender: { name: 'input', props: { type: 'number', step: 0.01, min: 0 } },
      formatter: ({ cellValue }) => {
        if (cellValue === null || cellValue === undefined || cellValue === '') {
          return '0.00';
        }
        const num = parseFloat(String(cellValue));
        return isNaN(num) ? '0.00' : num.toFixed(2);
      },
    },
    {
      title: '操作',
      slots: { default: 'row-action' },
    },
  );

  return {
    columns,
    editConfig: {
      mode: 'cell',
      trigger: 'click',
      showStatus: true,
    },
    proxyConfig: {
      ajax: {
        query: async (_ctx, formValues) => {
          const storeId = getStoreId();
          const productType = getProductType();
          if (!storeId) {
            return { items: [], total: 0 };
          }
          const res = await getStoreDrugsByTypeApi(storeId, productType);
          let items = res || [];

          if (formValues?.drug_name) {
            const keyword = String(formValues.drug_name).toLowerCase();
            items = items.filter((item: DrugItem) =>
              item.drug_name?.toLowerCase().includes(keyword),
            );
          }

          return { items, total: items.length };
        },
      },
    },
    toolbarConfig: {
      search: true,
      refresh: true,
      zoom: true,
      slots: {
        buttons: 'toolbar-actions',
      },
    },
    height: 500,
    showOverflow: true,
  };
};

export { TCM_PLACEHOLDER_IMAGE };
