import { Tag, Badge, Statistic, Button, Popconfirm } from 'antd';
import React from 'react';
import moment from 'moment';

import { SEARCH_TYPE } from '@/components/FormSearch';

const { Countdown } = Statistic;

export const TAB_MAPPING_DATA = {
  '': {},
  1: {
    label: $t('pending.refund.review.unshipped'),
    type: 0,
    dealStatus: 14,
  },
  2: {
    label: $t('pending.refund.review'),
    type: 1,
    dealStatus: 14,
  },
  3: {
    label: $t('refund.pending'),
    type: 2,
    dealStatus: 14,
  },
  4: {
    label: $t('return.pending.review'),
    dealStatus: 40,
  },
  5: {
    label: $t('completed'),
    dealStatus: 70,
  },
};

// 售后类型
const AFTER_TYPE = [
  {
    value: 0,
    name: $t('refund.only.unshipped'),
  },
  {
    value: 1,
    name: $t('refund.only'),
  },
  {
    value: 2,
    name: $t('return.refund'),
  },
];

// 售后状态
const AFTER_STATUS = [
  {
    value: 14,
    name: $t('merchant.under.review'),
  },
  {
    value: 16,
    name: $t('merchant.approval.rejected'),
  },
  {
    value: 30,
    name: $t('pending.return.logistics'),
  },
  {
    value: 40,
    name: $t('pending.return'),
  },
  {
    value: 50,
    name: $t('return.rejected'),
  },
  {
    value: 70,
    name: $t('refund.success'),
  },
  {
    value: 99,
    name: $t('user.revoked'),
  },
];

export const getFormConfig = (props = {}) => {
  const { setTableParams, setCurrentTab, tableParams, actionRef } = props;
  return {
    formConfig: [
      {
        type: SEARCH_TYPE.INPUT,
        label: $t('order.id'),
        bindKey: 'orderNo',
        column: 5,
      },
      {
        type: SEARCH_TYPE.INPUT,
        label: $t('aftersales.id'),
        bindKey: 'serviceNo',
        column: 5,
      },
      {
        type: SEARCH_TYPE.SELECT,
        label: $t('aftersales.status'),
        column: 5,
        bindKey: 'dealStatus',
        options: AFTER_STATUS,
        originOptions: {
          allowClear: true,
        },
      },
      {
        type: SEARCH_TYPE.SELECT,
        label: $t('aftersales.type'),
        column: 5,
        bindKey: 'type',
        options: AFTER_TYPE,
        originOptions: {
          allowClear: true,
        },
      },
      {
        type: SEARCH_TYPE.INPUT,
        label: $t('receiver.name'),
        column: 5,
        bindKey: 'receiverName',
      },
      {
        type: SEARCH_TYPE.INPUT,
        label: $t('receiver.mobile'),
        column: 5,
        bindKey: 'receiverPhone',
      },
      {
        type: SEARCH_TYPE.RANGE_PICKER,
        label: $t('aftersales.date'),
        column: 5,
        bindKey: 'afterTime',
        limit: {
          rangeNum: 3,
          rangeUnit: 'months',
        },
        originOptions: {
          placeholder: [$t('start.date'), $t('end.date')],
          allowClear: false,
        },
      },
    ],
    btnConfig: [
      {
        label: $t('filter'),
        clickType: 'submit',
        onClick: ({ params }) => {
          // 参数相同，直接执行刷新
          if (JSON.stringify(params) === JSON.stringify(tableParams)) {
            actionRef.current.reload();
            return;
          }

          const { type, dealStatus } = params;
          let hasMatchingKey = '';
          Object.keys(TAB_MAPPING_DATA).forEach(key => {
            const item = TAB_MAPPING_DATA[key];
            if (type === item.type && dealStatus === item.dealStatus) {
              hasMatchingKey = key;
            }
          });
          setCurrentTab(hasMatchingKey);
          setTableParams(params);
        },
      },
      {
        label: $t('reset'),
        type: '',
        clickType: 'reset',
        onClick: ({ params }) => {
          setTableParams({});
          actionRef.current.reload();
          setCurrentTab('');
        },
      },
    ],
  };
};

export const appealType = {
  1: $t('appealed'),
  0: $t('not.appealed'),
};

