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: '仅退款（未发货）待审核',
    type: 0,
    dealStatus: 14,
  },
  2: {
    label: '仅退款待审核',
    type: 1,
    dealStatus: 14,
  },
  3: {
    label: '退货退款待审核',
    type: 2,
    dealStatus: 14,
  },
  4: {
    label: '退货入库待审核',
    dealStatus: 40,
  },
  5: {
    label: '已完成',
    dealStatus: 70,
  },
};

// 售后类型
const AFTER_TYPE = [
  {
    value: 0,
    name: '仅退款（未发货）',
  },
  {
    value: 1,
    name: '仅退款',
  },
  {
    value: 2,
    name: '退货退款',
  },
];

// 售后状态
const AFTER_STATUS = [
  {
    value: 14,
    name: '商户审核中',
  },
  {
    value: 16,
    name: '商户审核拒绝',
  },
  {
    value: 30,
    name: '待填写退货物流信息',
  },
  {
    value: 40,
    name: '待退货入库',
  },
  {
    value: 50,
    name: '退货拒收',
  },
  {
    value: 70,
    name: '退款成功',
  },
  {
    value: 99,
    name: '用户撤销',
  },
];

export const getFormConfig = (props = {}) => {
  const { setTableParams, setCurrentTab, tableParams, actionRef } = props;
  return {
    formConfig: [
      {
        type: SEARCH_TYPE.INPUT,
        label: '订单ID',
        bindKey: 'orderNo',
        column: 5,
      },
      {
        type: SEARCH_TYPE.INPUT,
        label: '售后单ID',
        bindKey: 'serviceNo',
        column: 5,
      },
      {
        type: SEARCH_TYPE.SELECT,
        label: '售后状态',
        column: 5,
        bindKey: 'dealStatus',
        options: AFTER_STATUS,
        originOptions: {
          allowClear: true,
        },
      },
      {
        type: SEARCH_TYPE.SELECT,
        label: '售后类型',
        column: 5,
        bindKey: 'type',
        options: AFTER_TYPE,
        originOptions: {
          allowClear: true,
        },
      },
      {
        type: SEARCH_TYPE.INPUT,
        label: '收货人姓名',
        column: 5,
        bindKey: 'receiverName',
      },
      {
        type: SEARCH_TYPE.INPUT,
        label: '收货人手机号',
        column: 5,
        bindKey: 'receiverPhone',
      },
      {
        type: SEARCH_TYPE.RANGE_PICKER,
        label: '售后日期',
        column: 5,
        bindKey: 'afterTime',
        limit: {
          rangeNum: 3,
          rangeUnit: 'months',
        },
        originOptions: {
          placeholder: ['开始日期', '结束日期'],
          allowClear: false,
        },
      },
    ],
    btnConfig: [
      {
        label: '筛选',
        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: '重置',
        type: '',
        clickType: 'reset',
        onClick: ({ params }) => {
          setTableParams({});
          actionRef.current.reload();
          setCurrentTab('');
        },
      },
    ],
  };
};

export const appealType = {
  1: '已申诉',
  0: '未申诉',
};

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: '审核倒计时',
      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="HH时mm分ss秒"
            value={serviceTime}
            valueStyle={{ color: 'red', fontSize: '14px' }}
          />
        );
      },
    },
  ];
  // 售后状态：已完成/退款成功不展示审核倒计时
  if (dealStatus === 70) {
    auditCountDown = [];
  }

  return [
    ...auditCountDown,
    {
      title: '售后状态',
      dataIndex: 'serviceStatus',
      hideInSearch: true,
      width: 120,
    },
    {
      title: '售后类型',
      dataIndex: 'serviceType',
      hideInSearch: true,
      width: 140,
      render: serviceType => {
        if (+serviceType === 0) {
          return <span style={{ color: '#ff1616' }}>仅退款(未发货)</span>;
        }
        if (+serviceType === 1) {
          return (
            <span style={{ color: '#ff1616' }}>
              {/* {AFTER_TYPE.find(item=> item.value === serviceType)} */}
              仅退款
            </span>
          );
        }
        return <span>退货退款</span>;
      },
    },
    {
      title: '售后单ID',
      dataIndex: 'serviceNo',
      width: 300,
      render: (serviceNo, r) => (
        <div>
          {r.timeout ? <Tag color="red">{serviceNo}</Tag> : serviceNo}
          {<Badge count={r.reminderFlag ? '催' : ''} size="default" />}
        </div>
      ),
    },
    {
      title: '订单ID',
      dataIndex: 'orderNo',
      hideInSearch: true,
      width: 300,
    },
    {
      title: '收货人信息',
      dataIndex: 'receiverName',
      width: 200,
      render: (_, record) => {
        const { receiverPhone, receiveAddress } = record;
        return (
          <>
            <p>{_}</p>
            <p>{receiverPhone}</p>
            <p>{receiveAddress}</p>
          </>
        );
      },
    },
    {
      title: '订单开始时间',
      width: 120,
      dataIndex: 'startDate',
      key: 'startDate',
      valueType: 'date',
      hideInTable: true,
    },
    {
      title: '订单结束时间',
      width: 120,
      dataIndex: 'endDate',
      key: 'endDate',
      valueType: 'date',
      hideInTable: true,
    },
    {
      title: '售后原因',
      dataIndex: 'serviceReason',
      hideInSearch: true,
      width: 200,
    },
    {
      title: '售后发生时间',
      dataIndex: 'serviceTime',
      hideInSearch: true,
      width: 200,
    },
    {
      title: '超时时间',
      dataIndex: 'overtime',
      hideInSearch: true,
      width: 200,
    },
    // {
    //   title: '是否催办',
    //   dataIndex: 'reminderFlag',
    //   hideInSearch: true,
    //   width: 120,
    //   valueEnum: {
    //     true: '是',
    //     false: '否',
    //   },
    // },
    {
      title: '是否同意售后',
      dataIndex: 'isAgree',
      hideInSearch: true,
      width: 120,
    },
    {
      title: '拒绝原因',
      dataIndex: 'refuseReason',
      hideInSearch: true,
      width: 200,
    },
    {
      title: '商家退货信息',
      dataIndex: 'merchantAddress',
      hideInSearch: true,
      width: 200,
      render: (_, record) => {
        const { expressCompanyName, deliveryNo } = record;
        return (
          <>
            <p>{_}</p>
            <p>{expressCompanyName}</p>
            <p>{deliveryNo}</p>
          </>
        );
      },
    },
    {
      title: '售后凭证',
      dataIndex: 'proofs',
      hideInSearch: true,
      width: 100,
      render: (val, r) => <a onClick={() => viewProofs(r.proofs)}>查看凭证</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: '操作',
      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: '确定允许退款？',
          okText: '确认',
          cancelText: '取消',
          key: 'pop',
        };

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

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

        let cancelAuditBtn = (
          <Button key="cancellink1" onClick={() => openCancelAudit(record)} {...btnProps}>
            审核
          </Button>
        );

        const cancelDetailBtn = (
          <Button key="cancellink2" onClick={() => viewCancelDetail(record)} {...btnProps}>
            订单详情
          </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
        if (serviceType === 0) {
          // 待商户审核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];
      },
    },
  ];
};
