import React, { useState, useRef } from 'react';
import { notification, Button, Popconfirm, Modal, Statistic } from 'antd';
import ProTable from '@ant-design/pro-table';
import moment from 'moment';
import _ from 'lodash';
import { searchList, auditInfoApi, orderDetail, logisticsIntercept, getOpLog } from '../services';
import { columnSticData, appealType } from '../data';
import AuditModal from '../components/auditModal';
import DetailTable from '../components/detailTable';
import ProofsModal from '../components/proofsModal';
import { getDetail } from '../../afterSale/appeal/services';
import AppealDetail from '../../afterSale/components/detail';
import AfterLog from '../components/AfterLog';
import styles from '../styles.less';

const { Countdown } = Statistic;

const { confirm } = Modal;
export default props => {
  const { canEditable } = props;
  const table = useRef();
  const [visible, setVisible] = useState(false);
  const [detailVisible, setDetailVisible] = useState(false);
  const [detailInfo, setDetailInfo] = useState([]);
  const [proofsVisible, setProofsVisible] = useState(false);
  const [proofsData, setProofsData] = useState([]);
  const [auditInfo, setAuditInfo] = useState({});
  const [appealDetailModal, setAppealDetailModal] = useState(false);
  const [selectedRow, setSelectedRow] = useState({});
  const [afterVisible, setAfterVisible] = useState(false);
  const [afterList, setAfterList] = useState([]);
  const viewDetail = async ({ serviceNo }) => {
    const data = await orderDetail({ serviceNo });
    setDetailInfo(data || []);
    setDetailVisible(true);
  };
  const closeModal = isReload => {
    if (isReload === true) {
      // eslint-disable-next-line no-unused-expressions
      table.current?.reload?.();
    }
    setVisible(false);
    setDetailVisible(false);
    setProofsVisible(false);
    setAppealDetailModal(false);
    setAfterVisible(false);
  };
  const openAudit = async ({ serviceNo, serviceType }) => {
    const data = await auditInfoApi({ serviceNo });
    setAuditInfo({ ...data?.data, serviceNo, serviceType });
    setVisible(true);
  };
  const viewProofs = proofs => {
    if (!proofs) {
      notification.warning({ message: '该订单没有凭证' });
      return;
    }
    const list = proofs.replace(/(\uff1b|\uff0c|\u003b)/g, ',').split(',');
    setProofsData(list);
    setProofsVisible(true);
  };
  const viewAppeal = async r => {
    const detailData = await getDetail({ appealNo: r.appealNo });
    setAppealDetailModal(true);
    setSelectedRow(detailData);
  };
  const viewLog = async r => {
    const data = await getOpLog(r.serviceNo);
    if (data?.data?.length) {
      setAfterList(data.data);
      setAfterVisible(true);
    }
  };
  const openLogistics = r => {
    confirm({
      title: '温馨提示',
      okText: '确认拦截',
      cancelText: '取消拦截',
      content: (
        <div>
          请48小时内自行联系物流公司进行物流拦截，系统监测拦截成功后
          <span className={styles.redTipBold}>自动同意</span>退款
        </div>
      ),
      async onOk() {
        const data = await logisticsIntercept({ serviceNo: r.serviceNo });
        if (data.businessCode === '0000') {
          notification.success({ message: '拦截成功' });
          table.current.reload();
        } else {
          notification.error({ message: data.msg || '拦截失败' });
        }
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };
  const columns = [
    {
      title: '审核倒计时',
      dataIndex: 'serviceTime',
      key: 'serviceTime',
      hideInSearch: true,
      width: 150,
      render: (val, record) => {
        const serviceTime = moment(record.approvalEndTime).valueOf();
        return (
          <Countdown
            format="HH时mm分ss秒"
            value={serviceTime}
            valueStyle={{ color: 'red', fontSize: '14px' }}
          />
        );
      },
    },
    {
      title: '售后状态',
      dataIndex: 'serviceStatus',
      hideInSearch: true,
      width: 120,
    },
    ...columnSticData,
    {
      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, r) => {
        const operations = [
          <Button key="link1" onClick={() => openAudit(r)} className="mr10 mt10" type="primary">
            审核
          </Button>,
          <Button
            disabled={r.serviceType !== 1 || (r.serviceType === 1 && r.intercept)}
            onClick={() => openLogistics(r)}
            className="mr10 mt10"
            type="primary"
          >
            物流拦截
          </Button>,
          <Button className="mr10 mt10" key="link" onClick={() => viewDetail(r)} type="primary">
            订单详情
          </Button>,
          <Button className="mr10 mt10" type="primary" onClick={() => viewLog(r)}>
            查看记录
          </Button>,
        ];

        // 不可编辑直接隐藏可操作按钮
        if (!canEditable) {
          return [operations[2], operations[3]];
        }

        // 服务订单删除物流拦截
        if (!['vip', 'self'].includes(r.supplierType)) {
          return [operations[0], operations[2], operations[3]];
        }
        return operations;
      },
    },
  ];
  return (
    <div>
      <ProTable
        columns={columns}
        request={params => searchList(params, 1)}
        rowKey={r => r.serviceNo}
        pagination={{
          pagesSize: 20,
        }}
        bordered
        actionRef={table}
        scroll={{ x: '100%', y: 400 }}
        search={{
          collapsed: false,
          collapseRender: () => null,
        }}
        toolBarRender={false}
      />
      <AuditModal visible={visible} onCancel={closeModal} formData={auditInfo} />
      <DetailTable visible={detailVisible} onCancel={closeModal} dataSource={detailInfo} />
      <ProofsModal visible={proofsVisible} onCancel={closeModal} data={proofsData} />
      <AppealDetail
        data={selectedRow}
        modalVisible={appealDetailModal}
        onCancel={closeModal}
      ></AppealDetail>
      <AfterLog visible={afterVisible} onCancel={closeModal} data={afterList} />
    </div>
  );
};