export const getColumns = props => {
  const {
    openAudit,
    // viewAppeal,
    viewProofs,
    openLogistics,
    viewDetail,
    viewLog,
    handleCom,
    refund,
    reject,
    canEditable,
    openCancelAudit,
    viewCancelDetail,
    tableParams,
  } = props;

  const { dealStatus } = tableParams;

  let auditCountDown = [
    {
      title: $t('review.countdown'),
      dataIndex: 'serviceTime',
      key: 'serviceTime',
      hideInSearch: true,
      width: 150,
      render: (val, record) => {
        if (record.status !== 14) {
          return <div align="center">-</div>;
        }
        const serviceTime = moment(record.approvalEndTime).valueOf();
        return (
          <Countdown
            format={$t('hhmmss')}
            value={serviceTime}
            valueStyle={{ color: 'red', fontSize: '14px' }}
          />
        );
      },
    },
  ];
  // 售后状态：已完成/退款成功不展示审核倒计时
  if (dealStatus === 70) {
    auditCountDown = [];
  }

  return [
    ...auditCountDown,
    {
      title: $t('aftersales.status'),
      dataIndex: 'serviceStatus',
      hideInSearch: true,
      width: 120,
    },
    {
      title: $t('aftersales.type'),
      dataIndex: 'serviceType',
      hideInSearch: true,
      width: 140,
      render: serviceType => {
        if (+serviceType === 0) {
          return <span style={{ color: '#ff1616' }}>{$t('refund.only.not.shipped')}</span>;
        }
        if (+serviceType === 1) {
          return (
            <span style={{ color: '#ff1616' }}>
              {/* {AFTER_TYPE.find(item=> item.value === serviceType)} */}{$t('refund.only')}</span>
          );
        }
        if (+serviceType === 4) {
          return <span style={{ color: '#ff1616' }}>{$t('refund.only.shipping')}</span>;
        }
        return <span>{$t('return.refund')}</span>;
      },
    },
    {
      title: $t('aftersales.id'),
      dataIndex: 'serviceNo',
      width: 300,
      render: (serviceNo, r) => (
        <div>
          {r.timeout ? <Tag color="red">{serviceNo}</Tag> : serviceNo}
          {<Badge count={r.reminderFlag ? $t('remind') : ''} size="default" />}
          {<Badge count={+r.autoCancelTimeType === 1 ? $t('large.payment') : ''} size="default" />}
        </div>
      ),
    },
    {
      title: $t('order.id'),
      dataIndex: 'orderNo',
      hideInSearch: true,
      width: 300,
    },
    {
      title: $t('recipient.info'),
      dataIndex: 'receiverName',
      width: 200,
      render: (_, record) => {
        const { receiverPhone, receiveAddress } = record;
        return (
          <>
            <p>{_}</p>
            <p>{receiverPhone}</p>
            <p>{receiveAddress}</p>
          </>
        );
      },
    },
    {
      title: $t('order.start.time'),
      width: 120,
      dataIndex: 'startDate',
      key: 'startDate',
      valueType: 'date',
      hideInTable: true,
    },
    {
      title: $t('order.end.time'),
      width: 120,
      dataIndex: 'endDate',
      key: 'endDate',
      valueType: 'date',
      hideInTable: true,
    },
    {
      title: $t('aftersales.reason'),
      dataIndex: 'serviceReason',
      hideInSearch: true,
      width: 200,
    },
    {
      title: $t('aftersales.occurrence.time'),
      dataIndex: 'serviceTime',
      hideInSearch: true,
      width: 200,
    },
    {
      title: $t('timeout.period'),
      dataIndex: 'overtime',
      hideInSearch: true,
      width: 200,
    },
    // {
    //   title: '是否催办',
    //   dataIndex: 'reminderFlag',
    //   hideInSearch: true,
    //   width: 120,
    //   valueEnum: {
    //     true: '是',
    //     false: '否',
    //   },
    // },
    {
      title: $t('approve.aftersale'),
      dataIndex: 'isAgree',
      hideInSearch: true,
      width: 120,
    },
    {
      title: $t('rejection.reason'),
      dataIndex: 'refuseReason',
      hideInSearch: true,
      width: 200,
    },
    {
      title: $t('merchant.return.info'),
      dataIndex: 'merchantAddress',
      hideInSearch: true,
      width: 200,
      render: (_, record) => {
        const { expressCompanyName, deliveryNo } = record;
        return (
          <>
            <p>{_}</p>
            <p>{expressCompanyName}</p>
            <p>{deliveryNo}</p>
          </>
        );
      },
    },
    {
      title: $t('aftersales.proof'),
      dataIndex: 'proofs',
      hideInSearch: true,
      width: 100,
      render: (val, r) => <a onClick={() => viewProofs(r.proofs)}>{$t('view.proof')}</a>,
    },
    // {
    //   title: '售后申诉',
    //   dataIndex: 'appealFlag',
    //   valueEnum: appealType,
    //   hideInSearch: true,
    //   width: 120,
    //   render: (appealFlag, r) => {
    //     if (appealFlag) {
    //       return <a onClick={() => viewAppeal(r)}>已申诉</a>;
    //     }
    //     return <div>未申诉</div>;
    //   },
    // },
    {
      title: $t('actions'),
      hideInSearch: true,
      dataIndex: 'action',
      width: 250,
      fixed: 'right',
      render: (val, record) => {
        const {
          status,
          supplierType,
          serviceType,
          intercept,
          showRefuse,
          showRefund,
          showLogistics,
          showRefunded,
          isReceived,
        } = record;
        // 是否是服务类商品
        const isServiceGoods = ['pop'].includes(supplierType);
        // 按钮通用属性
        const btnProps = {
          className: 'mr10 mt10',
          type: 'primary',
        };

        const refundBtnProps = {
          title: $t('confirm.refund.approval'),
          okText: $t('confirm'),
          cancelText: $t('cancel'),
          key: 'pop',
        };

        /** @name applyTpye=1 */
        // 允许退款/已退款按钮
        const refundBtn = (
          <Popconfirm {...refundBtnProps} onConfirm={() => refund(record)} disabled={!showRefund}>
            <Button key="link1" {...btnProps} disabled={!showRefund}>
              {showRefunded ? $t('refunded') : $t('allow.refund')}
            </Button>
          </Popconfirm>
        );
        // 审核按钮
        let auditBtn = (
          <Button key="link2" onClick={() => openAudit(record)} {...btnProps}>{$t('review')}</Button>
        );

        // 驳回按钮
        let refuseBtn = (
          <Button key="link3" onClick={() => reject(record)} {...btnProps} disabled={!showRefuse}>{$t('reject')}</Button>
        );
        // 物流拦截按钮
        let logisticsInterceptionBtn = (
          <Button
            key="link7"
            onClick={() => openLogistics(record)}
            {...btnProps}
            disabled={serviceType !== 1 || (serviceType === 1 && intercept)}
          >{$t('logistics.interception')}</Button>
        );
        // 订单详情
        const detailBtn = (
          <Button key="link4" onClick={() => viewDetail(record)} {...btnProps}>{$t('order.details')}</Button>
        );
        // 查看物流
        const viewLogisticsBtn = (
          <Button
            key="link5"
            onClick={() => handleCom(record)}
            {...btnProps}
            disabled={!showLogistics}
          >{$t('return.logistics')}</Button>
        );
        // 查看记录
        const viewLogBtn = (
          <Button key="link6" onClick={() => viewLog(record)} {...btnProps}>{$t('view.records')}</Button>
        );

        let cancelAuditBtn = (
          <Button key="cancellink1" onClick={() => openCancelAudit(record)} {...btnProps}>{$t('review')}</Button>
        );

        const cancelDetailBtn = (
          <Button key="cancellink2" onClick={() => viewCancelDetail(record)} {...btnProps}>{$t('order.details')}</Button>
        );

        // 仅退款状态 && 用户已收到货 不展示物流拦截按钮
        if (serviceType === 1 && isReceived === 1) {
          logisticsInterceptionBtn = '';
        }

        // 无权限 不展示审核、驳回、物流拦截
        if (!canEditable) {
          auditBtn = '';
          refuseBtn = '';
          logisticsInterceptionBtn = '';
          cancelAuditBtn = '';
        }

        // 服务商品
        if (isServiceGoods) {
          // 待商户审核14
          if ([14].includes(status)) {
            return [auditBtn, detailBtn, viewLogBtn];
          }

          // 拒绝16, 处理成功70
          if ([16, 70].includes(status)) {
            return [detailBtn, viewLogBtn];
          }
        }

        // 实物商品-仅退款未发货 serviceType = 0, 仅退款(发货中) serviceType = 4
        if (serviceType === 0 || serviceType === 4) {
          // 待商户审核14 待审核0
          if ([14, 0].includes(status)) {
            return [cancelAuditBtn, cancelDetailBtn, viewLogBtn];
          }

          // 拒绝16, 处理成功70
          if ([16, 70].includes(status)) {
            return [cancelDetailBtn, viewLogBtn];
          }
        }

        // 实物商品-仅退款 serviceType = 1
        if (serviceType === 1) {
          // 待商户审核14
          if ([14].includes(status)) {
            return [auditBtn, detailBtn, viewLogBtn, logisticsInterceptionBtn];
          }
          // 拒绝16/处理成功70
          if ([16, 70].includes(status)) {
            return [detailBtn, viewLogBtn];
          }
        }

        // 实物商品-退货退款 serviceType = 2
        if (serviceType === 2) {
          // 待商户审核14
          if ([14].includes(status)) {
            return [auditBtn, detailBtn, viewLogBtn];
          }
          // 待退货入库40
          if ([40].includes(status)) {
            return [refundBtn, refuseBtn, viewLogisticsBtn, detailBtn, viewLogBtn];
          }
          // 拒绝16/待填写退货物流信息30/处理成功70
          if ([16, 30, 70].includes(status)) {
            return [viewLogisticsBtn, detailBtn, viewLogBtn];
          }
        }

        return [detailBtn, viewLogBtn];
      },
    },
  ];
};
