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: $t('no.credentials.for.this.order') });
      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: $t('reminder'),
      okText: $t('confirm.interception'),
      cancelText: $t('cancel.interception'),
      content: (
        <div>{$t('intercept.logistics.within.48.hours.before.system.confirms')}<span className={styles.redTipBold}>{$t('auto.approve')}</span>{$t('refund')}</div>
      ),
      async onOk() {
        const data = await logisticsIntercept({ serviceNo: r.serviceNo });
        if (data.businessCode === '0000') {
          notification.success({ message: $t('block.success') });
          table.current.reload();
        } else {
          notification.error({ message: data.msg || $t('block.failed') });
        }
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };
  const columns = [
    {
      title: $t('review.countdown'),
      dataIndex: 'serviceTime',
      key: 'serviceTime',
      hideInSearch: true,
      width: 150,
      render: (val, record) => {
        const serviceTime = moment(record.approvalEndTime).valueOf();
        return (
          <Countdown
            format={$t('hhmmss')}
            value={serviceTime}
            valueStyle={{ color: 'red', fontSize: '14px' }}
          />
        );
      },
    },
    {
      title: $t('aftersales.status'),
      dataIndex: 'serviceStatus',
      hideInSearch: true,
      width: 120,
    },
    ...columnSticData,
    {
      title: $t('aftersales.proof'),
      dataIndex: 'proofs',
      hideInSearch: true,
      width: 100,
      render: (val, r) => <a onClick={() => viewProofs(r.proofs)}>{$t('view.proof')}</a>,
    },
    {
      title: $t('aftersales.appeal'),
      dataIndex: 'appealFlag',
      valueEnum: appealType,
      hideInSearch: true,
      width: 120,
      render: (appealFlag, r) => {
        if (appealFlag) {
          return <a onClick={() => viewAppeal(r)}>{$t('appealed')}</a>;
        }
        return <div>{$t('not.appealed')}</div>;
      },
    },
    {
      title: $t('actions'),
      hideInSearch: true,
      dataIndex: 'action',
      width: 250,
      fixed: 'right',
      render: (val, r) => {
        const operations = [
          <Button key="link1" onClick={() => openAudit(r)} className="mr10 mt10" type="primary">{$t('review')}</Button>,
          <Button
            disabled={r.serviceType !== 1 || (r.serviceType === 1 && r.intercept)}
            onClick={() => openLogistics(r)}
            className="mr10 mt10"
            type="primary"
          >{$t('logistics.interception')}</Button>,
          <Button className="mr10 mt10" key="link" onClick={() => viewDetail(r)} type="primary">{$t('order.details')}</Button>,
          <Button className="mr10 mt10" type="primary" onClick={() => viewLog(r)}>{$t('view.records')}</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>
  );
};
