/* eslint-disable no-mixed-operators */
/* eslint-disable radix */
import React, { useState, useRef, useEffect } from 'react';
import { Button, notification } from 'antd';
import ProTable from '@ant-design/pro-table';
import _ from 'lodash';
// import { searchList, auditInfoApi, orderDetail } from './service';
import moment from 'moment';
import { searchList, orderDetail } from './service';
import { column } from './data';
import AuditModal from './components/auditModal';
import DetailTable from './components/detailTable';
import { dateDiff } from './common';

export default props => {
  const { canEditable } = props;
  const table = useRef();
  const ref = useRef();
  const [visible, setVisible] = useState(false);
  const [detailVisible, setDetailVisible] = useState(false);
  const [detailInfo, setDetailInfo] = useState([]);
  const [auditInfo, setAuditInfo] = useState({});
  const [timeString, setTimeString] = useState({});
  const [time, setTime] = useState({});

  const query = async (params, type) => {
    if (params.orderId) {
      params.orderId = `${params.orderId}`.replace(/\s/g, '');
      if (Number.isNaN(+params.orderId)) {
        notification.warning({
          message: '输入的订单Id只能为数字格式',
        });
        return false;
      }
    }
    if (params.receiverPhone) {
      const reg = /^1[3456789]\d{9}$/;
      if (!reg.test(params.receiverPhone)) {
        notification.warning({
          message: '您输入的手机号有误，请重新输入！',
        });
        return false;
      }
    }
    if (params.orderTime && params.orderTime.length) {
      const startTime = params.orderTime[0];
      const endTime = params.orderTime[1];
      if (dateDiff(startTime, endTime)) {
        notification.warning({
          message: '您输入的订单创建时间超过3个月啦！',
        });
        return false;
      }
    }
    if (params.applyTime && params.applyTime.length) {
      const startTime = params.applyTime[0];
      const endTime = params.applyTime[1];
      if (dateDiff(startTime, endTime)) {
        notification.warning({
          message: '您输入的订单取消提交时间超过3个月啦！',
        });
        return false;
      }
    }
    const tempParams = {
      ...params,
      applyTimeStartAt: params.applyTime?.[0],
      applyTimeEndAt: params.applyTime?.[1],
      orderTimeStartAt: params.orderTime?.[0],
      orderTimeEndAt: params.orderTime?.[1],
      auditStatus: 1,
    };

    return searchList(tempParams, type);
  };

  const viewDetail = async ({ serviceNo }) => {
    const data = await orderDetail({ serviceNo });
    setDetailInfo(data || []);
    setDetailVisible(true);
  };
  const renderContent = (record, index, action) => {
    if (!time[record.orderId]) {
      const applyTime = moment(record.applyTime).valueOf() + 24 * 3600 * 1000;
      const nowTime = moment(record.nowTime).valueOf();
      let timeNumber = (applyTime - nowTime) / 1000;
      time[record.orderId] = setInterval(() => {
        if (timeNumber > 0) {
          timeNumber -= 1;
          const hours = parseInt((timeNumber / 3600) % 24)
            .toString()
            .padStart(2, '0');
          const minutes = parseInt((timeNumber / 60) % 60)
            .toString()
            .padStart(2, '0');
          const seconds = parseInt(timeNumber % 60)
            .toString()
            .padStart(2, '0');
          const str = `${hours}时${minutes}分${seconds}秒`;
          timeString[record.orderId] = str;
          const strings = _.cloneDeep(timeString);
          setTimeString(strings);
        } else {
          clearInterval(time[record.orderId]);
          timeString[record.orderId] = '0时0分0秒';
          const strings = _.cloneDeep(timeString);
          setTimeString(strings);
          // eslint-disable-next-line no-unused-expressions
          table.current?.reload?.();
        }
      }, 1000);
    }
  };

  const closeModal = isReload => {
    if (isReload === true) {
      // eslint-disable-next-line no-unused-expressions
      table.current?.reload?.();
    }
    setVisible(false);
    setDetailVisible(false);
  };
  const openAudit = async ({ serviceNo }) => {
    // const data = await auditInfoApi({ serviceNo });
    setAuditInfo({ serviceNo });
    setVisible(true);
  };

  const columns = [
    {
      title: '审核倒计时',
      dataIndex: 'examine',
      key: 'examine',
      hideInSearch: true,
      width: 200,
      // eslint-disable-next-line no-shadow
      render: (_, record, index, action) => [
        <span style={{ color: 'red' }}>
          {renderContent(record, index, action)}
          {timeString[record.orderId]}
        </span>,
      ],
    },
    ...column,
    {
      title: '操作',
      hideInSearch: true,
      dataIndex: 'action',
      width: 250,
      fixed: 'right',
      // eslint-disable-next-line no-shadow
      render: (_, r) => {
        const examine = (
          <Button key="link1" onClick={() => openAudit(r)} className="mr10" type="primary">
            审核
          </Button>
        );
        const detail = (
          <Button key="link" onClick={() => viewDetail(r)} type="primary">
            订单详情
          </Button>
        );

        if (!canEditable) {
          return [detail];
        }
        return [examine, detail];
      },
    },
  ];
  return (
    <div>
      <ProTable
        columns={columns}
        request={params => query(params, 1)}
        rowKey={r => r.orderId + r.serviceNo}
        pagination={{
          pagesSize: 20,
        }}
        bordered
        actionRef={table}
        formRef={ref}
        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} />
    </div>
  );
};
