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_GRCC } from '@/services/report/reportService';
import ExportForm from './components/ExportForm/index';
import moment from 'moment';
import { Button, message, Space, Tag } 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.RptProductionProgressGroupBySG) => {
                const target = record.details.find((item) => item.operation === t.operation);
                let color = '';
                if (
                  target &&
                  target.byDay &&
                  target.byDay.length > 0 &&
                  target.plannedByDay &&
                  target.plannedByDay.length > 0
                ) {
                  if (target.byDay > target.plannedByDay) {
                    color = 'red';
                  }
                }
                if (
                  target &&
                  ((target.byDay && target.byDay.length == 0) || target.byDay == null) &&
                  target.plannedByDay &&
                  target.plannedByDay.length > 0
                ) {
                  if (moment().format('YYYY-MM-DD') > target.plannedByDay) {
                    color = 'red';
                  }
                }
                if (color && color.length > 0) {
                  return (
                    <Space>
                      <Tag color={color}>{target ? target.plannedByDay : ''}</Tag>
                    </Space>
                  );
                } else {
                  return target ? target.plannedByDay : '';
                }
              },
            },
            {
              title: '实际',
              width: 100,
              render: (_: any, record: Report.RptProductionProgressGroupBySG) => {
                const target = record.details.find((item) => item.operation === t.operation);
                return target ? target.byDay : '';
              },
            },
          ],
        }));

  const columns: ProColumns<Report.RptProductionProgressGroupBySG>[] = [
    {
      title: '施工号',
      dataIndex: 'sgNo',
      valueType: 'text',
      width: 150,
      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.RptProductionProgressGroupBySG, 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_GRCC(queryParams);
          if (sr.data == null) {
            setDataSource(undefined);
            return {
              data: [],
              total: 0,
              success: true,
            };
          } else {
            setDataSource(sr.data);
            return {
              data: sr.data.groupBySGList,
              total: sr.data.groupBySGList.length,
              success: true,
            };
          }
        }}
        columns={columns}
        tableAlertRender={false}
        pagination={{
          pageSize: 100,
        }}
        scroll={{ y: 600, x: 1400 }}
        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;
