import { h } from 'vue';
import { NFlex, NImage, NTag } from 'naive-ui';
// import { fetchGetAllStoreList } from '@/service/api/goods/desk-category';
import { fetchBackendChannelSelect, fetchGetStoreList } from '@/service/api/xsb-manage/store-info';
import { fetchChannelList } from '@/service/api/h5-manage/channel-manage';
import { fetchGetDictDataList } from '@/service/api/system-manage';
// import { useAuth } from '@/hooks/business/auth';
import { useAuthStore } from '@/store/modules/auth';
import { useAuth } from '@/hooks/business/auth';
import type { FormSchema } from '@/components/zt/Form/types/form';

export const SearchForm: FormSchema[] = [
  {
    label: '业务类型',
    field: 'businessType',
    component: 'ApiSelect',
    componentProps: {
      api: fetchGetDictDataList,
      labelFeild: 'name',
      valueFeild: 'value',
      resultFeild: 'data.list',
      params: {
        typeCode: 'sys_business_type'
      }
    }
  },
  {
    label: '所属企业',
    field: 'channelIdList',
    component: 'ApiSelect',
    componentProps: {
      api: fetchBackendChannelSelect,
      multiple: true,
      labelFeild: 'name',
      valueFeild: 'id'
    }
  },
  {
    label: '门店名称',
    component: 'ApiSelect',
    field: 'shopId',
    componentProps: {
      api: fetchGetStoreList,
      resultFeild: 'data.list',
      labelFeild: 'shopName',
      valueFeild: 'shopId'
    }
  },

  {
    label: '订单编号',
    component: 'NInput',
    field: 'orderNumber'
  },
  {
    label: '下单时间',
    component: 'NDatePicker',
    field: 'createTime',
    componentProps: {
      type: 'datetimerange',
      defaultTime: ['00:00:00', '23:59:59']
    }
  },
  {
    label: '客户姓名',
    component: 'NInput',
    field: 'consigneeName'
  },
  {
    label: '客户手机号',
    component: 'NInput',
    field: 'consigneeMobile'
  },
  {
    label: '买家姓名',
    component: 'NInput',
    field: 'buyerName'
  },
  {
    label: '买家手机号',
    component: 'NInput',
    field: 'buyerMobile'
  },
  {
    field: 'userAttrType',
    label: '买家属性',
    component: 'dictSelect',
    componentProps: {
      dictCode: 'user_attr_type',
      immediate: true
    },
    show: useAuth().hasAuth('order:user:attr:type')
  },
  {
    label: '退款类型',
    component: 'NSelect',
    field: 'refundStatus',
    componentProps: {
      options: [
        {
          label: '整单退款',
          value: 2
        },
        {
          label: '部分退款',
          value: 1
        },
        {
          label: '无售后订单',
          value: 0
        }
      ]
    }
  },
  {
    field: 'accessIds',
    label: '渠道',
    component: 'ApiSelect',
    componentProps: {
      api: fetchChannelList,
      multiple: true,
      resultFeild: 'data.list',
      labelFeild: 'accessName',
      valueFeild: 'accessId'
    }
  },
  {
    label: '发货情况',
    component: 'NSelect',
    field: 'deliveryStatus',
    componentProps: {
      options: [
        {
          label: '已发货',
          value: 'Shipped'
        },
        {
          label: '未发货',
          value: 'NoShipped'
        },
        {
          label: '未发货-无需发货',
          value: 'NoNeedShipped'
        }
      ]
    },
    ifShow({ model }) {
      return model.businessType == 'XSB';
    }
  },
  {
    label: '配送方式',
    component: 'NSelect',
    field: 'dvyTypeList',
    componentProps: {
      multiple: true,
      options: [
        {
          label: '快递',
          value: 1
        },
        {
          label: '自提',
          value: 2
        },
        {
          label: '即时配送',
          value: 3
        },
        {
          label: '其他方式',
          value: 4
        },
        {
          label: '商家自送',
          value: 10
        }
      ]
    },
    ifShow({ model }) {
      return model.businessType == 'XSB';
    }
  },
  {
    label: '业务状态',
    component: 'NSelect',
    field: 'hbOrderStatus',
    componentProps: {
      options: [
        {
          label: '待支付',
          value: 0
        },
        {
          label: '订单已接单(待拣货)',
          value: 20
        },
        {
          label: '订单待配送',
          value: 30
        },
        {
          label: '订单配送中',
          value: 40
        },
        {
          label: '订单取消待审核',
          value: 50
        },
        {
          label: '订单取消',
          value: 60
        },
        {
          label: '订单已送达',
          value: 70
        },
        {
          label: '订单已完成',
          value: 80
        }
      ]
    },
    ifShow({ model }) {
      return model.businessType == 'XSB';
    }
  }
];

