/**
 * 快递公司相关功能
 */
import { ref, reactive } from 'vue';

// 快递公司列表
const expressList = [
  { code: 'FEDEX', name: 'FedEx' },
  { code: 'UPS', name: 'UPS' },
  { code: 'DHL', name: 'DHL' },
  { code: 'PATHAO', name: 'Pathao Courier' },
  { code: 'EDESH', name: 'eDesh' },
  { code: 'STEADFAST', name: 'Steadfast' },
  { code: 'REDX', name: 'Redx' },
];

// 快递公司Hook
export default function useExpress() {
  const express = reactive({
    code: '',
    name: '',
    no: '',
  });

  const expressOptions = ref(expressList);

  // 快递公司数据
  const deliverCompany = reactive({
    data: expressList,
    loading: false,
    pageData: {
      page: 1,
      size: 10,
      total: expressList.length,
    },
  });

  // 根据快递代码获取快递公司名称
  const getExpressName = (code) => {
    const item = expressList.find((item) => item.code === code);
    return item ? item.name : '';
  };

  // 设置快递信息
  const setExpress = (code, no = '') => {
    express.code = code;
    express.name = getExpressName(code);
    express.no = no;
  };

  // 重置快递信息
  const resetExpress = () => {
    express.code = '';
    express.name = '';
    express.no = '';
  };

  // 验证快递信息
  const validateExpress = () => {
    if (!express.code) {
      return { valid: false, message: '请选择快递公司' };
    }
    if (!express.no) {
      return { valid: false, message: '请输入快递单号' };
    }
    return { valid: true, message: '' };
  };

  // 获取快递公司列表
  const getDeliverCompany = (page = 1) => {
    deliverCompany.pageData.page = page;
    // 这里可以添加实际的API调用
    deliverCompany.data = expressList;
  };

  // 快递公司选择变化
  const onChangeExpressCode = (code) => {
    express.code = code;
    express.name = getExpressName(code);
  };

  // 远程搜索方法
  const remoteMethod = (query) => {
    if (query) {
      deliverCompany.loading = true;
      setTimeout(() => {
        deliverCompany.data = expressList.filter(
          (item) =>
            item.name.toLowerCase().includes(query.toLowerCase()) ||
            item.code.toLowerCase().includes(query.toLowerCase()),
        );
        deliverCompany.loading = false;
      }, 200);
    } else {
      deliverCompany.data = expressList;
    }
  };

  return {
    express,
    expressOptions,
    deliverCompany,
    getExpressName,
    setExpress,
    resetExpress,
    validateExpress,
    getDeliverCompany,
    onChangeExpressCode,
    remoteMethod,
  };
}
