import React, { useState, useRef } from 'react';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { queryRptProductionProgress_GYQP } from '@/services/report/reportService';
import ExportForm from './components/ExportForm/index';
import moment from 'moment';
import { Button, message } from 'antd';
import { FormattedMessage, useIntl } from '@@/plugin-locale/localeExports';
import { FileExcelOutlined } from '@ant-design/icons';
import '../RptProductionByDay_GYQP/index.less';
const Main: React.FC = () => {
  const intl = useIntl();
  const actionRef = useRef<ActionType>();
  const [dataSource, setDataSource] = useState<Report.RptProductionProgressDto>();
  const [exportFormVisible, setExportFormVisible] = useState(false);

  const defColumns =
    dataSource == null || dataSource.operations == null || dataSource.operations.length == 0
      ? []
      : dataSource.operations.map((t) => ({
          title: t.operation,
          hideInSearch: true,
          children: [
            {
              title: '计划',
              width: 100,
              render: (text: any, record: Report.RptProductionProgressGroupByDay) => {
                const target = record.details.find((item) => item.operation === t.operation);
                return target ? target.plannedQuantity : '';
              },
            },
            {
              title: '实际',
              width: 100,
              render: (_: any, record: Report.RptProductionProgressGroupByDay) => {
                const target = record.details.find((item) => item.operation === t.operation);
                return target ? target.finishedQuantity : '';
              },
            },
          ],
        }));

  const columns: ProColumns<Report.RptProductionProgressGroupByDay>[] = [
    {
      title: 'SAP订单号',
      dataIndex: 'aufnr',
      valueType: 'text',
      width: 100,
      hideInSearch: true,
    },
    {
      title: '物料编码',
      dataIndex: 'partCode',
      valueType: 'text',
      width: 100,
      hideInSearch: true,
    },
    {
      title: '物料描述',
      dataIndex: 'partName',
      valueType: 'text',
      width: 100,
      hideInSearch: true,
    },
    {
      title: '订单数量',
      dataIndex: 'sapOrderQuantity',
      valueType: 'text',
      width: 60,
      hideInSearch: true,
    },
    {
      title: '产品施工号',
      dataIndex: 'sgNo',
      valueType: 'text',
      width: 100,
      hideInSearch: true,
    },
    {
      title: '日期',
      dataIndex: 'byDay',
      valueType: 'text',
      width: 100,
      hideInSearch: true,
    },
    ...defColumns,
    {
      title: '工厂',
      dataIndex: 'werks',
      valueType: 'text',
      hideInTable: true,
      formItemProps: {
        initialValue: '1248',
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      },
    },
    {
      title: '生产管理员',
      dataIndex: 'fevor',
      valueType: 'text',
      hideInTable: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      },
    },
    {
      title: '产品施工号',
      dataIndex: 'sgNo',
      valueType: 'text',
      hideInTable: true,
    },
    {
      title: '订单状态',
      dataIndex: 'orderStatus',
      valueType: 'select',
      hideInTable: true,
      valueEnum: {
        all: { text: '全部' },
        working: {
          text: '未完工',
        },
        finished: {
          text: '已完工',
        },
      },
      initialValue: ['working'],
    },
    {
      title: '开始时间范围',
      dataIndex: 'monthRange',
      valueType: 'dateRange',
      hideInTable: true,
      initialValue: [moment().add(-7, 'days').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')],
      colSize: 2,
    },
  ];

  return (
    <PageContainer
      header={{
        title: null,
      }}
    >
      <ProTable<Report.RptProductionProgressGroupByDay, Report.RptProductionProgressCriteria>
        headerTitle=""
        rowKey="key"
        actionRef={actionRef}
        search={{
          labelWidth: 120,
        }}
        bordered
        rowClassName={(record, index) => {
          return index % 2 === 0 ? 'grey' : '';
        }}
        tableStyle={{ height: '650px' }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="export"
            onClick={() => {
              setExportFormVisible(true);
            }}
          >
            <FileExcelOutlined />
            <FormattedMessage id="component.option.exprot" defaultMessage="导出" />
          </Button>,
        ]}
        request={async (params: Report.RptProductionProgressCriteria) => {
          // 日期格式转换
          const monthRange: [string, string] = [
            moment(params.monthRange ? params.monthRange[0] : undefined)?.format(
              'YYYY-MM-DD HH:mm:ss',
            ),
            moment(params.monthRange ? params.monthRange[1] : undefined)
              ?.add(1, 'days')
              .format('YYYY-MM-DD HH:mm:ss'),
          ];
          let orderFinished: boolean | undefined = undefined;
          if (params.orderStatus == 'working') {
            orderFinished = false;
          }
          if (params.orderStatus == 'finished') {
            orderFinished = true;
          }
          const queryParams: Report.RptProductionProgressCriteria = {
            werks: params.werks,
            fevor: params.fevor,
            sgNo: params.sgNo,
            dateFrom: monthRange[0],
            dateTo: monthRange[1],
            orderFinished: orderFinished,
          };
          const sr = await queryRptProductionProgress_GYQP(queryParams);
          if (sr.data == null) {
            setDataSource(undefined);
            return {
              data: [],
              total: 0,
              success: true,
            };
          } else {
            setDataSource(sr.data);
            return {
              data: sr.data.groupByDays,
              total: sr.data.groupByDays.length,
              success: true,
            };
          }
        }}
        columns={columns}
        tableAlertRender={false}
        pagination={{
          pageSize: 100,
        }}
        scroll={{ y: 600 }}
        manualRequest={true}
        form={{
          ignoreRules: false,
        }}
      />
      <ExportForm
        dataGetter={async () => {
          return dataSource;
        }}
        fileNameProvider={async () => {
          const data = moment().format('-YYYYMMDDHHmmss');
          return '高压气瓶生产进度报表' + data + '.xlsx';
        }}
        visible={exportFormVisible}
        onVisibleChange={setExportFormVisible}
        onSubmitting={async () => {
          const hide = message.loading(
            intl.formatMessage({
              id: 'component.option.exprot.loading',
              defaultMessage: '正在导出...',
            }),
          );
          return {
            hide,
          };
        }}
        onSuccess={async (params: any) => {
          params.hide();
          setExportFormVisible(false);
        }}
        onError={async (params: any) => {
          params.hide();
        }}
      />
    </PageContainer>
  );
};

export default Main;
