import React, { useRef, useState, useEffect } from 'react';
import { Tabs, notification, Form, Modal } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { AFTER_SALE_ORDER } from '@/../config/permission.config';
import { connect } from 'umi';
import { FormSearch } from '@/components/FormSearch';
import moment from 'moment';
import { useLocation } from 'react-router-dom';
import AuditModal from './components/auditModal';
import DetailTable from './components/detailTable';
import ProofsModal from './components/proofsModal';
// import AppealDetail from '@/pages/afterSale/components/detail';
import AfterLog from './components/AfterLog';
import RejectModal from './components/rejectModal';
import LogisticsCom from '../orderManage/pendingDeliveryOrder/components/LogisticsCom';
import CancelAuditModal from './components/CancelAuditModal';
import CancelDetailTable from './components/CancelDetailTable';
import LogisticsRecordModal from './components/LogisticsRecordModal';

import { getColumns, getFormConfig, TAB_MAPPING_DATA } from './data.js';
import { getDetail } from '@/pages/afterSale/appeal/services';
import { getClientInfo } from '@/utils/utils';
import {
  searchList,
  logisticsIntercept,
  orderDetail,
  getOpLog,
  auditInfoApi,
  trackInfo,
  shopCheck,
  getAfterPendingNum,
  cancelOrderDetail,
} from './services';

import styles from './index.less';

const { TabPane } = Tabs;
const { confirm } = Modal;

