import { useState, useEffect } from 'react';
import React, { useMemo, useReducer } from 'react';
import { request } from '@/utils';
import {
  Input,
  Button,
  Row,
  Col,
  Form,
  DatePicker,
  Collapse,
  message,
  Table,
  Space,
  Modal,
  Card,
  Tooltip,
  Tabs,
  Select,
} from 'antd';
import {
  CheckCircleOutlined,
  FormOutlined,
  MinusCircleOutlined,
  PlusCircleOutlined,
  PrinterOutlined,
  SearchOutlined,
  UndoOutlined,
  CopyTwoTone,
  ZoomInOutlined,
  SplitCellsOutlined,
  ExclamationCircleOutlined,
  DownloadOutlined,
} from '@ant-design/icons';
import moment from 'moment';
import ReactEcharts from 'echarts-for-react';
import Dictionary from '@/components/Dictionary';
import { exportTable } from '@/utils/exportTable';
import styles from './index.less';
import useARH from '@minko-fe/use-antd-resizable-header';
import 'antd/dist/antd.css';
import '@minko-fe/use-antd-resizable-header/dist/index.css';

import { KeepAlive } from 'umi';
import { ColumnsType } from 'antd/lib/table/interface';
import { ITableHeader, StudentInfo } from '@/types';
import * as ExcelJs from 'exceljs';
import {
  addHeaderStyle,
  DEFAULT_COLUMN_WIDTH,
  DEFAULT_ROW_HEIGHT,
  generateHeaders,
  getColumnNumber,
  mergeColumnCell,
  mergeRowCell,
  saveWorkbook,
} from '@/utils/indexs';
import { Worksheet } from 'exceljs';
interface MultiHeaderProps { }