export const businessType = {
  XSB: '星闪豹',
  CD: '充电',
  DYY: '电影演出',
  DJK: '大健康',
  XNSP: '虚拟商品',
  JY: '加油',
  JDMP: '景区门票'
};

/**
 * 获取搜索表单schema，业务类型下拉框根据当前用户权限过滤
 * ROOT用户：显示全量字典选项
 * 非ROOT用户：只显示有权限的业务类型
 */
export function getSearchForm(): FormSchema[] {
  const authStore = useAuthStore();
  const userBusinessTypes = authStore.userInfo.businessTypes;

  // businessTypes 为 null 或 undefined 表示不限制（ROOT用户），使用原始ApiSelect拉全量
  if (!userBusinessTypes || userBusinessTypes.length === 0) {
    return [...SearchForm];
  }

  // 非ROOT用户：用NSelect + 静态选项，只显示有权限的业务类型
  const filteredOptions = userBusinessTypes.map(type => ({
    label: businessType[type as keyof typeof businessType] || type,
    value: type
  }));

  return SearchForm.map(schema => {
    if (schema.field === 'businessType') {
      return {
        ...schema,
        component: 'NSelect',
        componentProps: {
          options: filteredOptions
        }
      };
    }
    return schema;
  });
}

export enum orderStatusEnum {
  /**
   *
   *  待支付
   */
  WAIT_PAY = 0,
  /**
   * 待发货
   */
  WAIT_DELIVERY = 1,
  /**
   * 订单已接单(待拣货)
   */
  ORDER_ACCEPT = 20,
  /**
   * 订单待配送（拣货完成/自提类订单为待自提）
   */
  ORDER_WAIT_DELIVERY = 30,
  /**
   * 订单配送中
   */
  ORDER_DELIVERY = 40,
  /**
   * 订单取消待审核
   */
  ORDER_CANCEL_WAIT_AUDIT = 50,
  /**
   * 订单已取消
   */
  ORDER_CANCEL = 60,
  /**
   * 订单已退款
   */
  ORDER_REFUNDED = 61,
  /**
   * 订单已过期
   */
  ORDER_EXPIRED = 62,
  /**
   * 订单已送达
   */
  ORDER_ARRIVE = 70,
  /**
   * 订单已完成
   */
  ORDER_COMPLETE = 80
}
/**
 * 发货按钮显示状态
 */
export const ShippingButton = [
  orderStatusEnum.WAIT_DELIVERY,
  orderStatusEnum.ORDER_ACCEPT,
  orderStatusEnum.ORDER_DELIVERY,
  orderStatusEnum.ORDER_WAIT_DELIVERY
];
/**
 *  // 0-待支付 1-待发货，20-订单已接单(待拣货),30-订单待配送（拣货完成/自提类订单为待自提）,40-订单配送中
        // ,50-订单取消待审核,60-订单已取消,70-订单已送达,80-订单已完成
 */
export const orderStatus = {
  [orderStatusEnum.WAIT_PAY]: '待支付',
  [orderStatusEnum.WAIT_DELIVERY]: '待发货',
  [orderStatusEnum.ORDER_ACCEPT]: '订单已接单(待拣货)',
  [orderStatusEnum.ORDER_WAIT_DELIVERY]: '订单待配送（拣货完成/自提类订单为待自提）',
  [orderStatusEnum.ORDER_DELIVERY]: '订单配送中',
  [orderStatusEnum.ORDER_CANCEL_WAIT_AUDIT]: '订单取消待审核',
  [orderStatusEnum.ORDER_CANCEL]: '订单已取消',
  [orderStatusEnum.ORDER_ARRIVE]: '订单已送达',
  [orderStatusEnum.ORDER_COMPLETE]: '订单已完成'
};

export const refundOrderStatus = {
  0: '进行中',
  1: '已完成',
  2: '积分退款成功,微信退款失败',
  3: '退款订单已取消',
  4: '退款订单驳回'
};

export const returnMoneyStatus = {
  10: '待审核',
  20: '处理中',
  30: '驳回退款',
  40: '撤销退款',
  60: '待退货（一审同意）',
  65: '待确认收货（二审待审核）',
  70: '退款完成'
};

export const auditStatus = {
  1: '申请原因',
  2: '商家待审核，',
  3: '申请已通过',
  4: '用户撤回申请',
  5: '待用户待发货',
  7: '待商家收货',
  10: '审核通过',
  20: '驳回',
  25: '已收货',
  30: '退款成功'
};

