import { Button, notification, Modal, Popover } from 'antd';
import React, { useState, useEffect, useRef } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { useLocation } from 'react-router-dom';
import ProTable from '@ant-design/pro-table';
import { FormInstance } from 'antd/lib/form';
import moment from 'moment';
import { connect } from 'dva';
import { PENDING_DELIVERY_ORDER, DELIVERY_ORDER } from '@/../config/permission.config';
import style from './index.less';
import LogisticsForm from './components/LogisticsForm';
import PopoverDom from './components/PreviewImage';
import LogisticsCom from './components/LogisticsCom';
import DelayDeliverGoods from './components/DelayDeliverGoods';
import GoodsRemark from '../components/GoodsRemark';

import MultiLogisticsModal from './components/MultiLogisticsModal';
import {
  queryToSend,
  queryExpress,
  getGoods,
  downOrder,
  apiQueryOrderInfo,
  apiDeliveriesTraceList,
} from './service';

const { confirm } = Modal;

const TableList = props => {
  const location = useLocation();
  const dateFormat = 'YYYY-MM-DD';
  const { permissions } = props;

  // 因待发货 和 已发货都使用当前组件，功能且相同，所以只要授权其中一个均可获得发货物流权限
  const canEditable =
    permissions[PENDING_DELIVERY_ORDER.EDITABLE] || permissions[DELIVERY_ORDER.EDITABLE];
  const [companys, setCompanys] = useState([]);
  const [LogisticsModalVisible, handleModalVisible] = useState(false);
  const [skuList, setSkuList] = useState([]);
  const [LogisticsData, setLogisticsData] = useState([{}]);
  const [ShowUpdateBtn] = useState([2, 5]);
  const [LogisticsComList, setLogisticsComList] = useState({});
  const [LogisticsComModalVisible, handleComModalVisible] = useState(false);
  const [startTime, setStartTime] = useState(moment().add(-1, 'months'));
  const [startTimeStr, setStartTimeStr] = useState(
    moment()
      .add(-1, 'months')
      .format(dateFormat),
  );

  const [endTime, setEndTime] = useState(moment());
  const [orderStatus, setorderStatus] = useState(1);
  const [orderNo, setOrderNo] = useState('');
  const [endTimeStr, setEndTimeStr] = useState(moment().format(dateFormat));

  const [visibleDelay, setVisibleDelay] = useState(false);
  const [delayOrderIDs, setDelayOrderIDs] = useState(0);

  // const startDisabledDate = current =>
  //   current && (endTime.diff(current, 'days') > 30 || endTime.diff(current, 'days') < 0);
  // const endDisabledDate = current =>
  //   current && (current.diff(startTime, 'days') > 30 || current.diff(startTime, 'days') < 0);

  const multiLogisticsModalRef = useRef();
  const actionRef = useRef();
  const ref = useRef(FormInstance);
  const handleCom = async (skuInfo, expressInfo) => {
    const tempObj = {
      expressCompanyCode: expressInfo?.expressCompanyCode ?? '',
      expressCompanyName: expressInfo.expressCompanyName ?? '',
      deliveryNo: expressInfo?.expressNo ?? '',
      detailList: [],
      key: Date.now(),
    };

    const res = await apiDeliveriesTraceList({
      expressCompanyCode: expressInfo.expressCompanyCode,
      expressNo: expressInfo.expressNo,
      orderNo: skuInfo.orderNo,
    });

    const data = res.data[0];
    console.log(data);
    if (!data) {
      notification.info({ message: '暂无物流信息' });
      return;
    }
    tempObj.expressCompanyName = data?.expressCompanyName || tempObj.expressCompanyName;
    tempObj.deliveryNo = data?.expressNo || tempObj.deliveryNo;
    if (data.traceList?.length) {
      data.traceList.forEach(v => {
        tempObj.detailList = [...tempObj.detailList, ...v.detailList];
      });
    }
    handleComModalVisible(true);
    setLogisticsComList(tempObj);
  };

  const onDelay = (id, state, content) => {
    if (state === 1) {
      confirm({
        title: '提示',
        content,
        cancelButtonProps: {
          style: {
            display: 'none',
          },
        },
      });
    } else {
      setDelayOrderIDs(id);
      setVisibleDelay(true);
    }
  };
  const onCancelDelay = e => {
    setVisibleDelay(false);
    if (e && actionRef.current) {
      actionRef.current.reload();
    }
  };

  const renderContent = (record, key) => {
    if (record.mchOrderSkuVoList) {
      return record?.mchOrderSkuVoList.map((item, index) => {
        const tableContentHeight = item?.expressList?.length || 1;

        return (
          <div
            // eslint-disable-next-line prefer-template
            style={{ height: tableContentHeight * 60 + 'px' }}
            className={[
              'tableContent',
              index < record?.mchOrderSkuVoList?.length - 1 ? 'border' : null,
            ].join(' ')}
            key={item.orderSkuId}
          >
            {key === 'skuName' ? <PopoverDom name={item[key]} url={item.imageUrl} /> : ''}
            {key === 'expressCompanyName' ? (
              <div className="expressList">
                {item.expressList?.map((info, idx) => (
                  <span
                    className={[
                      'subContent',
                      idx < item.expressList?.length - 1 ? 'border' : null,
                    ].join(' ')}
                  >
                    {info.expressCompanyName}
                  </span>
                ))}
              </div>
            ) : (
              ''
            )}

            {key === 'deliveryNo' ? (
              <div className="expressList">
                {item.expressList?.map((info, idx) => (
                  <a
                    onClick={() => {
                      handleCom(item, info);
                    }}
                    className={[
                      'subContent',
                      idx < item.expressList?.length - 1 ? 'border' : null,
                    ].join(' ')}
                  >
                    {info.expressNo}
                  </a>
                ))}
              </div>
            ) : (
              ''
            )}
            {item[key]}
          </div>
        );
      });
    }
    return '';
  };

  const PopoverNotice = noticeProps => {
    const { time, content } = noticeProps || {};
    return (
      <div className={style['popover-notice']}>
        {time}：{content}
      </div>
    );
  };

  const columns = [
    {
      title: '订单号',
      dataIndex: 'orderNo',
      key: 'orderNo',
      order: 6,
      width: 250,
      fixed: 'left',
      formItemProps: {
        value: orderNo,
        onChange(e) {
          console.log(e.target.value);
          setOrderNo(e.target.value);
        },
      },
      render: (_, record) => {
        const { urgeDeliverGoodsList } = record;
        const content = () =>
          urgeDeliverGoodsList?.map(item => (
            <PopoverNotice time={item?.time} content={item?.content} />
          ));
        return (
          <div className={style['urge-box']}>
            {_}
            {urgeDeliverGoodsList ? (
              <Popover placement="top" title="催发货" content={<>{content()}</>} trigger="hover">
                <span className={style.urge}>催单</span>
              </Popover>
            ) : (
              ''
            )}
          </div>
        );
      },
    },
    {
      title: '订单提醒',
      dataIndex: 'orderNotice',
      key: 'orderNotice',
      width: 150,
      render: (_, record) => {
        const { updateAddressList, platformRemark, platformRemarkList } = record;
        // let addressData;
        // if (updateAddressList) {
        //   addressData = updateAddressList.pop();
        // }
        const content = () => (
          <div className={style['popover-notice-box']}>
            {updateAddressList?.map(item => (
              <PopoverNotice time={item?.time} content={item?.content} />
            ))}
          </div>
        );
        return (
          <div className={style['notice-btn']}>
            {updateAddressList ? (
              <Popover placement="top" title="收货地址变更" content={content()} trigger="hover">
                <Button block type="primary">
                  收货地址变更
                </Button>
              </Popover>
            ) : (
              ''
            )}
            {platformRemarkList && platformRemarkList.length ? (
              <Popover
                placement="top"
                title="平台备注"
                content={<GoodsRemark dataSource={platformRemarkList} />}
                trigger="hover"
              >
                <Button block type="warning">
                  平台备注
                </Button>
              </Popover>
            ) : (
              ''
            )}
          </div>
        );
      },
    },
    {
      title: '商品名称',
      dataIndex: 'skuName',
      key: 'skuName',
      order: 6,
      hideInTable: true,
    },
    {
      title: '超时发货',
      dataIndex: 'orderStatus',
      key: 'orderStatus',
      hideInTable: true,
      formItemProps: {
        // eslint-disable-next-line no-nested-ternary
        value: orderStatus ? (orderStatus === 1 ? '是' : '否') : null,
        onChange(status) {
          setorderStatus(Number(status));
        },
      },
      valueEnum: {
        1: '是',
        2: '否',
      },
    },
    {
      title: '交易时间',
      dataIndex: 'orderTime',
      key: 'orderTime',
      hideInSearch: true,
      width: 200,
    },
    {
      title: '商品名称',
      dataIndex: 'skuName',
      key: 'skuName',
      width: 400,
      className: 'colStyle',
      hideInSearch: true,
      render: (_, record) => renderContent(record, 'skuName'),
    },
    {
      title: '商品规格',
      dataIndex: 'skuAttr',
      key: 'skuAttr',
      width: 200,
      className: 'colStyle',
      hideInSearch: true,
      render: (_, record) => renderContent(record, 'skuAttr'),
    },
    {
      title: '商品数量',
      dataIndex: 'count',
      key: 'count',
      width: 100,
      className: 'colStyle',
      hideInSearch: true,
      render: (_, record) => renderContent(record, 'count'),
    },
    {
      title: '商品自编码',
      dataIndex: 'thirdSpuNo',
      key: 'thirdSpuNo',
      width: 150,
      hideInSearch: true,
      className: 'colStyle',
      render: (_, record) => renderContent(record, 'thirdSpuNo'),
    },
    {
      title: '收货人手机',
      dataIndex: 'receiverPhone',
      key: 'receiverPhone',
      order: 4,
      width: 150,
    },
    {
      title: '收货人姓名',
      dataIndex: 'receiverName',
      key: 'receiverName',
      order: 3,
      width: 120,
    },
    {
      title: '收货地址',
      dataIndex: 'fullAddress',
      key: 'fullAddress',
      hideInSearch: true,
      width: 350,
    },
    {
      title: '物流公司',
      dataIndex: 'expressCompanyName',
      key: 'expressCompanyName',
      width: 120,
      className: 'colStyle',
      hideInSearch: true,
      hideInTable: props.type !== 2,
      render: (_, record) => renderContent(record, 'expressCompanyName'),
    },
    {
      title: '物流单号',
      dataIndex: 'deliveryNo',
      key: 'deliveryNo',
      width: 210,
      className: 'colStyle',
      hideInSearch: true,
      hideInTable: props.type !== 2,
      render: (_, record) => renderContent(record, 'deliveryNo'),
    },
    // {
    //   title: '物流信息',
    //   dataIndex: 'action',
    //   key: 'action',
    //   width: 150,
    //   hideInSearch: true,
    //   hideInTable: props.type !== 2,
    //   className: 'colStyle',
    //   render: (_, record) => renderContent(record, 'action'),
    // },
    {
      title: '订单状态',
      dataIndex: 'orderStatusDesc',
      key: 'orderStatusDesc',
      width: 120,
      hideInSearch: true,
    },
    {
      title: '订单开始时间',
      dataIndex: 'startTime',
      key: 'startTime',
      valueType: 'date',
      hideInTable: true,
      formItemProps: {
        value: startTime,
        onChange(time, timeString) {
          setStartTime(time);
          setStartTimeStr(timeString);
        },
        // disabledDate: startDisabledDate,
        allowClear: false,
      },
    },
    {
      title: '订单结束时间',
      dataIndex: 'endTime',
      key: 'endTime',
      valueType: 'date',
      hideInTable: true,
      formItemProps: {
        value: endTime,
        onChange(time, timeString) {
          setEndTime(time);
          setEndTimeStr(timeString);
        },
        // disabledDate: endDisabledDate,
        allowClear: false,
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      key: 'option',
      valueType: 'option',
      width: 150,
      fixed: 'right',
      render: (_, record) => (
        <React.Fragment>
          {canEditable && ShowUpdateBtn.includes(record?.skuSource?.value) ? null : (
            <Button
              type="primary"
              style={{
                marginBottom: '10px',
              }}
              onClick={async () => {
                const res = await apiQueryOrderInfo({
                  orderNo: record.orderNo,
                });

                multiLogisticsModalRef.current.open(
                  {
                    ...record,
                    packageList: res?.data?.packageList || [],
                  },
                  actionRef,
                );
              }}
            >
              {props.type === 2 ? '更新物流信息' : '填写物流信息'}
            </Button>
          )}
          {canEditable && props.type !== 2 && (
            <Button
              type="primary"
              className={+record.delayStatus === 1 ? style.btnWarning : ''}
              onClick={() => onDelay(record.orderId, +record.delayStatus, record.delayRemark)}
            >
              {+record.delayStatus === 1 ? '异常订单已报备' : '异常订单报备'}
            </Button>
          )}
        </React.Fragment>
      ),
    },
  ];
  const reload = () => {
    handleModalVisible(false);
    if (actionRef.current) {
      actionRef.current.reload();
    }
  };

  useEffect(() => {
    const getCompanys = async () => {
      const data = await queryExpress();
      setCompanys(data);
    };
    getCompanys();
    if (props.location?.state) {
      const { status } = props.location?.state;
      setorderStatus(status);
    } else {
      setorderStatus('');
    }
  }, []);

  // 监听路由query参数变化重新发起请求
  useEffect(() => {
    if (location?.query) {
      const { orderNo: orderNumber } = location?.query;
      if (orderNumber) {
        setorderStatus('');
      }
      setOrderNo(orderNumber);
      if (ref.current) {
        ref.current.resetFields();
        ref.current.submit();
      }
    } else {
      setOrderNo('');
    }
  }, [location]);

  const queryToSendFn = params => {
    const transformedParam = {
      ...params,
      logisticsStatus: props.type || 1,
      pageNo: params.current,
      pageSize: params.pageSize || 20,
      timeOutType: orderStatus || '',
      orderNo,
    };
    return queryToSend(transformedParam);
  };
  const searchRender = ({ searchText, resetText }, { form }) => [
    <Button
      key="search"
      type="primary"
      style={{ marginRight: '10px' }}
      onClick={() => {
        // eslint-disable-next-line no-unused-expressions
        form?.submit();
      }}
    >
      {searchText}
    </Button>,
    <Button
      key="rest"
      style={{ marginRight: '10px' }}
      onClick={() => {
        // eslint-disable-next-line no-unused-expressions
        form?.resetFields();
        setorderStatus('');
        setOrderNo('');
        // eslint-disable-next-line no-unused-expressions
        form?.submit();
      }}
    >
      {resetText}
    </Button>,
  ];

  const toolBarRenderFn = () => [
    <Button
      type="primary"
      onClick={() => {
        if (ref.current) {
          const obj = {
            ...ref.current.getFieldsValue(),
            orderNo,
            logisticsStatus: props.type || 1,
          };
          obj.startTime = startTimeStr;
          obj.endTime = endTimeStr;
          downOrder(obj);
        }
      }}
    >
      导出数据
    </Button>,
  ];
  return (
    <PageHeaderWrapper>
      <ProTable
        className={style.protable}
        actionRef={actionRef}
        request={params =>
          queryToSendFn({ ...params, startTime: startTimeStr, endTime: endTimeStr })
        }
        columns={columns}
        rowKey={r => r.orderNo}
        formRef={ref}
        toolBarRender={toolBarRenderFn}
        search={{
          collapsed: false,
          optionRender: searchRender,
        }}
        bordered
        scroll={{ x: 1500 }}
      />
      <LogisticsForm
        onSubmit={reload}
        skuList={skuList}
        company={companys}
        onCancel={() => handleModalVisible(false)}
        modalVisible={LogisticsModalVisible}
        value={LogisticsData}
      />
      <LogisticsCom
        onSubmit={reload}
        onCancel={() => handleComModalVisible(false)}
        modalVisible={LogisticsComModalVisible}
        value={LogisticsComList}
        key={LogisticsComList.key}
      />
      <DelayDeliverGoods
        visible={visibleDelay}
        orderId={delayOrderIDs}
        onCancel={e => onCancelDelay(e)}
      />

      <MultiLogisticsModal companys={companys} ref={multiLogisticsModalRef} />
    </PageHeaderWrapper>
  );
};

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