import React, { useState, useRef } from 'react';
import { Button, notification, Popconfirm } from 'antd';
import ProTable from '@ant-design/pro-table';
import { searchList, shopCheck, orderDetail, trackInfo, getOpLog } from '../services';
import { getDetail } from '../../afterSale/appeal/services';
import { columnPassAudit } from '../data';
import RejectModal from '../components/rejectModal';
import DetailTable from '../components/detailTable';
import ProofsModal from '../components/proofsModal';
import LogisticsCom from '../../orderManage/pendingDeliveryOrder/components/LogisticsCom';
import AppealDetail from '../../afterSale/components/detail';
import AfterLog from '../components/AfterLog';

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 [serviceNoInfo, setServiceNoInfo] = useState({});
  const [LogisticsComList, setLogisticsComList] = useState({});
  const [LogisticsComModalVisible, handleComModalVisible] = useState(false);
  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);
    handleComModalVisible(false);
    setAppealDetailModal(false);
    setAfterVisible(false);
  };
  const reject = async ({ serviceNo }) => {
    setServiceNoInfo(serviceNo);
    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 refund = async ({ serviceNo }) => {
    const data = await shopCheck({
      serviceNo,
      auditResult: 1,
    });
    if (data.businessCode === '0000') {
      notification.success({ message: '操作成功' });
      closeModal(true);
    }
  };
  const viewLog = async r => {
    const data = await getOpLog(r.serviceNo);
    if (data?.data?.length) {
      setAfterList(data.data);
      setAfterVisible(true);
    }
  };
  const handleCom = async ({ expressCompanyCode, deliveryNo }) => {
    const tempObj = {
      detailList: [],
      key: Date.now(),
    };
    const data = await trackInfo({ expressCompanyCode, logisticsNo: deliveryNo });
    if (!data) {
      notification.info({ message: '暂无物流信息' });
      return;
    }
    tempObj.expressCompanyName = data.logisticsName;
    tempObj.deliveryNo = data.logisticsBillNo;
    if (data.logisticsList?.length) {
      data.logisticsList.forEach(v => {
        tempObj.detailList = [...tempObj.detailList, ...v.detailList];
      });
    }
    handleComModalVisible(true);
    setLogisticsComList(tempObj);
  };
  const viewAppeal = async r => {
    const detailData = await getDetail({ appealNo: r.appealNo });
    setAppealDetailModal(true);
    setSelectedRow(detailData);
  };
  const columns = [
    ...columnPassAudit,
    {
      title: '售后凭证',
      dataIndex: 'proofs',
      hideInSearch: true,
      width: 120,
      order: 4,
      render: (_, r) => <a onClick={() => viewProofs(r.proofs)}>查看凭证</a>,
    },
    {
      title: '售后申诉',
      dataIndex: 'appealFlag',
      hideInSearch: true,
      width: 120,
      render: (appealFlag, r) => {
        if (appealFlag) {
          return <a onClick={() => viewAppeal(r)}>已申诉</a>;
        }
        return <div> 未申诉</div>;
      },
    },
    {
      title: '操作',
      hideInSearch: true,
      width: 300,
      dataIndex: 'action',
      fixed: 'right',
      render: (_, r) => {
        const operations = [
          <Popconfirm
            title="确定允许退款？"
            onConfirm={() => refund(r)}
            okText="确认"
            cancelText="取消"
            key="pop"
            disabled={!r.showRefund}
          >
            <Button key="link1" className="mr10 mt10" type="primary" disabled={!r.showRefund}>
              {r.showRefunded ? '已退款' : '允许退款'}
            </Button>
          </Popconfirm>,
          <Button
            key="link2"
            onClick={() => reject(r)}
            type="primary"
            className="mr10 mt10"
            disabled={!r.showRefuse}
          >
            驳回
          </Button>,
          <Button key="link3" onClick={() => viewDetail(r)} type="primary" className="mr10 mt10">
            订单详情
          </Button>,
          <Button
            key="link4"
            onClick={() => handleCom(r)}
            type="primary"
            className="mr10 mt10"
            disabled={!r.showLogistics}
          >
            查看物流
          </Button>,
          <Button className="mr10 mt10" type="primary" onClick={() => viewLog(r)}>
            查看记录
          </Button>,
        ];

        // 没权限返回详情、查看物流、查看记录
        if (!canEditable) {
          // 服务订单返回订单详情和查看记录
          if (!['vip', 'self'].includes(r.supplierType)) {
            return [operations[2], operations[4]];
          }
          return [operations[2], operations[3], operations[4]];
        }

        // 有权限 服务订单 不反返回物流
        if (!['vip', 'self'].includes(r.supplierType)) {
          return [operations[0], operations[1], operations[2], operations[4]];
        }
        // 有修改权限&&非服务订单 全部返回
        return operations;
      },
    },
  ];
  return (
    <div>
      <ProTable
        columns={columns}
        request={params => searchList(params, 2)}
        rowKey={r => r.serviceNo}
        pagination={{
          pagesSize: 20,
        }}
        bordered
        actionRef={table}
        scroll={{ x: '100%', y: 400 }}
        toolBarRender={false}
        search={{
          collapsed: false,
          collapseRender: () => null,
        }}
      />
      <RejectModal visible={visible} onCancel={closeModal} serviceNo={serviceNoInfo} />
      <DetailTable visible={detailVisible} onCancel={closeModal} dataSource={detailInfo} />
      <ProofsModal visible={proofsVisible} onCancel={closeModal} data={proofsData} />
      <LogisticsCom
        onSubmit={closeModal}
        onCancel={closeModal}
        modalVisible={LogisticsComModalVisible}
        value={LogisticsComList}
        key={LogisticsComList.key}
      />
      <AppealDetail
        data={selectedRow}
        modalVisible={appealDetailModal}
        onCancel={closeModal}
      ></AppealDetail>
      <AfterLog visible={afterVisible} onCancel={closeModal} data={afterList} />,
    </div>
  );
};
