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 { queryRptProductionByDay_GYQP } from '@/services/report/reportService';
import ExportForm from './components/ExportForm/index';
import moment from 'moment';
import { Button, Card, Descriptions, message } from 'antd';
import { FormattedMessage, useIntl } from '@@/plugin-locale/localeExports';
import { FileExcelOutlined } from '@ant-design/icons';
import { ProFormDatePicker } from '@ant-design/pro-form';
import './index.less';

const Main: React.FC = () => {
  const intl = useIntl();
  const actionRef = useRef<ActionType>();
  const [dataSource, setDataSource] = useState<Report.RptProductionByDayDto>();
  const [exportFormVisible, setExportFormVisible] = useState(false);

  const defColumns =
    dataSource == null || dataSource.headers == null || dataSource.headers.length == 0
      ? []
      : dataSource.headers.map((t) => ({
          title: t.operation,
          hideInSearch: true,
          children: [
            {
              title: t.dailyQuantity,
              children: [
                {
                  title: t.totalQuantity,
                  children: [
                    {
                      title: '施工号',
                      width: 400,
                      render: (text: any, record: Report.RptProductionByDayDetailGroup) => {
                        const target = record.details.find(
                          (item) => item.operation === t.operation && item.fevor === t.fevor,
                        );
                        return target ? target.sgNo : '';
                      },
                    },
                    {
                      title: '数量',
                      width: 60,
                      render: (text: any, record: Report.RptProductionByDayDetailGroup) => {
                        const target = record.details.find(
                          (item) => item.operation === t.operation && item.fevor === t.fevor,
                        );
                        return target ? target.quantity : '';
                      },
                    },
                  ],
                },
              ],
            },
          ],
        }));

  const columns: ProColumns<Report.RptProductionByDayDetailGroup>[] = [
    {
      title: '工序',
      hideInSearch: true,
      children: [
        {
          title: '日标准产量',
          children: [
            {
              title: '月累计完工量',
              children: [
                {
                  width: 150,
                  title: '日期',
                  dataIndex: 'byDay',
                  valueType: 'text',
                  fixed: true,
                },
              ],
            },
          ],
        },
      ],
    },
    ...defColumns,
    {
      title: '生产管理员',
      dataIndex: 'fevor',
      valueType: 'text',
      hideInTable: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      },
    },
    {
      title: '月份',
      dataIndex: 'month',
      hideInTable: true,
      renderFormItem: () => {
        return (
          <div className="cust-prosearch-month">
            <ProFormDatePicker.Month name="month" initialValue={moment()} />
          </div>
        );
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      },
    },
    {
      title: '工厂',
      dataIndex: 'werks',
      valueType: 'text',
      hideInTable: true,
      formItemProps: {
        initialValue: '1248',
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      },
    },
  ];

  return (
    <PageContainer
      header={{
        title: null,
      }}
    >
      <ProTable<Report.RptProductionByDayDetailGroup, Report.RptProductionByDayCriteria>
        headerTitle=""
        rowKey="byDay"
        actionRef={actionRef}
        search={{
          labelWidth: 120,
        }}
        bordered
        rowClassName={(record, index) => {
          return index % 2 === 0 ? 'grey' : '';
        }}
        tableStyle={{ height: '300px' }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="export"
            onClick={() => {
              setExportFormVisible(true);
            }}
          >
            <FileExcelOutlined />
            <FormattedMessage id="component.option.exprot" defaultMessage="导出" />
          </Button>,
        ]}
        tableExtraRender={() => (
          <Card>
            <Descriptions size="small" column={2}>
              <Descriptions.Item label="月计划">{dataSource?.monthlyPlanQty}</Descriptions.Item>
              <Descriptions.Item label="月计划达成率">
                {dataSource ? (dataSource?.monthlyPlanRate * 100).toFixed(2) : 0}%
              </Descriptions.Item>
            </Descriptions>
          </Card>
        )}
        request={async (params: Report.RptProductionByDayCriteria) => {
          const sr = await queryRptProductionByDay_GYQP(params);
          if (sr.data == null) {
            setDataSource(undefined);
            return {
              data: [],
              total: 0,
              success: true,
            };
          } else {
            setDataSource(sr.data);
            return {
              data: sr.data.detailGroups,
              total: sr.data.detailGroups.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;
