import { Form, Tabs, Input, Button, Pagination, notification } from 'antd';
import React, { useState, useEffect, useRef } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { connect } from 'dva';
import { QUERY_ORDER } from '@/../config/permission.config';
import { values } from 'lodash';
import style from './index.less';
import { CustomTable } from './components/CustomTable/index';
import { FormSearch, SEARCH_TYPE } from './components/FormSearch/index';

import MultiLogisticsModal from '../pendingDeliveryOrder/components/MultiLogisticsModal';
import LogisticsCom from '../pendingDeliveryOrder/components/LogisticsCom';
import DetailModal from './components/DetailModal/index';

import { queryOrderList, getGoods, queryExpress, queryToSend } from './service';
import { apiQueryOrderInfo, apiDeliveriesTraceList } from '../pendingDeliveryOrder/service';
import { ORDER_SEARCH_TYPE, ORDER_TYPE, ORDER_STATUS } from './const';

const { TabPane } = Tabs;

const OrderList = props => {
  const { permissions } = props;
  const canEditable = permissions[QUERY_ORDER.EDITABLE];
  const [loading, setLoading] = useState(false);
  const detailModalRef = useRef();
  const multiLogisticsModalRef = useRef();

  /** @module 发货弹框 */
  // 物流公司数据
  const [companys, setCompanys] = useState([]);

  /** @module 查看物流记录 */
  const [LogisticsComList, setLogisticsComList] = useState({});
  const [LogisticsComModalVisible, handleComModalVisible] = useState(false);

  /**  @module 表格区域 */
  const [tableData, setTableData] = useState([]);
  const [dataTotal, setDataTotal] = useState(10);
  const [pagination, setPagination] = useState({
    pageSize: 20,
    pageNo: 1,
  });

  /**  @module 搜索区域 */
  const [form] = Form.useForm();

  /**  @module 状态切换区域 */
  const [currentOrderStatus, setCurrentOrderStatus] = useState('');

  // 获取列表数据
  const getOrderList = () => {
    const {
      orderSearch = 'orderNo',
      orderSearchValue = '',
      orderTime = [],
      skuName = '',
      productType = '',
      orderStatus = '',
    } = form.getFieldValue();
    //  筛选同步订单状态tabs
    const startTime = orderTime[0] ? orderTime[0].format('YYYY-MM-DD') : '';
    const endTime = orderTime[1] ? orderTime[1].format('YYYY-MM-DD') : '';
    const searchParams = {
      [orderSearch]: orderSearchValue,
      startTime,
      endTime,
      skuName,
      productType,
      orderStatus,
      ...pagination,
    };
    setLoading(true);
    queryOrderList(searchParams).then(res => {
      setLoading(false);

      const { total, records } = res.data;
      setDataTotal(total);
      setTableData(records);
    });
  };

  // 打开详情弹框
  const openDetailModal = record => {
    detailModalRef.current.open(record);
  };

  // 切换订单状态- 同步select和tabs
  function orderStatusChange(value) {
    setCurrentOrderStatus(String(value));
    form.setFieldsValue({
      orderStatus: Number(value) || '',
    });

    setPagination({
      ...pagination,
      pageNo: 1,
    });
  }

  // 获取物流记录信息
  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 reload = () => {
    getOrderList();
  };

  const actionRef = {
    current: {
      reload,
    },
  };

  // 获取物流公司列表
  const getCompanys = async () => {
    const res = await queryExpress();
    setCompanys(res);
  };

  // 分页操作
  const onPageChange = (page, size) => {
    const current = pagination.pageSize !== size ? 1 : page;
    setPagination({
      pageNo: current,
      pageSize: size,
    });
  };

  useEffect(() => {
    getCompanys();
  }, []);

  useEffect(() => {
    getOrderList();
  }, [pagination]);

  const baseStyle = {
    style: {
      // width: '250px',
    },
  };
  const FormSearchProps = {
    // width: '1200px',
    form,
    initialValues: {
      orderSearch: 'orderNo',
      orderStatus: '',
      productType: '',
    },
    formOptions: {},
    formConfig: [
      {
        type: SEARCH_TYPE.SELECT,
        label: '订单搜索',
        bindKey: 'orderSearch',
        column: 5,
        options: ORDER_SEARCH_TYPE,
        originOptions: {
          placeholder: '请选择',
          ...baseStyle,
        },
        afterRender: () => <Input style={{ width: '100%' }} type="text"></Input>,
        afterOptions: {
          bindKey: 'orderSearchValue',
        },
      },
      {
        type: SEARCH_TYPE.RANGE_PICKER,
        label: '下单时间',
        column: 5,
        bindKey: 'orderTime',
        originOptions: {
          placeholder: ['请选择', '请选择'],
          ...baseStyle,
        },
      },
      {
        type: SEARCH_TYPE.INPUT,
        label: '商品名称',
        column: 5,
        bindKey: 'skuName',
        originOptions: {
          placeholder: '请输入',
          ...baseStyle,
        },
      },
      {
        // 1-普通商品订单 2-虚拟商品订单 3-电子卡券 4-服务商品
        type: SEARCH_TYPE.SELECT,
        label: '订单类型',
        column: 5,
        bindKey: 'productType',
        options: ORDER_TYPE,
        originOptions: {
          placeholder: '请选择',
          ...baseStyle,
        },
      },
      {
        type: SEARCH_TYPE.SELECT,
        label: '订单状态',
        column: 5,
        bindKey: 'orderStatus',
        options: ORDER_STATUS,
        originOptions: {
          placeholder: '请选择',
          ...baseStyle,
        },
      },
    ],
    btnConfig: [
      {
        label: '筛选',
        clickType: 'submit',
        onClick: () => {
          const { orderStatus } = form.getFieldValue();
          orderStatusChange(orderStatus);
        },
      },
      {
        label: '重置',
        type: '',
        clickType: 'reset',
        onClick: () => {
          orderStatusChange('');
        },
      },
    ],
  };

  const columns = [
    {
      title: '商品',
      dataIndex: 'spuName',
      align: 'left',
      width: 350,
      render: ({ value, subRecord }) => {
        const { primaryImage, skuSpec, spuId } = subRecord;
        return (
          <div className={style['sku-info']}>
            <img src={primaryImage} width="50px" height="50px" alt="" />
            <div className={style['sku-info__box']}>
              <p className={style['sku-info__box--name']}>{value}</p>
              <p className={style['sku-info__box--spec']}>规格：{skuSpec}</p>
              <p className={style['sku-info__box--id']}>商品id: {spuId}</p>
            </div>
          </div>
        );
      },
    },
    {
      title: '单位（元）/数量',
      dataIndex: 'supplyPrice',
      width: 150,
      render: ({ value, subRecord }) => {
        const { count } = subRecord;
        return `${value}/${count}`;
      },
    },
    {
      title: '买家/收货人',
      dataIndex: 'receiverName',
      rowSpanMode: 'auto',
      width: 150,
      render: ({ value, record }) => `${value || '-'}/${record.receiverMobile || '-'}`,
    },
    {
      title: '付款金额（元）',
      dataIndex: 'supplyAmount',
      width: 150,
    },
    {
      title: '订单状态',
      dataIndex: 'orderStatusDesc',
      rowSpanMode: 'auto',
      width: 150,
    },
    {
      title: '配送方式',
      dataIndex: 'deliveryMethodList',
      // rowSpanMode: 'auto',
      width: 150,
      render: ({ value, record, subRecord }) => {
        console.log(value);
        const info = {
          orderNo: record.orderNoStr,
        };
        return value?.map(item => (
          <p>
            {item.expressCompanyName}/
            <a
              onClick={() => {
                handleCom(info, item);
              }}
            >
              {item.expressNo}
            </a>
          </p>
        ));
      },
    },
    {
      title: '售后',
      dataIndex: 'afterSaleVos',
      width: 220,
      align: 'left',
      render: ({ value }) => {
        if (value && value.length) {
          return value.map(item => (
            <div className={style['after-status-box']}>
              <div className={style.desc}>{item.afterServiceStatusDesc}</div>
              <div className={style.blue}>{item.afterServiceNo}</div>
            </div>
          ));
        }
        return <div align="center">-</div>;
      },
    },
    {
      title: '操作',
      rowSpanMode: 'auto',
      align: 'center',
      width: 100,
      render: ({ value, record, index, subRecord, subIndex }) => {
        if (!canEditable) {
          return '-';
        }
        let text = '';

        if ([12, 14].includes(record.orderStatus)) {
          text = '发货';
        }
        if ([13].includes(record.orderStatus)) {
          text = '修改物流';
        }
        // 服务订单不展示发货/修改物流
        if (record.productType === 4) {
          return <></>;
        }
        return (
          <>
            {text ? (
              <Button
                type="primary"
                onClick={async () => {
                  const res = await apiQueryOrderInfo({
                    orderNo: record.orderNoStr,
                  });

                  multiLogisticsModalRef.current.open(
                    {
                      ...record,
                      orderNo: record.orderNoStr,
                      mchOrderSkuVoList: record.skuVos.map(item => ({
                        ...item,
                        skuNo: item.skuId?.toString(),
                        orderNo: record.orderNoStr,
                      })),
                      packageList: res.data.packageList || [],
                    },
                    actionRef,
                  );
                }}
              >
                {text}
              </Button>
            ) : (
              ''
            )}
          </>
        );
      },
    },
  ];

  const tableProps = {
    bordered: true,
    columns,
    rowKey: 'skuId',
    align: 'center',
    dataSource: tableData,
    subDataField: 'skuVos',
    loading,
  };

  return (
    <PageHeaderWrapper>
      <FormSearch {...FormSearchProps} />
      <div className={style['tab-box']}>
        <Tabs
          activeKey={currentOrderStatus}
          onChange={orderStatusChange}
          size="large"
          tabBarStyle={{ padding: '0 30px' }}
        >
          <TabPane key="" tab="全部"></TabPane>
          <TabPane key={1} tab="未支付"></TabPane>
          <TabPane key={2} tab="待发货"></TabPane>
          <TabPane key={3} tab="已发货"></TabPane>
          <TabPane key={4} tab="已完成"></TabPane>
          <TabPane key={5} tab="已关闭"></TabPane>
        </Tabs>
      </div>

      <div className={style['white-box']}>
        <CustomTable
          {...tableProps}
          eachRowHeadRender={record => (
            <div className={style['table-item-header']}>
              <div className={style['table-item-header--info']}>
                <span>订单编号：{record.orderNoStr}</span>
                <span>下单时间：{record.orderTime}</span>
              </div>
              <a
                onClick={() => {
                  openDetailModal(record);
                }}
                className={style['table-item-header--btn']}
              >
                查看详情
              </a>
            </div>
          )}
        ></CustomTable>
        {/* 分页 */}
        {tableData.length ? (
          <div className={style['table-pagination']}>
            <Pagination
              onChange={onPageChange}
              total={dataTotal}
              showTotal={(total, range) => `第${range[0]}-${range[1]}条 /总共${total}条`}
              pageSize={pagination.pageSize}
              current={pagination.pageNo}
            />
          </div>
        ) : (
          ''
        )}
      </div>

      <LogisticsCom
        onSubmit={reload}
        onCancel={() => handleComModalVisible(false)}
        modalVisible={LogisticsComModalVisible}
        value={LogisticsComList}
        key={LogisticsComList.key}
      />
      <MultiLogisticsModal companys={companys} ref={multiLogisticsModalRef} />
      <DetailModal ref={detailModalRef} />
    </PageHeaderWrapper>
  );
};
export default connect(({ menu }) => ({
  permissions: menu.permissions,
}))(OrderList);
