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_DWP } 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 { ProFormDatePicker } from '@ant-design/pro-form';
import LotForm from '@/pages/report/RptProductionByDay_DWP/components/LotForm';
import '../RptProductionByDay_GYQP/index.less';
const Main: React.FC = () => {
  const intl = useIntl();
  const actionRef = useRef<ActionType>();
  const [dataSource, setDataSource] = useState<Report.RptProductionByDayDto>();
  const [currentRow, setCurrentRow] = useState<any>();
  const [lotFormVisible, setLotFormVisible] = useState(false);
  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,
          dataIndex: 'details',
          children: [
            {
              title: '计划数量',
              width: 100,
              render: (text: any, record: Report.RptProductionByDayDetailGroup) => {
                const target = record.details.find(
                  (item) => item.operation === t.operation && item.fevor === t.fevor,
                );
                return target ? target.dailyQuantity : '';
              },
            },
            {
              title: '完成数量',
              width: 100,
              render: (_: any, record: Report.RptProductionByDayDetailGroup) => {
                const target = record.details.find(
                  (item) => item.operation === t.operation && item.fevor === t.fevor,
                );
                return (
                  <a
                    onClick={async () => {
                      setCurrentRow(target);
                      setLotFormVisible(true);
                    }}
                  >
                    {target ? target.quantity.toString() : ''}
                  </a>
                );
              },
            },
          ],
        }));

  const columns: ProColumns<Report.RptProductionByDayDetailGroup>[] = [
    {
      title: '日期',
      hideInSearch: true,
      width: 150,
      dataIndex: 'byDay',
      valueType: 'text',
    },
    ...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: 'Q248',
        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: '400px' }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="export"
            onClick={() => {
              setExportFormVisible(true);
            }}
          >
            <FileExcelOutlined />
            <FormattedMessage id="component.option.exprot" defaultMessage="导出" />
          </Button>,
        ]}
        request={async (params: Report.RptProductionByDayCriteria) => {
          const sr = await queryRptProductionByDay_DWP(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, x: 1400 }}
        manualRequest={true}
        form={{
          ignoreRules: false,
        }}
      />
      <LotForm
        values={currentRow || {}}
        visible={lotFormVisible}
        onVisibleChange={setLotFormVisible}
      />
      <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;