export const DJKOrderStatus = {
  [orderStatusEnum.WAIT_PAY]: '待支付',
  [orderStatusEnum.ORDER_ACCEPT]: '待使用',
  [orderStatusEnum.ORDER_CANCEL]: '已取消',
  [orderStatusEnum.ORDER_REFUNDED]: '已退款',
  [orderStatusEnum.ORDER_EXPIRED]: '已过期',
  [orderStatusEnum.ORDER_COMPLETE]: '已核销'
};

export enum yppStatusEnum {
  /**
   *
   *  待支付
   */
  WAIT_PAY = 0,
  /**
   * 已支付
   */
  WAIT_DELIVERY = 1,
  /**
   * 出票成功
   */
  SUCCESS = 4,
  /**
   * 出票失败(退款)
   */
  REFUND_FAIL = 7,
  /**
   * 超时未支付（取消）
   */
  TIMEOUT_CANCEL = 8
}
export const yppStatus = {
  [yppStatusEnum.WAIT_PAY]: '待支付',
  [yppStatusEnum.WAIT_DELIVERY]: '已支付',
  [yppStatusEnum.SUCCESS]: '出票成功',
  [yppStatusEnum.REFUND_FAIL]: '出票失败(退款)',
  [yppStatusEnum.TIMEOUT_CANCEL]: '超时未支付（取消）'
};

/**
 // 1:申请退款 2:退款成功 3:部分退款成功 4:退款失败
 *
 */

export const refundStatus = {
  1: '申请退款',
  2: '退款成功',
  3: '部分退款成功',
  4: '退款失败'
};
/**
 *
 * 配送方式
 */

export const dvyStatus = {
  1: '快递',
  2: '自提',
  3: '即时配送'
};

export const orderColumns: NaiveUI.TableColumn<Api.delivery.OrderItemElement>[] = [
  {
    title: '商品',
    key: 'goods',
    width: 300,
    render: row => {
      const goodsNodes = [
        h(NImage, { src: row.pic, width: 80, height: 80 }),
        h('div', { class: 'ml-2 ' }, [
          h('div', { class: 'text-15px font-semibold' }, row.skuName),
          h('div', { class: 'text-gray' }, `规格：${row.spec || '--'}`)
        ])
      ];
      return h('div', { class: 'flex items-center' }, goodsNodes);
    }
  },
  {
    title: '单价（元）',
    key: 'price'
    // width: 100
  },
  {
    title: '数量',
    key: 'prodCount',
    // width: 250,
    render: row => {
      const nodes = [h('div', { class: 'mr-2' }, row.prodCount)];
      // if (row.refundSuccessCount) {
      //   nodes.push(h(NTag, { class: 'ml2', type: 'success' }, () => `退款成功：${row.refundSuccessCount}`));
      // }
      // if (row.refundIngCount && !row.refundSuccessCount) {
      //   nodes.push(h(NTag, { class: 'ml2', type: 'error' }, () => `售后处理：${row.refundIngCount}`));
      // }
      return h(NFlex, { align: 'center' }, () => nodes);
    }
  },
  {
    title: '退款成功数量',
    key: 'refundSuccessCount'
  },
  {
    title: '小计/元',
    key: 'productTotalAmount'
  }
];

export const orderShipColumns: NaiveUI.TableColumn<Api.delivery.OrderItemElement>[] = [
  {
    title: '商品',
    key: 'goods',
    width: 300,
    render: row => {
      const goodsNodes = [
        h(NImage, { src: row.pic, width: 80, height: 80 }),
        h('div', { class: 'ml-2 ' }, [
          h('div', { class: 'text-15px font-semibold' }, row.skuName),
          h('div', { class: 'text-gray' }, `规格：${row.spec || '--'}`)
        ])
      ];
      return h('div', { class: 'flex items-center' }, goodsNodes);
    }
  },
  {
    title: '原商品数量',
    key: 'prodCount',
    width: 120,
    render: row => {
      const nodes = [h('div', { class: 'mr-2' }, row.prodCount)];
      // if (row.refundSuccessCount) {
      //   nodes.push(h(NTag, { class: 'ml2', type: 'success' }, () => `退款成功：${row.refundSuccessCount}`));
      // }
      // if (row.refundIngCount && !row.refundSuccessCount) {
      //   nodes.push(h(NTag, { class: 'ml2', type: 'error' }, () => `售后处理：${row.refundIngCount}`));
      // }
      return h(NFlex, { align: 'center' }, () => nodes);
    }
  },
  {
    title: '退款成功数量',
    width: 120,
    key: 'refundSuccessCount'
  },
  {
    title: '状态',
    key: 'status',
    width: 120,
    render: () => {
      return '等待发货';
    }
  },
  {
    title: '可发货数量',
    key: 'prodCount',
    width: 120,
    render: row => {
      return h('div', { class: '' }, Number(row.prodCount) - Number(row.refundSuccessCount));
    }
  }
];