const AfterSale = props => {
  const { permissions } = props;
  const canEditable = permissions[AFTER_SALE_ORDER.EDITABLE];
  const location = useLocation();

  const actionRef = useRef();
  const formRef = useRef();
  const logisticsRecordModalRef = useRef();
  const [tableParams, setTableParams] = useState({});
  const [currentTab, setCurrentTab] = useState('');
  // const [appealDetailModal, setAppealDetailModal] = useState(false);
  // const [selectedRow, setSelectedRow] = useState({});
  const [tabInfoData, setTabInfoData] = useState({
    cancelOrderPendingAuditNum: 0,
    refundPendingAuditNum: 0,
    returnPendingAuditNum: 0,
    returnWaitAuditNum: 0,
    afterSalseDoneNum: 0,
  });
  const scrollYRef = useRef();
  const [tableScrollY, setTableScrollY] = useState(0);

  // 申诉
  const [proofsData, setProofsData] = useState([]);
  const [proofsVisible, setProofsVisible] = useState(false);

  // 详情
  const [detailVisible, setDetailVisible] = useState(false);
  const [detailInfo, setDetailInfo] = useState([]);
  //  售后操作记录
  const [afterVisible, setAfterVisible] = useState(false);
  const [afterList, setAfterList] = useState([]);

  // 审核
  const [visible, setVisible] = useState(false);
  const [auditInfo, setAuditInfo] = useState({});

  // 查看物流
  const [LogisticsComList, setLogisticsComList] = useState({});
  const [logisticsComModalVisible, setLogisticsComModalVisible] = useState(false);

  // 驳回
  const [serviceNoInfo, setServiceNoInfo] = useState({});
  const [rejectVisible, setRejectVisible] = useState(false);

  // 取消订单审核
  const [cancelVisible, setCancelVisible] = useState(false);
  const [cancelAuditInfo, setCancelAuditInfo] = useState({});

  // 取消订单审核详情
  const [cancelDetailVisible, setCancelDetailVisible] = useState(false);
  const [cancelDetailInfo, setCancelDetailInfo] = useState({});

  // 关闭modal
  const closeModal = isReload => {
    if (isReload === true) {
      // eslint-disable-next-line no-unused-expressions
      actionRef.current?.reload?.();
    }
    setVisible(false);
    setDetailVisible(false);
    setProofsVisible(false);
    // setAppealDetailModal(false);
    setAfterVisible(false);
    setLogisticsComModalVisible(false);
    setCancelVisible(false);
    setCancelDetailVisible(false);
    setRejectVisible(false);
  };

  // 查看申诉详情
  // const viewAppeal = async r => {
  //   const detailData = await getDetail({ appealNo: r.appealNo });
  //   setAppealDetailModal(true);
  //   setSelectedRow(detailData);
  // };

  // 查看凭证
  const viewProofs = proofs => {
    if (!proofs) {
      notification.warning({ message: '该订单没有凭证' });
      return;
    }
    const list = proofs.replace(/(\uff1b|\uff0c|\u003b)/g, ',').split(',');
    setProofsData(list);
    setProofsVisible(true);
  };

  // 审核
  const openAudit = async ({ serviceNo, serviceType, orderNo, skuNo }) => {
    const data = await auditInfoApi({ serviceNo });
    setAuditInfo({ ...data?.data, serviceNo, serviceType, orderNo, skuNo });
    setVisible(true);
  };

  // 查看物流
  const handleCom = async record => {
    console.log('record', record);
    const { expressCompanyCode, deliveryNo: expressNo } = record;
    logisticsRecordModalRef.current.open({ expressCompanyCode, expressNo }, 'single');
    // 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];
    //   });
    // }
    // setLogisticsComModalVisible(true);
    // setLogisticsComList(tempObj);
  };

  // 物流拦截
  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: '拦截成功' });
          actionRef.current.reload();
        } else {
          notification.error({ message: data.msg || '拦截失败' });
        }
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };

  //  查看
  const viewDetail = async ({ serviceNo }) => {
    const res = await orderDetail({ serviceNo });
    const data = res.data || [];
    setDetailInfo(data);
    setDetailVisible(true);
  };

  // 查看售后操作日志
  const viewLog = async r => {
    const data = await getOpLog(r.serviceNo);
    if (data?.data?.length) {
      setAfterList(data.data);
      setAfterVisible(true);
    }
  };
  // 已退款/允许退款
  const refund = async ({ serviceNo }) => {
    const data = await shopCheck({
      serviceNo,
      auditResult: 1,
    });
    if (data.businessCode === '0000') {
      notification.success({ message: '操作成功' });
      closeModal(true);
    }
  };

  // 驳回
  const reject = async ({ serviceNo }) => {
    setServiceNoInfo(serviceNo);
    setRejectVisible(true);
  };

  // 取消订单审核
  const openCancelAudit = async ({ serviceNo }) => {
    // const data = await auditInfoApi({ serviceNo });
    setCancelAuditInfo({ serviceNo });
    setCancelVisible(true);
  };

  //  取消订单审核详情
  const viewCancelDetail = async ({ serviceNo }) => {
    const data = await cancelOrderDetail({ serviceNo });
    setCancelDetailInfo(data || []);
    setCancelDetailVisible(true);
  };

  const [form] = Form.useForm();
  const formConfig = getFormConfig({
    actionRef,
    tableParams,
    setTableParams,
    setCurrentTab,
  });

  const afterTime = [moment().subtract(3, 'month'), moment()];
  const FormSearchProps = {
    form,
    initialValues: {
      afterTime,
    },
    formOptions: {},
    ...formConfig,
  };

  // tab选项框回调
  const tabChange = tabIndex => {
    setCurrentTab(tabIndex);
    const { type, dealStatus } = TAB_MAPPING_DATA[tabIndex];

    form.resetFields();
    // 清空页码
    actionRef.current.reloadAndRest();
    form.setFieldsValue({
      ...tableParams,
      dealStatus,
      type,
    });
    setTableParams({ ...tableParams, dealStatus, type });
  };

  // 监听路由query参数变化重新发起请求
  useEffect(() => {
    if (location?.query) {
      const { orderNo: orderNumber, tab } = location?.query;

      if (orderNumber) {
        tabChange('');
      }
      const params = {
        orderNo: orderNumber,
        dealStatus: null,
        serviceNo: null,
        type: null,
        receiverPhone: null,
        receiverName: null,
      };
      form.setFieldsValue(params);
      setTableParams(params);

      if (tab) {
        tabChange(tab);
      }

      if (actionRef.current) {
        actionRef.current.reload();
      }
    }
  }, [location]);

  // 动态计算表格滚动区域高度
  const clientInfo = getClientInfo();
  const calculationLayoutHeight = e => {
    const otherHeight = typeof e === 'number' ? e : 330;
    const h = clientInfo.height - (scrollYRef?.current?.offsetTop || 0) - otherHeight;
    setTableScrollY(h < 500 ? '500px' : h);
  };

  useEffect(() => {
    calculationLayoutHeight(330);
  }, []);

  window.removeEventListener('resize', calculationLayoutHeight);
  window.addEventListener('resize', calculationLayoutHeight);

  const columns = getColumns({
    openAudit,
    // viewAppeal,
    viewProofs,
    openLogistics,
    viewDetail,
    viewLog,
    handleCom,
    refund,
    reject,
    canEditable,
    openCancelAudit,
    viewCancelDetail,
    tableParams,
  });

  // 表格属性
  const tableProps = {
    columns,
    params: tableParams,
    bordered: true,
    scroll: { x: '100%', y: tableScrollY },
    rowKey: r => r.serviceNo,
    request: async params => {
      console.log(params);
      const [start, end] = params.afterTime || afterTime;
      const { current: pageNo, pageSize } = params;
      const startDate = start ? moment(start).format('YYYY-MM-DD') : '';
      const endDate = end ? moment(end).format('YYYY-MM-DD') : '';
      const requestParams = {
        pageNo,
        pageSize,
        ...params,
        startDate,
        endDate,
      };
      delete requestParams.afterTime;
      delete requestParams.current;
      const countRes = await getAfterPendingNum({
        startDate,
        endDate,
      });
      const res = await searchList(requestParams);
      const { records = [], total } = res.data;

      if (countRes.code === '0000') {
        setTabInfoData(countRes.data);
      }
      return {
        data: records,
        total,
      };
    },
    toolBarRender: null,
  };

  const TabCountElement = ({ count, text }) => (
    <span>
      {text}
      <span className="count">{count}</span>
    </span>
  );

  return (
    <PageHeaderWrapper>
      <FormSearch {...FormSearchProps} />
      <div className={styles['tab-box']}>
        <Tabs
          activeKey={currentTab}
          onChange={tabChange}
          size="large"
          tabBarStyle={{ padding: '0 30px 0 15px', border: 'none' }}
        >
          <TabPane key="" tab="全部"></TabPane>
          <TabPane
            key="1"
            tab={
              <TabCountElement
                text="仅退款（未发货）待审核"
                count={tabInfoData.cancelOrderPendingAuditNum}
              />
            }
          />
          <TabPane
            key="2"
            tab={<TabCountElement text="仅退款待审核" count={tabInfoData.refundPendingAuditNum} />}
          />
          <TabPane
            key="3"
            tab={
              <TabCountElement text="退货退款待审核" count={tabInfoData.returnPendingAuditNum} />
            }
          />
          <TabPane
            key="4"
            tab={<TabCountElement text="退货入库待审核" count={tabInfoData.returnWaitAuditNum} />}
          />
          <TabPane
            key="5"
            tab={<TabCountElement text="已完成" count={tabInfoData.afterSalseDoneNum} />}
          />
        </Tabs>
      </div>
      <div ref={scrollYRef}></div>
      <ProTable
        {...tableProps}
        actionRef={actionRef}
        formRef={formRef}
        search={false}
        // toolBarRender={false}
      />

      <AuditModal visible={visible} onCancel={closeModal} formData={auditInfo} />
      <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} />
      <RejectModal visible={rejectVisible} onCancel={closeModal} serviceNo={serviceNoInfo} />

      <CancelAuditModal visible={cancelVisible} onCancel={closeModal} formData={cancelAuditInfo} />
      <CancelDetailTable
        visible={cancelDetailVisible}
        onCancel={closeModal}
        dataSource={cancelDetailInfo}
      />

      <LogisticsRecordModal ref={logisticsRecordModalRef} />
    </PageHeaderWrapper>
  );
};

export default connect(({ menu }) => ({
  permissions: menu.permissions,
}))(AfterSale);