const formRow = 1;
const SubHistory = () => {
  const { Item } = Form;
  const { Panel } = Collapse;
  const nowDate = new Date();
  const nowStartDate = parseInt(
    new Date(nowDate.setDate(nowDate.getDate() - 2)).getTime().toString(),
  ); // 当前时间-1天
  const nowEndDate = parseInt(new Date().getTime().toString()); // 当前时间
  const print = nowDate.toLocaleTimeString();
  const [dataSource, setDataSource] = useState([]);
  const [dataSource1, setDataSource1] = useState([]);
  const [Visible, setVisible] = useState(false);
  const [action, setAction] = useState('');
  const [loading, setLoading] = useState(false);
  const [numOption, setNumOption] = useState({});
  const [rateOption, setRateOption] = useState({});
  const [activeKey, setActiveKey] = useState('');
  const { TabPane } = Tabs;
  const [form] = Form.useForm();
  const [formData] = Form.useForm();
  const [selectedRow, setselectedRow] = useState([]);
  const [selectedKey, setselectedkey] = useState(0);
  const [list, setList] = useState<StudentInfo[]>([]);
  const [begin, setBegin] = useState('');
  const [end, setEnd] = useState('');
  const dateFormat = 'YYYY-MM-DD';
  const { RangePicker } = DatePicker;
  const [OPTIONS, setOptions] = useState([]);
  const [selectedItems, setSelectedItems] = useState<string[]>([]);
  const [selectedItems1, setSelectedItems1] = useState<string[]>([]);
  const filteredOptions = OPTIONS.filter((o) => !selectedItems.includes(o));
  const [CUVOPTIONS, setCuvOptions] = useState([]);
  const filteredOptions1 = CUVOPTIONS.filter((o) => !selectedItems1.includes(o));
  const [, forceRender] = useReducer((s) => s + 1, 0);
  const [deps, setDeps] = useState(0);
  // const [selectedRowKeys, setSelectedRowKeys] = useState([])
  // const onSelectChange = (selectedRowKeys:any, selectedRows:any) => {
  //   //setSelectedRows(selectedRows)
  //   setSelectedRowKeys(selectedRowKeys)   PROFIT
  // }

  //导出操作
  const onExportClick = () => {
    if (dataSource.length == 0) {
      message.error('暂无数据，请确认后重试！');
      return;
    }
    exportTable(columns, dataSource, '余材替代历史信息.xlsx');
  };

  useEffect(() => {
    generateData();
    ts();
    onSearchClick();
    iniClick();
    cuvClick();
  }, []);

  function generateData() {
    let arr: StudentInfo[] = [];
    for (let i = 0; i < 5; i++) {
      arr.push({
        id: i,
        name: ``,
        age: 8 + i,
        gender: i % 2 === 0 ? '' : '',
        english: 80 + i,
        math: 60 + i,
        physics: 70 + i,
        comment: ``,
      });
    }
    setList(arr);
  }

  function onExportMultiHeaderExcel() {
    // 创建工作簿
    const workbook = new ExcelJs.Workbook();
    // 添加sheet
    const worksheet = workbook.addWorksheet('sheet');
    // 设置 sheet 的默认行高
    worksheet.properties.defaultRowHeight = 20;
    // 解析 AntD Table 的 columns
    const headers = generateHeaders(columns);
    console.log({ headers });
    // 第一行表头
    const names1: string[] = [];
    // 第二行表头
    const names2: string[] = [];
    // 用于匹配数据的 keys
    const headerKeys: string[] = [];
    headers.forEach((item) => {
      if (item.children) {
        // 有 children 说明是多级表头，header name 需要两行
        item.children.forEach((child) => {
          names1.push(item.header);
          names2.push(child.header);
          headerKeys.push(child.key);
        });
      } else {
        const columnNumber = getColumnNumber(item.width);
        for (let i = 0; i < columnNumber; i++) {
          names1.push(item.header);
          names2.push(item.header);
          headerKeys.push(item.key);
        }
      }
    });
    handleHeader(worksheet, headers, names1, names2);
    // 添加数据
    addData2Table(worksheet, headerKeys, headers);
    // 给每列设置固定宽度
    worksheet.columns = worksheet.columns.map((col) => ({ ...col, width: DEFAULT_COLUMN_WIDTH }));
    // 导出
    saveWorkbook(workbook, print + '-' + '余材替代历史信息.xlsx');
  }

  function handleHeader(
    worksheet: Worksheet,
    headers: ITableHeader[],
    names1: string[],
    names2: string[],
  ) {
    // 判断是否有 children, 有的话是两行表头
    const isMultiHeader = headers?.some((item) => item.children);
    if (isMultiHeader) {
      // 加表头数据
      const rowHeader1 = worksheet.addRow(names1);
      const rowHeader2 = worksheet.addRow(names2);
      // 添加表头样式
      addHeaderStyle(rowHeader1, { color: 'dff8ff' });
      addHeaderStyle(rowHeader2, { color: 'dff8ff' });
      mergeColumnCell(headers, rowHeader1, rowHeader2, names1, names2, worksheet);
      return;
    }
    // 加表头数据
    const rowHeader = worksheet.addRow(names1);
    // 表头根据内容宽度合并单元格
    mergeRowCell(headers, rowHeader, worksheet);
    // 添加表头样式
    addHeaderStyle(rowHeader, { color: 'dff8ff' });
  }

  function addData2Table(worksheet: Worksheet, headerKeys: string[], headers: ITableHeader[]) {
    dataSource?.forEach((item: any) => {
      const rowData = headerKeys?.map((key) => item[key]);
      const row = worksheet.addRow(rowData);
      mergeRowCell(headers, row, worksheet);
      row.height = DEFAULT_ROW_HEIGHT;
      // 设置行样式, wrapText: 自动换行
      row.alignment = { vertical: 'middle', wrapText: false, shrinkToFit: false };
      row.font = { size: 11, name: '微软雅黑' };
    });
  }

  //数据源，字典查询
  const iniClick = () => {
    const sd = {
      CD_MANA_NO: 'TDZT',
    };
    const res = request.post(`/ipdApi/basic/getBasicCode`, sd).then((res) => {
      if (res.data.code == '1') {
        if (res.data.data) {
          const array = res.data.data.map((item: any) => {
            return item.CD;
          });
          setOptions(array);
        }
      }
    });
  };

  const cuvClick = () => {
    const sd = {
      CD_MANA_NO: 'CKKB',
    };
    const res = request.post(`/ipdApi/basic/getBasicCode`, sd).then((res) => {
      if (res.data.code == '1') {
        if (res.data.data) {
          const array = res.data.data.map((item: any) => {
            return item.CD;
          });
          setCuvOptions(array);
        }
      }
    });
  };

  //添加按钮打开添加Modal页面
  const onAddClick = () => {
    formData.resetFields();
    setVisible(true);
    setAction('新增');
  };
  //复制新增按钮按下时操作
  const onCopyAddClick = () => {
    if (dataSource.length == 0 || selectedRow.length != 1) {
      message.warn('请先选中一条数据');
      return;
    }
    formData.setFieldsValue(selectedRow[0]);
    setVisible(true);
    setAction('复制新增');
  };
  //修改按钮按下时操作
  const onEditClick = () => {
    formData.resetFields();
    if (dataSource.length == 0 || selectedRow.length != 1) {
      message.warn('请先选中一条数据');
      return;
    }
    formData.setFieldsValue(selectedRow[0]);
    setVisible(true);
    setAction('修改');
  };

  //导出操作
  // const onExportClick = () => {
  //   if (dataSource.length == 0) {
  //     message.error('暂无数据，请确认后重试！');
  //     return;
  //   }
  //   exportTable(columns, dataSource, '压缩比规范.xlsx');
  // };

  // 新增、复制新增、修改功能
  const modalSubmit = () => {
    const postData = formData.getFieldsValue();
    if (action == '新增' || action == '复制新增') {
      const res = request.post(`/ipdApi/hotRoll/addCompressionRatio`, postData).then((res) => {
        if (res.data.code == '1') {
          message.success('操作成功！');
          setVisible(false);
          onSearchClick();
          // setselectedkey(0)
        } else {
          message.error(res.data.msg);
        }
      });
    } else if (action == '修改') {
      // 因数据库表结构设计多主键，所以更新操作传值时需要将未修改前的数据与修改后的数据一并传到后台处理
      const requestData = selectedRow.map((item: any, index: any) => ({
        ...item,
      }));
      requestData.push(postData);
      const res = request.post(`/ipdApi/hotRoll/updCompressionRatio`, requestData).then((res) => {
        if (res.data.code == '1') {
          message.success('操作成功！');
          setselectedkey(0);
          setVisible(false);
          // onSearchClick();
        } else {
          message.error(res.data.msg);
          setVisible(false);
        }
        onSearchClick();
      });
    }
  };

  // 删除按钮按下时操作
  const onDeleteClick = () => {
    if (dataSource.length == 0 || selectedRow.length != 1) {
      message.warn('请选择要删除的数据！');
      return;
    }

    Modal.confirm({
      title: '确定要删除吗？',
      icon: <ExclamationCircleOutlined />,
      onOk: async () => {
        const res = request
          .post(`/ipdApi/hotRoll/delCompressionRatio`, selectedRow[0])
          .then((res) => {
            if (res.data.code == '1') {
              message.success('操作成功！');
              setselectedkey(0);
              setVisible(false);
              onSearchClick();
            } else {
              message.error(res.data.msg);
              setVisible(false);
            }
          });
      },
    });
  };
  const onTabChange = (key: any) => {
    if (key === '1') {
      setDataSource;
    }
    setActiveKey(key);
  };
  //容器头按钮
  const headerButtons = () => (
    <Space size={8}>
      <Button
        type="primary"
        size="small"
        icon={<SearchOutlined />}
        onClick={(event) => {
          ts();
          event.stopPropagation();
          onSearchClick();
        }}
        disabled={loading ? true : false}
      >
        查询
      </Button>
      <Button
        type="primary"
        danger
        size="small"
        icon={<UndoOutlined />}
        onClick={(event) => {
          event.stopPropagation();
          handleRest();
        }}
      >
        重置
      </Button>
      <Button
        type="primary"
        size="small"
        icon={<DownloadOutlined />}
        onClick={(event) => {
          event.stopPropagation();
          onExportMultiHeaderExcel();
        }}
      >
        导出
      </Button>
    </Space>
  );

  const columns = [
    {
      title: '序号',
      dataIndex: 'NO',
      key: 'NO',
      render: (text: any, record: any, index: any) => <div>{index + 1}</div>,
      width: 50,
      fixed: 'left',
    },
    // {
    //   title: '序号',
    //   dataIndex: 'ID',
    //   key: 'ID',
    //   width: 70,
    // },
    {
      title: '钢板号',
      dataIndex: 'PLATE_NO',
      key: 'PLATE_NO',
      width: 130,
      ellipsis: true,
      fixed: 'left',
      className: 'last_lt',
    },
    { title: '替代成材率', dataIndex: 'EFF_RATE', key: 'EFF_RATE', width: 90, ellipsis: true },
    {
      title: '替代价值',
      dataIndex: 'ALTERNATIVE_PRICE',
      key: 'ALTERNATIVE_PRICE',
      width: 90,
      ellipsis: true,
    },
    {
      title: '现货价值',
      dataIndex: 'GENUINE_PRICE',
      key: 'GENUINE_PRICE',
      width: 90,
      ellipsis: true,
    },
    {
      title: '损耗费',
      dataIndex: 'BREAKAGE_COSTS',
      key: 'BREAKAGE_COSTS',
      width: 90,
      ellipsis: true,
    },
    {
      title: '切割费',
      dataIndex: 'CUTTING_COSTS',
      key: 'CUTTING_COSTS',
      width: 90,
      ellipsis: true,
    },
    {
      title: '运输费',
      dataIndex: 'TRANSPORT_COSTS',
      key: 'TRANSPORT_COSTS',
      width: 90,
      ellipsis: true,
    },
    {
      title: '检验费',
      dataIndex: 'INSPECT_COSTS',
      key: 'INSPECT_COSTS',
      width: 90,
      ellipsis: true,
    },
    { title: '牌号价格', dataIndex: 'PRICE', key: 'PRICE', width: 90, ellipsis: true },
    { title: '废钢价格', dataIndex: 'SCRAP_PRICE', key: 'SCRAP_PRICE', width: 90, ellipsis: true },
    { title: '现货价格', dataIndex: 'SPOT_PRICE', key: 'SPOT_PRICE', width: 90, ellipsis: true },
    { title: '增效', dataIndex: 'PROFIT', key: 'PROFIT', width: 90, ellipsis: true },
    { title: '是否小尺板', dataIndex: 'IS_SMALL_PLATE', key: 'IS_SMALL_PLATE', width: 90, ellipsis: true },
    { title: '替代成材率', dataIndex: 'EFF_RATE', key: 'EFF_RATE', width: 100, ellipsis: true },
    {
      title: '钢板利用率',
      dataIndex: 'SUB_RATE',
      key: 'SUB_RATE',
      width: 90,
    },
    {
      title: '确认时间',
      dataIndex: 'CON_TIME',
      key: 'CON_TIME',
      width: 102,
      ellipsis: true,
    },
    { title: '替代类型', dataIndex: 'IS_FULL', key: 'IS_FULL', width: 83, ellipsis: true },
    {
      title: '处理结果',
      dataIndex: 'HAN_STATE',
      key: 'HAN_STATE',
      width: 75,
      ellipsis: true,
    },
    {
      title: '处理内容',
      dataIndex: 'HAN_CON',
      key: 'HAN_CON',
      width: 100,
      ellipsis: true,
    },
    {
      title: '当前状态',
      dataIndex: 'PROC_CD_NOW',
      key: 'PROC_CD_NOW',
      width: 90,
      ellipsis: true,
    },
    {
      title: '当前仓库',
      dataIndex: 'CURRENT_CUR_INV',
      key: 'CURRENT_CUR_INV',
      width: 90,
      ellipsis: true,
    },
    {
      title: '当前货位',
      dataIndex: 'CURRENT_LOC',
      key: 'CURRENT_LOC',
      width: 100,
      ellipsis: true,
    },
    {
      title: '订单材/余材',
      dataIndex: 'ORD_FL',
      key: 'ORD_FL',
      width: 100,
    },
    {
      title: '原始钢板信息',
      ellipsis: true,
      dataIndex: 'age5',
      key: 'age5',
      children: [
        {
          title: '厚度',
          dataIndex: 'GP_Y_THK',
          key: 'GP_Y_THK',
          width: 60,
        },
        {
          title: '宽度',
          dataIndex: 'GP_Y_WID',
          key: 'GP_Y_WID',
          width: 60,
        },
        {
          title: '长度',
          dataIndex: 'GP_Y_LEN',
          key: 'GP_Y_LEN',
          width: 60,
        },
        {
          title: '重量',
          dataIndex: 'GP_Y_WGT',
          key: 'GP_Y_WGT',
          width: 60,
        },
      ],
    },
    {
      title: '替代前物料信息',
      ellipsis: true,
      dataIndex: 'age1',
      key: 'age1',
      className: 'hisPlaColor',
      children: [
        {
          title: '标准号',
          dataIndex: 'GP_APLY_STDSPEC',
          key: 'GP_APLY_STDSPEC',
          width: 160,
          ellipsis: true,
          className: 'hisPlaColor',
        },
        {
          title: '厚度',
          dataIndex: 'GP_THK',
          key: 'GP_THK',
          width: 60,
          ellipsis: true,
          className: 'hisPlaColor',
        },
        {
          title: '宽度',
          dataIndex: 'GP_WID',
          key: 'GP_WID',
          width: 60,
          ellipsis: true,
          className: 'hisPlaColor',
        },
        {
          title: '长度',
          dataIndex: 'GP_LEN',
          key: 'GP_LEN',
          width: 60,
          ellipsis: true,
          className: 'hisPlaColor',
        },
        {
          title: '重量',
          dataIndex: 'GP_WGT',
          key: 'GP_WGT',
          width: 60,
          ellipsis: true,
          className: 'hisPlaColor',
        },
        {
          title: '状态',
          dataIndex: 'PROC_STATE',
          key: 'PROC_STATE',
          width: 75,
          ellipsis: true,
          className: 'hisPlaColor',
        },
        {
          title: '表面等级',
          dataIndex: 'GP_SURF_GRD',
          key: 'GP_SURF_GRD',
          width: 90,
          ellipsis: true,
          className: 'hisPlaColor',
        },
        {
          title: '仓库',
          dataIndex: 'GP_CUR_INV',
          key: 'GP_CUR_INV',
          width: 90,
          ellipsis: true,
          className: 'hisPlaColor',
        },
        {
          title: '货位',
          dataIndex: 'LOC',
          key: 'LOC',
          width: 100,
          ellipsis: true,
          className: 'hisPlaColor',
        },
      ],
    },
    {
      title: '替代后订单',
      ellipsis: true,
      dataIndex: 'age2',
      key: 'age2',
      className: 'hisEndColor',
      children: [
        {
          title: '订单号',
          dataIndex: 'BOI_ORD_NO',
          key: 'BOI_ORD_NO',
          width: 110,
          ellipsis: true,
          className: 'hisEndColor',
        },
        {
          title: '序列号',
          dataIndex: 'BOI_ORD_ITEM',
          key: 'BOI_ORD_ITEM',
          width: 70,
          ellipsis: true,
          className: 'hisEndColor',
        },
        {
          title: '厚度',
          dataIndex: 'BOI_ORD_THK',
          key: 'BOI_ORD_THK',
          width: 60,
          ellipsis: true,
          className: 'hisEndColor',
        },
        {
          title: '宽度',
          dataIndex: 'BOI_ORD_WID',
          key: 'BOI_ORD_WID',
          width: 60,
          ellipsis: true,
          className: 'hisEndColor',
        },
        {
          title: '长度',
          dataIndex: 'BOI_ORD_LEN',
          key: 'BOI_ORD_LEN',
          width: 60,
          ellipsis: true,
          className: 'hisEndColor',
        },
        {
          title: '重量',
          dataIndex: 'BOB_WGT',
          key: 'BOB_WGT',
          width: 60,
          ellipsis: true,
          className: 'hisEndColor',
        },
        {
          title: '标准',
          dataIndex: 'BOI_STDSPEC',
          key: 'BOI_STDSPEC',
          width: 160,
          ellipsis: true,
          className: 'hisEndColor',
        },
        {
          title: '欠重',
          dataIndex: 'SUB_LACK_WGT',
          key: 'SUB_LACK_WGT',
          width: 60,
          ellipsis: true,
          className: 'hisEndColor',
        },
        {
          title: '订单重',
          dataIndex: 'ORD_WGT',
          key: 'ORD_WGT',
          width: 80,
          ellipsis: true,
          className: 'hisEndColor',
        },

        {
          title: '欠量',
          dataIndex: 'SUB_LACK_NUM',
          key: 'SUB_LACK_NUM',
          width: 60,
          ellipsis: true,
          className: 'hisEndColor',
        },
        {
          title: '欠缓',
          dataIndex: 'SLAB_LACK_NUM',
          key: 'SLAB_LACK_NUM',
          width: 60,
          ellipsis: true,
          className: 'hisEndColor',
        },
        {
          title: '客户名称',
          dataIndex: 'BOI_CUST_CD',
          key: 'BOI_CUST_CD',
          width: 90,
          ellipsis: true,
          className: 'hisEndColor',
        },
        // {
        //   title: '订单用途',
        //   dataIndex: 'BOI_ENDUSE_CD',
        //   key: 'BOI_ENDUSE_CD',
        //   width: 100,
        //   ellipsis: true,
        // },
        {
          title: '订单种类',
          dataIndex: 'BOI_ORD_KND',
          key: 'BOI_ORD_KND',
          width: 90,
          ellipsis: true,
          className: 'hisEndColor',
        },
      ],
    },
    {
      title: '替代前订单',
      dataIndex: 'age3',
      key: 'age3',
      ellipsis: true,
      className: 'hisStColor',
      children: [
        {
          title: '订单号',
          dataIndex: 'BOB_ORD_NO',
          key: 'BOB_ORD_NO',
          width: 110,
          ellipsis: true,
          className: 'hisStColor',
        },
        {
          title: '序列号',
          dataIndex: 'BOB_ORD_ITEM',
          key: 'BOB_ORD_ITEM',
          width: 70,
          ellipsis: true,
          className: 'hisStColor',
        },
        {
          title: '厚度',
          dataIndex: 'BOB_ORD_THK',
          key: 'BOB_ORD_THK',
          width: 60,
          ellipsis: true,
          className: 'hisStColor',
        },
        {
          title: '宽度',
          dataIndex: 'BOB_ORD_WID',
          key: 'BOB_ORD_WID',
          width: 60,
          ellipsis: true,
          className: 'hisStColor',
        },
        {
          title: '长度',
          dataIndex: 'BOB_ORD_LEN',
          key: 'BOB_ORD_LEN',
          width: 60,
          ellipsis: true,
          className: 'hisStColor',
        },
        {
          title: '重量',
          dataIndex: 'BOB_WGT_UNIT',
          key: 'BOB_WGT_UNIT',
          width: 60,
          ellipsis: true,
          className: 'hisStColor',
        },
        {
          title: '客户名称',
          dataIndex: 'BOB_CUST_CD',
          key: 'BOB_CUST_CD',
          width: 90,
          ellipsis: true,
          className: 'hisStColor',
        },
        {
          title: '订单用途',
          dataIndex: 'BOB_ENDUSE_CD',
          key: 'BOB_ENDUSE_CD',
          width: 90,
          ellipsis: true,
          className: 'hisStColor',
        },
        {
          title: '订单种类',
          dataIndex: 'BOB_ORD_KND',
          key: 'BOB_ORD_KND',
          width: 100,
          ellipsis: true,
          className: 'hisStColor',
        },
        {
          title: '表面等级',
          dataIndex: 'GP_SURF_GRD',
          key: 'GP_SURF_GRD',
          width: 90,
          ellipsis: true,
          className: 'hisStColor',
        },
      ],
    },
    {
      title: '用户交货期',
      dataIndex: 'BOI_DEL_FR_DATE',
      key: 'BOI_DEL_FR_DATE',
      width: 100,
      ellipsis: true,
    },
    //{ title: '替代人员', dataIndex: 'SUB_USER', key: 'SUB_USER', width: 100, ellipsis: true },
    {
      title: '替代时间',
      dataIndex: 'DATA_TIME',
      key: 'DATA_TIME',
      width: 100,
      ellipsis: true,
    },
    {
      title: '处理时间',
      dataIndex: 'HAN_DATE',
      key: 'HAN_DATE',
      width: 136,
      ellipsis: true,
    },
    {
      title: '产品备注',
      dataIndex: 'SUR_PRO_REM',
      key: 'SUR_PRO_REM',
      width: 100,
      ellipsis: true,
    },
    { title: '轧制工厂', dataIndex: 'GP_PLT', key: 'GP_PLT', width: 100, ellipsis: true },
    { title: '余材原因', dataIndex: 'CD_NAME', key: 'CD_NAME', width: 100, ellipsis: true },
    { title: '替代块数', dataIndex: 'SUB_NUM', key: 'SUB_NUM', width: 100, ellipsis: true },
    { title: '排列方向', dataIndex: 'SUB_DIR', key: 'SUB_DIR', width: 100, ellipsis: true },
    {
      title: '切割点X坐标',
      dataIndex: 'SUB_CUT_X',
      key: 'SUB_CUT_X',
      width: 100,
      ellipsis: true,
    },
    {
      title: '切割点Y坐标',
      dataIndex: 'SUB_CUT_Y',
      key: 'SUB_CUT_Y',
      width: 100,
      ellipsis: true,
    },
    {
      title: '替代损失重量',
      dataIndex: 'SUB_LOS_WGT',
      key: 'SUB_LOS_WGT',
      width: 100,
      ellipsis: true,
    },
    { title: '是否强制替代', dataIndex: 'SUB_FOR', key: 'SUB_FOR', width: 100, ellipsis: true },
    {
      title: '仓库',
      dataIndex: 'CUR_INV',
      key: 'CUR_INV',
      width: 60,
      ellipsis: true,
    },
    {
      title: '备注原因',
      dataIndex: 'SUR_REM_REA',
      key: 'SUR_REM_REA',
      width: 100,
      ellipsis: true,
    },
    { title: '切边', dataIndex: 'GP_TRIM_FL', key: 'GP_TRIM_FL', width: 50, ellipsis: true },
    { title: '定尺', dataIndex: 'SIZE_KND', key: 'SIZE_KND', width: 50, ellipsis: true },
    { title: '订单备注', dataIndex: 'ORD_REM', key: 'ORD_REM', width: 90, ellipsis: true },
    {
      title: '探伤',
      dataIndex: 'GP_UST_RLT_CD',
      key: 'GP_UST_RLT_CD',
      width: 100,
      ellipsis: true,
    },
    { title: '切割', dataIndex: 'GP_GAS_FL', key: 'GP_GAS_FL', width: 100, ellipsis: true },
    { title: '矫直', dataIndex: 'GP_CL_FL', key: 'GP_CL_FL', width: 100, ellipsis: true },
    { title: '热处理', dataIndex: 'GP_HTM_CNT', key: 'GP_HTM_CNT  ', width: 100, ellipsis: true },
    {
      title: '标识标准',
      dataIndex: 'GP_APLY_STDSPEC',
      key: 'GP_APLY_STDSPEC',
      width: 148,
      ellipsis: true,
    },
    { title: '标识钢种', dataIndex: 'GP_STLGRD', key: 'GP_STLGRD', width: 120, ellipsis: true },
    {
      title: '客户表面要求',
      dataIndex: 'BOI_SURFACE_REQUESTS',
      key: 'BOI_SURFACE_REQUESTS',
      width: 100,
      ellipsis: true,
    },
    {
      title: '加喷内容',
      dataIndex: 'BOI_VESSEL_NO',
      key: 'BOI_VESSEL_NO',
      width: 100,
      ellipsis: true,
    },
    {
      title: '侧喷加喷',
      dataIndex: 'BOI_SIDEMARK',
      key: 'BOI_SIDEMARK',
      width: 100,
      ellipsis: true,
    },
    {
      title: '表喷次数',
      dataIndex: 'BOI_FACEPAINT',
      key: 'BOI_FACEPAINT',
      width: 100,
      ellipsis: true,
    },
    {
      title: '是否钢印',
      dataIndex: 'BOI_SEALMEMO',
      key: 'BOI_SEALMEMO',
      width: 100,
      ellipsis: true,
    },
    {
      title: '钢印加冲',
      dataIndex: 'BOI_SEALMEMO',
      key: 'BOI_SEALMEMO',
      width: 100,
      ellipsis: true,
    },
    {
      title: '综判时间',
      dataIndex: 'BOI_ORD_PROD_END_TIME',
      key: 'BOI_ORD_PROD_END_TIME',
      width: 100,
      ellipsis: true,
    },
    { title: '产品', dataIndex: 'BOI_PROD_CD', key: 'BOI_PROD_CD', width: 100, ellipsis: true },
    // {
    //   title: '替代分类',
    //   dataIndex: 'BOI_DOME_FL',
    //   key: 'BOI_DOME_FL',
    //   width: 100,
    //   ellipsis: true,
    // },
    {
      title: '是否全部替代',
      dataIndex: 'SUB_FULL',
      key: 'SUB_FULL',
      width: 100,
      ellipsis: true,
    },
    {
      title: '替代缺失内容',
      dataIndex: 'SUB_LACK_CON',
      key: 'SUB_LACK_CON',
      width: 165,
      ellipsis: true,
    },
    // {
    //   title: '处理时间',
    //   dataIndex: 'HAN_DATE',
    //   key: 'HAN_DATE',
    //   width: 136,
    //   ellipsis: true,
    // },
    {
      title: '替代人员',
      dataIndex: 'CON_USER',
      key: 'CON_USER',
      width: 100,
      ellipsis: true,
    },
    {
      title: '产品等级',
      dataIndex: 'PROD_GRD',
      key: 'PROD_GRD',
      width: 100,
      ellipsis: true,
    },
    {
      title: '是否接受',
      dataIndex: 'STATE',
      key: 'STATE',
      width: 100,
      ellipsis: true,
    },
    {
      title: '理论替代余材信息',
      dataIndex: 'age4',
      key: 'age4',
      ellipsis: true,
      className: 'sciColor',
      children: [
        {
          title: '厚度',
          dataIndex: 'CUTTING_THK',
          key: 'CUTTING_THK',
          width: 100,
          ellipsis: true,
          className: 'sciColor',
        },
        {
          title: '宽度',
          dataIndex: 'CUTTING_WID',
          key: 'CUTTING_WID',
          width: 100,
          ellipsis: true,
          className: 'sciColor',
        },
        {
          title: '长度',
          dataIndex: 'CUTTING_LEN',
          key: 'CUTTING_LEN',
          width: 100,
          ellipsis: true,
          className: 'sciColor',
        },
        {
          title: '重量',
          dataIndex: 'CUTTING_WGT',
          key: 'CUTTING_WGT',
          width: 100,
          ellipsis: true,
          className: 'sciColor',
        },
      ],
    },
    //理论替代余材信息应为替代时的余材信息
    // {
    //   title: '理论替代余材信息',
    //   dataIndex: 'age4',
    //   key: 'age4',
    //   ellipsis: true,
    //   className: 'sciColor',
    //   children: [
    //     {
    //       title: '厚度',
    //       dataIndex: 'GP_THK',
    //       key: 'GP_THK',
    //       width: 100,
    //       ellipsis: true,
    //       className: 'sciColor',
    //     },
    //     {
    //       title: '宽度',
    //       dataIndex: 'GP_WID',
    //       key: 'GP_WID',
    //       width: 100,
    //       ellipsis: true,
    //       className: 'sciColor',
    //     },
    //     {
    //       title: '长度',
    //       dataIndex: 'GP_LEN',
    //       key: 'GP_LEN',
    //       width: 100,
    //       ellipsis: true,
    //       className: 'sciColor',
    //     },
    //     {
    //       title: '重量',
    //       dataIndex: 'GP_WGT',
    //       key: 'GP_WGT',
    //       width: 100,
    //       ellipsis: true,
    //       className: 'sciColor',
    //     },
    //   ],
    // },
    {
      title: '废钢重量',
      dataIndex: 'STEEL_SCRAP_WGT',
      key: 'STEEL_SCRAP_WGT',
      width: 100,
      ellipsis: true,
    },
    {
      title: '剩余钢板重量',
      dataIndex: 'SUB_PLATE_WGT',
      key: 'SUB_PLATE_WGT',
      width: 120,
      ellipsis: true,
    },
    {
      title: '终结订单',
      dataIndex: 'IS_END',
      key: 'IS_END',
      width: 100,
      ellipsis: true,
    },
    {
      title: '是否分板',
      dataIndex: 'DIVISION',
      key: 'DIVISION',
      width: 100,
      ellipsis: true,
    },
    {
      title: '降级',
      dataIndex: 'DOWN',
      key: 'DOWN',
      width: 100,
      ellipsis: true,
    },
  ];
  const columns1 = [
    {
      title: '序号',
      render: (text: any, record: any, index: any) => <div>{index + 1}</div>,
    },
    {
      title: '钢板号',
      dataIndex: 'PLATE_NO',
      key: 'PLATE_NO',
    },
    {
      title: '钢种',
      dataIndex: 'STLGRD',
      key: 'STLGRD',
    },
    {
      title: '替代日期',
      dataIndex: 'SUPERSED_TIME',
      key: 'SUPERSED_TIME',
    },
    {
      title: '钢板规格',
      dataIndex: 'PLATE_SIZE',
      key: 'PLATE_SIZE',
    },
    {
      title: '钢板重量',
      dataIndex: 'ORD_WGT',
      key: 'ORD_WGT',
    },
    {
      title: '成材率',
      dataIndex: 'YIELD_RATIO',
      key: 'YIELD_RATIO',
    },
    {
      title: '替代率',
      dataIndex: 'AVE_SUP_RATE',
      key: 'AVE_SUP_RATE',
    },
    {
      title: '替代块数',
      dataIndex: 'SUP_NUM',
      key: 'SUP_NUM',
    },
  ];
  // 点击重置按钮
  const handleRest = (): any => {
    form.resetFields();
  };
  const ts = () => {
    message.info('数据查询中,请勿重复点击~', 2);
  };
  const onSearchClick = (): any => {
    setLoading(true);
    const pro = form.getFieldsValue();
    const obj = { START_TIME: begin, END_TIME: end };
    const sd = Object.assign(pro, obj);
    sd.PROC_CD = sd.PROC_CD && sd.PROC_CD.join(',');
    sd.GP_CUR_INV = sd.GP_CUR_INV && sd.GP_CUR_INV.join(',');
    const res = request.post(`/ipdTestApi/getSupersedeConfiram`, sd).then((res) => {
      if (res.data.code == '1' && res.data.data.length !== 0) {
        const result = res.data.data.map((item: any, index: any) => ({
          ...item,
          ID: index,
        }));
        setDataSource(result);
        message.success('数据查询完成！', 1);
        setLoading(false);
      } else {
        setDataSource([]);
        message.warn(res.data.msg);
        setLoading(false);
      }
    });

    //获取趋势分析表格数据
    const res1 = request.post(`/ipdPsApi/getTrendAnalysis`, sd).then((res) => {
      if (res.data.code == '1') {
        const result = res.data.data.map((item: any, index: any) => ({
          ...item,
          ID: index,
        }));
        setDataSource1(result);
      } else {
        setDataSource1([]);
      }
    });
    //const param = form.getFieldsValue();
    //const obj = { START_TIME: begin, END_TIME: end };
    //const sd = Object.assign(pro, obj);
    const hisDataTol = request.post(`/ipdTestApi/GetHisDataTol`, sd).then((res) => {
      if (res.data.code == '1') {
        const xData = res.data.data.map((item: any) => {
          return item.SUB_DATE;
        });
        const yData = res.data.data.map((item: any) => {
          return item.SUB_NUM;
        });
        //替代块数趋势图option
        setNumOption({
          title: {
            left: 'center',
            text: '替代块数变化趋势图',
            textStyle: {
              color: '#ffa218',
              fontSize: 16,
            },
          },
          xAxis: {
            type: 'category',
            data: xData,
            axisLine: {
              show: true,
              symbol: ['none', 'arrow'],
              lineStyle: {
                color: '#1890ff',
                width: 2,
                type: 'solid',
              },
            },
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              label: {
                backgroundColor: '#bbbb15',
              },
            },
          },
          grid: {
            top: '32px',
            left: '32px',
            bottom: '32px',
            right: '32px',
            containLabel: true,
          },
          yAxis: {
            type: 'value',
            axisLabel: {
              formatter: '{value} 块',
            },
            axisLine: {
              show: true,
              symbol: ['none', 'arrow'],
              lineStyle: {
                color: '#1890ff',
                width: 2,
                type: 'solid',
              },
            },
          },
          series: [
            {
              data: yData,
              type: 'line',
            },
          ],
        });
      }
    });
    const hisDataRate = request.post(`/ipdTestApi/GetHisDataRate`, sd).then((res) => {
      if (res.data.code == '1') {
        const xData = res.data.data.map((item: any) => {
          return item.SUB_DATE;
        });
        const yData = res.data.data.map((item: any) => {
          return item.SUB_RATE;
        });
        const minNum = Math.min.apply(null, yData) - 5;
        setRateOption({
          title: {
            left: 'center',
            text: '替代率变化趋势图',
            textStyle: {
              color: '#ffa218',
              fontSize: 16,
            },
          },
          xAxis: {
            type: 'category',
            data: xData,
            axisLine: {
              show: true,
              symbol: ['none', 'arrow'],
              lineStyle: {
                color: '#1890ff',
                width: 2,
                type: 'solid',
              },
            },
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              label: {
                backgroundColor: '#bbbb15',
              },
            },
          },
          grid: {
            top: '32px',
            left: '32px',
            bottom: '32px',
            right: '32px',
            containLabel: true,
          },
          yAxis: {
            type: 'value',
            min: minNum,
            axisLabel: {
              formatter: '{value} %',
            },
            axisLine: {
              show: true,
              symbol: ['none', 'arrow'],
              lineStyle: {
                color: '#1890ff',
                width: 2,
                type: 'solid',
              },
            },
          },
          series: [
            {
              data: yData,
              type: 'line',
            },
          ],
        });
      }
    });
  };

  const onRangeChange = (value: any, dateString: any) => {
    setBegin(dateString[0]);
    setEnd(dateString[1]);
  };

  const { components, resizableColumns, tableWidth, ...others } = useARH({
    columns: useMemo(() => columns, [deps]),
    minConstraints: 50,
  });
  // 点击整行选择
  // const onSelectRow = (record:any) => {
  //   const selectedList = [...selectedRowKeys];
  //   if (selectedList[0] === record.id){
  //     return
  //     selectedList[0] = record.id
  //   }
  //   //setSelectedRows([record])
  //   setSelectedRowKeys(selectedList)
  // }

  return (
    <>
      <Card>
        <Row gutter={[16, 0]}>
          <Col span={24}>
            <Form
              labelCol={{ span: 6 }}
              wrapperCol={{ span: 18 }}
              form={form}
              onFinish={onSearchClick}
            >
              <Collapse defaultActiveKey={['1']}>
                <Panel key="1" header="查询条件" extra={headerButtons()}>
                  <Row gutter={[16, 8]} justify="start" wrap={false}>

                    <Col span={5} style={{ marginLeft: '-18px' }}>
                      <Item label="钢板号" name="PLATE_NO">
                        <Input
                          prefix={<SearchOutlined />}
                          style={{ color: '#ccc', width: 174 }}
                          allowClear
                          defaultValue=""
                          placeholder="请输入"
                        />
                      </Item>
                    </Col>
                    <Col span={4} style={{ marginLeft: '-55px' }}>
                      <Item
                        label="订单号"
                        name="ORD_NO"
                        style={{ marginLeft: '-8px', maxWidth: '232px' }}
                      >
                        <Input
                          prefix={<SearchOutlined />}
                          style={{ color: '#ccc' }}
                          allowClear
                          defaultValue=""
                          placeholder="请输入"
                        />
                      </Item>
                    </Col>

                    <Col span={4}>
                      <Item label="序列号" name="ORD_ITEM" style={{ marginLeft: -44 }}>
                        <Input
                          prefix={<SearchOutlined />}
                          style={{ color: '#ccc', width: 100 }}
                          allowClear
                          defaultValue=""
                          placeholder="请输入"
                        />
                      </Item>
                    </Col>
                    <Col span={5} style={{ marginLeft: '-128px' }}>
                      <Form.Item label="替代时间" name="">
                        <RangePicker
                          onChange={onRangeChange}
                          style={{ width: 226 }}
                          defaultValue={[moment(nowStartDate), moment(nowEndDate)]}
                        />
                      </Form.Item>
                    </Col>
                    <Col span={3} style={{ marginLeft: '-12px' }}>
                      <Item label={`结果`} name="HAN_STATE">
                        <Dictionary
                          style={{ width: 100 }}
                          placeholder="请选择"
                          dict="CLJG"
                          form={form}
                          valueName="HAN_STATE"
                          labelName="HAN_STATE"
                        />
                      </Item>
                    </Col>

                    <Col span={3} style={{ marginLeft: '-68px' }}>
                      <Item
                        label="替代类型"
                        name="IS_FULL"
                        style={{ marginLeft: '26px', width: 300 }}
                      >
                        <Dictionary
                          placeholder="请选择"
                          dict="TDLX"
                          form={form}
                          valueName="IS_FULL"
                          labelName="IS_FULL"
                        />
                      </Item>
                    </Col>
                    <Col span={4}>
                      <Item label="状态" name="PROC_CD" style={{ marginLeft: '-25px' }}>
                        <Select
                          mode="multiple"
                          showArrow={true}
                          placeholder="请选择"
                          value={selectedItems}
                          allowClear
                          onChange={setSelectedItems}
                          style={{ width: '174px' }}
                        >
                          {filteredOptions.map((item) => (
                            <Select.Option key={item} value={item}>
                              {item}
                            </Select.Option>
                          ))}
                        </Select>

                      </Item>
                    </Col>
                  </Row>
                  <Row
                    gutter={[16, 8]}
                    style={{ marginBottom: '-25px', marginTop: -16 }}
                    justify="start"
                  >
                    <Col span={5} style={{ marginLeft: '-18px' }}>
                      <Item label="处理内容" name="HAN_CON">
                        <Input
                          prefix={<SearchOutlined />}
                          style={{ color: '#ccc', width: 174 }}
                          allowClear
                          defaultValue=""
                          placeholder="请输入"
                        />
                      </Item>
                    </Col>
                    <Col span={4} style={{ marginLeft: '-57px' }}>
                      <Item label="仓库" name="GP_CUR_INV" style={{ width: 207 }}>
                        <Select
                          mode="multiple"
                          showArrow={true}
                          placeholder="请选择"
                          value={selectedItems1}
                          allowClear
                          onChange={setSelectedItems1}
                          style={{ width: '100%' }}
                        >
                          {filteredOptions1.map((item: any) => (
                            <Select.Option key={item} value={item}>
                              {item}
                            </Select.Option>
                          ))}
                        </Select>
                      </Item>
                    </Col>

                    <Col span={3} style={{ marginLeft: '-71px' }}>
                      <Item
                        label="是否分板"
                        name="DIVISION"
                        style={{ marginLeft: '26px', width: 300 }}
                      >
                        <Dictionary
                          placeholder="请选择"
                          dict="SFFB"
                          form={form}
                          valueName="DIVISION"
                          labelName="DIVISION"
                        />
                      </Item>
                    </Col>
                  </Row>
                </Panel>
              </Collapse>
            </Form>
          </Col>
        </Row>
      </Card>
      <Card style={{ marginTop: 20 }}>
        <Tabs onChange={onTabChange} defaultActiveKey="1" type="card">
          <TabPane tab="替代历史信息" key="1" forceRender={true}>
            <Table
              bordered
              components={components}
              columns={resizableColumns}
              className={styles.benchtable}
              loading={loading}
              dataSource={dataSource}
              size="small"
              pagination={{ defaultPageSize: 100 }}
              onRow={(record: any) => {
                return {

                };
              }}
              rowSelection={{
                columnWidth: '40px',
                type: 'radio',
                onChange: (selectedRowKeys: any, selectedRows: any) => {
                  setselectedRow(selectedRows), setselectedkey(selectedRowKeys);
                },
              }}
              rowKey="ID"
              scroll={{ x: tableWidth, y: 550 }}
            ></Table>
          </TabPane>
          {/* <TabPane tab="替代趋势分析" key="2" forceRender={true}>
            <Col span={24}>
              <Collapse defaultActiveKey={['1']} expandIconPosition="right">
                <Collapse.Panel header="替代块数" key="1">
                  <Row>
                    <Col span={24}>
                      <div style={{ height: '300px', fontSize: '30px' }}>
                        <ReactEcharts theme="light" option={numOption} />
                      </div>
                    </Col>
                  </Row>
                </Collapse.Panel>
              </Collapse>
            </Col>
            <Col span={24}>
              <Collapse defaultActiveKey={['1']} expandIconPosition="right">
                <Collapse.Panel header="替代率" key="1">
                  <Row>
                    <Col span={24}>
                      <div style={{ height: '300px', fontSize: '30px' }}>
                        <ReactEcharts theme="light" option={rateOption} />
                      </div>
                    </Col>
                  </Row>
                </Collapse.Panel>
              </Collapse>
            </Col>
          </TabPane> */}
        </Tabs>
      </Card>
      <Modal
        title={`【${action}】 `}
        forceRender={true}
        maskClosable={false}
        centered
        width="800px"
        visible={Visible}
        onOk={modalSubmit}
        onCancel={() => {
          setVisible(false);
        }}
      >
        <Form
          form={formData}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 18 }}
          onFinish={(values) => {
            console.log('values', values);
          }}
        >
          <Row gutter={[20, 0]}>
            <Col span={24 / formRow}>
              <Form.Item label="工厂" name="PLT" rules={[{ required: true, message: '必填' }]}>
                <Dictionary
                  placeholder="请输入"
                  dict="B0033"
                  form={formData}
                  valueName="PLT"
                  labelName="PLT"
                />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </>
  );
};
//export default SubHistory;
export default function () {
  return (
    <KeepAlive>
      <SubHistory />
    </KeepAlive>
  );
}