export const orderDJKColumns: NaiveUI.TableColumn<Api.delivery.OrderItemElement>[] = [
  {
    title: '商品',
    key: 'goods',
    width: 300,
    render: row => {
      const goodsNodes = [
        h(NImage, { src: row.goodsImg, width: 80, height: 80 }),
        h('div', { class: 'ml-2 ' }, [
          h('div', { class: 'text-15px font-semibold' }, row.goodsName),
          h('div', { class: 'text-gray' }, `规格：${row.goodsCode || '--'}`)
        ])
      ];
      return h('div', { class: 'flex items-center' }, goodsNodes);
    }
  },
  {
    title: '单价（元）',
    key: 'price',
    width: 100
  },
  {
    title: '数量',
    key: 'goodsNum',
    width: 250,
    render: row => {
      const nodes = [h('div', { class: 'mr-2' }, row.goodsNum)];
      if (row.refundSuccessCount) {
        nodes.push(h(NTag, { class: 'ml2', type: 'success' }, () => `退款成功：${row.refundSuccessCount}`));
      }
      if (row.refundIngCount && !row.refundSuccessCount) {
        nodes.push(h(NTag, { class: 'ml2', type: 'error' }, () => `售后处理：${row.refundIngCount}`));
      }
      return h(NFlex, { align: 'center' }, () => nodes);
    }
  },
  {
    title: '小计/元',
    key: 'productTotalAmount',
    width: 100,
    render: (row: any) => {
      return h('div', {}, (row.goodsNum * 1000 * (row.price * 1000)) / 1000000);
    }
  }
];

export const orderDJKLogColumns: NaiveUI.TableColumn<Api.delivery.OrderItemElement>[] = [
  {
    title: '时间',
    key: 'createTime'
  },
  {
    title: '操作',
    key: 'operation'
  },
  {
    title: '操作员',
    key: 'operator'
  },
  {
    title: '备注',
    key: 'remark'
  }
];

export const deliveryInfo: FormSchema[] = [
  {
    label: '配送方式',
    component: 'NGradientText',
    field: 'dvyMethod',
    render() {
      return h('div', {}, '快递');
    }
  },
  {
    label: '收货人姓名',
    component: 'NGradientText',
    field: 'receiver',
    render({ model, field }) {
      return h('div', {}, model[field]);
    }
  },
  {
    label: '收货人手机号',
    component: 'NInput',
    field: 'mobile',
    render({ model, field }) {
      return h('div', {}, model[field]);
    }
  },
  {
    label: '收货地址',
    component: 'NInput',
    field: 'address',

    render({ model, field }) {
      return h('div', {}, model[field]);
    }
  }
];

export const refundOrderColumns: NaiveUI.TableColumn<Api.delivery.OrderItemElement>[] = [
  {
    title: '退款商品',
    key: 'goods',
    width: 300,
    render: row => {
      const goodsNodes = [
        h(NImage, { src: row.pic, width: 80, height: 80 }),
        h('div', { class: 'ml-2 ' }, [
          h('div', { class: 'text-15px font-semibold' }, row.skuName || '--'),
          h('div', { class: 'text-gray' }, `规格：${row.spec || '--'}`)
        ])
      ];
      return h('div', { class: 'flex items-center' }, goodsNodes);
    }
  },
  {
    title: '购买单价（元）',
    key: 'skuPrice',
    width: 100
  },
  {
    title: '购买数量',
    key: 'productCount',
    width: 100,
    render: row => {
      const nodes = [h('div', { class: 'mr-2' }, row.productCount)];
      return h(NFlex, { align: 'center' }, () => nodes);
    }
  },
  {
    title: '小计/元',
    key: 'skuTotalPrice',
    width: 100
  },
  {
    title: '退款数量',
    key: 'refundProductCount',
    width: 100
  },
  {
    title: '退款金额/元',
    key: 'refundSkuTotalPrice',
    width: 100
  }
];

/**
 * 0:用户手动停止充电；1:客户归属地运营商平台停止充电；2:BMS停止充电；3:充电机设备故障；4:连接器断开；其它:自定义
 */

export const chargeMethod = [
  '用户手动停止充电',
  '客户归属地运营商平台停止充电',
  'BMS停止充电',
  '充电机设备故障',
  '连接器断开',
  '其它'
];

export const payType = {
  0: '积分支付',
  1: '微信支付',
  2: '支付宝'
};

export const cancelState = {
  0: '申请中',
  1: '取消成功',
  2: '取消被拒绝'
};
