import { useState, useEffect } from 'react';
import { request } from '@/utils';
import {
  Input,
  Button,
  Row,
  Col,
  Form,
  DatePicker,
  Collapse,
  message,
  Table,
  Space,
  Modal,
  Card,
  Tooltip,
  Select,
} from 'antd';
import {
  CheckCircleOutlined,
  FormOutlined,
  MinusCircleOutlined,
  PlusCircleOutlined,
  PrinterOutlined,
  SearchOutlined,
  UndoOutlined,
  CopyTwoTone,
  ZoomInOutlined,
  SplitCellsOutlined,
  ExclamationCircleOutlined,
  DownloadOutlined,
  CarryOutOutlined,
} from '@ant-design/icons';
import moment from 'moment';
import Dictionary from '@/components/Dictionary';
import { exportTable } from '@/utils/exportTable';
import { KeepAlive } from 'umi'; //从 umi 中导出 KeepAlive，包裹在需要被缓存的组件上
import styles from './index.less';
import { ITableHeader, StudentInfo } from '@/types';
import ResizeTables from '@/components/ResizeTable';
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';

const formRow = 1;
const AlternativeProcess = () => {
  const { Item } = Form;
  const { Panel } = Collapse;
  const nowDate = new Date();
  const nowStartDate = parseInt(
    new Date(nowDate.setDate(nowDate.getDate() - 7)).getTime().toString(),
  ); // 当前时间-1天
  const nowEndDate = parseInt(new Date().getTime().toString()); // 当前时间
  const print = nowDate.toLocaleTimeString();
  const [dataSource, setDataSource] = useState([]);
  const [dataSource2, setDataSource2] = useState([]);
  const [Visible, setVisible] = useState(false);
  const [action, setAction] = useState('');
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [formData] = Form.useForm();
  const [selectedRow, setselectedRow] = useState<any[]>([]);
  const [selectedKey, setselectedkey] = useState(0);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [OPTIONS, setOptions] = useState([]);
  const { RangePicker } = DatePicker;
  const [begin, setBegin] = useState('');
  const [end, setEnd] = useState('');
  const [selectedItems, setSelectedItems] = useState<string[]>([]);
  const filteredOptions = OPTIONS.filter((o) => !selectedItems.includes(o));
  const [arr, setArr] = useState<any[]>([]);
  const [exporting, setExporting] = useState(false);


  //进入页面加载
  useEffect(() => {
    onSearchClick();
  }, []);

  // 导出
  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 names: string[] = [];
    // 用于匹配数据的 keys
    const headerKeys: string[] = [];
    headers.forEach((item) => {
      const columnNumber = getColumnNumber(item.width);
      for (let i = 0; i < columnNumber; i++) {
        names.push(item.header);
        headerKeys.push(item.key);
      }
    });
    // 添加表头
    const rowHeader = worksheet.addRow(names);
    mergeRowCell(headers, rowHeader, worksheet);
    // 设置字体样式
    rowHeader.font = { size: 11, name: '微软雅黑' };
    // 添加数据
    addData2Table(worksheet, headerKeys, headers);
    // 给每列设置固定宽度
    worksheet.columns = worksheet.columns.map((col) => ({ ...col, width: 15 }));
    // 导出
    saveWorkbook(workbook, '库存分析.xlsx');
  }

  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 downloadFile = () => {
    const fileUrl = 'http://172.25.63.218:9088/statics/库存分析.xlsx';
    window.location.href = fileUrl;
  };

  //容器头按钮
  const headerButtons = () => (
    <Space>
      <Button
        type="primary"
        size="small"
        icon={<DownloadOutlined />}
        onClick={(event) => {
          event.stopPropagation();
          // onExportMultiHeaderExcel();
          downloadFile();
        }}
      >
        导出
      </Button>
    </Space>
  );

  const column2s: any = [
    
    { title: '厂别', dataIndex: 'PLT', key: 'PLT', width: 100 },
    { title: '判现', dataIndex: 'PX', key: 'PX', width: 130 },
    { title: '判废', dataIndex: 'PF', key: 'PF', width: 130 },
    { title: '保留', dataIndex: 'BL', key: 'BL', width: 130 },
    { title: '待定', dataIndex: 'DD', key: 'DD', width: 130 },
    ];


  const columns: any = [
    {
      title: '序号',
      dataIndex: 'NO',
      key: 'NO',
      render: (text: any, record: any, index: any) => <div>{index + 1}</div>,
      width: 50,
      fixed: 'left',
    },
    { title: '评估结果', dataIndex: 'INVENTORY_TYPE', key: 'INVENTORY_TYPE', fixed: 'left', width: 75 },
    { title: '半年内可替代次数', dataIndex: 'HALF_NUM', key: 'HALF_NUM', width: 130 },
    { title: '分类', dataIndex: 'TYPE', key: 'TYPE', width: 100 },
    { title: '钢板号', dataIndex: 'PLATE_NO', key: 'PLATE_NO', width: 140 },
    //{ title: '可替代订单', dataIndex: 'ORD_NUMBER', key: 'ORD_NUMBER', width: 200 },
    { title: '轧批号', dataIndex: 'OUT_SHEET_NO', key: 'OUT_SHEET_NO', width: 140 },
    { title: '是否标印', dataIndex: 'MARKING_FL', key: 'MARKING_FL', width: 100 },
    { title: '进程状态', dataIndex: 'PROC_CD', key: 'PROC_CD', width: 100 },
    { title: '客户交货日期', dataIndex: 'DEL_TO_DATE', key: 'DEL_TO_DATE', width: 110 },
    //特殊工艺
    { title: '标准号', dataIndex: 'APLY_STDSPEC', key: 'APLY_STDSPEC', width: 150 },
    { title: '厚度', dataIndex: 'THK', key: 'THK', width: 80 },
    { title: '宽度', dataIndex: 'WID', key: 'WID', width: 80 },
    { title: '长度', dataIndex: 'LEN', key: 'LEN', width: 80 },
    { title: '厚度公差最小值', dataIndex: 'THK_TOL_MIN', key: 'THK_TOL_MIN', width: 120 },
    { title: '厚度公差最大值', dataIndex: 'THK_TOL_MAX', key: 'THK_TOL_MAX', width: 120 },
    { title: '重量', dataIndex: 'WGT', key: 'WGT', width: 100 },
    { title: '过磅重量', dataIndex: 'LOAD_WGT', key: 'LOAD_WGT', width: 100 },
    { title: '产品等级', dataIndex: 'PROD_GRD', key: 'PROD_GRD', width: 100 },
    { title: '表面等级', dataIndex: 'SURF_GRD', key: 'SURF_GRD', width: 100 },
    { title: '试样代码', dataIndex: 'SMP_FL', key: 'SMP_FL', width: 100 },
    { title: '试样号', dataIndex: 'TEST_PIECE_NUMBER', key: 'TEST_PIECE_NUMBER', width: 130 },
    // 试样号状态	  
    { title: '委托单号', dataIndex: 'SMP_SEND_NO', key: 'SMP_SEND_NO', width: 100 },
    { title: '切边代码', dataIndex: 'TRIM_FL', key: 'TRIM_FL', width: 100 },
    { title: '定尺代码', dataIndex: 'SIZE_KND', key: 'SIZE_KND', width: 100 },
    { title: '生产厂', dataIndex: 'PLT', key: 'PLT', width: 100 },
    { title: '生产日期', dataIndex: 'PROD_DATE', key: 'PROD_DATE', width: 100 },
    { title: '轧制日期', dataIndex: 'MILL_END_DATE', key: 'MILL_END_DATE', width: 150 },
    { title: '综判时间', dataIndex: 'AGGREGATE_TIME', key: 'AGGREGATE_TIME', width: 130 },
    { title: '入库日期', dataIndex: 'WAREHOUSE_TIME', key: 'WAREHOUSE_TIME', width: 100 },
    { title: '出库日期', dataIndex: 'OUT_PLT_DATE', key: 'OUT_PLT_DATE', width: 100 },
    { title: '仓库', dataIndex: 'WAREHOUSE', key: 'WAREHOUSE', width: 80 },
    { title: '垛位号', dataIndex: 'LOC', key: 'LOC', width: 100 },
    // 销售方式	
    { title: '订单号', dataIndex: 'ORD_NO', key: 'ORD_NO', width: 150 },
    { title: '订单序列号', dataIndex: 'ORD_ITEM', key: 'ORD_ITEM', width: 100 },
    { title: '原始订单号', dataIndex: 'ORG_ORD_NO', key: 'ORG_ORD_NO', width: 150 },
    { title: '原始订单序列号', dataIndex: 'ORG_ORD_ITEM', key: 'ORG_ORD_ITEM', width: 120 },
    { title: '订单材/余材', dataIndex: 'ORD_FL', key: 'ORD_FL', width: 120 },
    { title: '余材原因代码', dataIndex: 'WOO_RSN', key: 'WOO_RSN', width: 120 },
    { title: '责任单位', dataIndex: 'WOO_RSN_CHG_GRD_DEP', key: 'WOO_RSN_CHG_GRD_DEP', width: 120 },
    // 板坯汇总量	
    // 余材	
    // 订单超量	
    // 设计成材率	
    // 缺陷	
    // 改判缺陷	 
    { title: '喷印', dataIndex: 'JET_PRINTING', key: 'JET_PRINTING', width: 100 },
    { title: '标识次数', dataIndex: 'PAINTNUM', key: 'PAINTNUM', width: 100 },
    { title: '冲印', dataIndex: 'PROCESSING', key: 'PROCESSING', width: 100 },
    { title: '侧喷', dataIndex: 'LATERAL_JET', key: 'LATERAL_JET', width: 100 },
    { title: '订单用途', dataIndex: 'ENDUSE_CD', key: 'ENDUSE_CD', width: 100 },
    { title: '是否保性能', dataIndex: 'IS_PERFORMANCE', key: 'IS_PERFORMANCE', width: 100 },
    { title: '客户', dataIndex: 'CUST_CD', key: 'CUST_CD', width: 100 },
    { title: '客户特殊要求', dataIndex: 'CUST_SPEC_NO', key: 'CUST_SPEC_NO', width: 130 },
    // 作业指示/实绩	
    { title: '切割', dataIndex: 'CUTTING', key: 'CUTTING', width: 100 },
    { title: '矫直', dataIndex: 'STRAIGHTENING', key: 'STRAIGHTENING', width: 100 },
    { title: '抛丸', dataIndex: 'SHOT', key: 'SHOT', width: 100 },
    { title: '热处理', dataIndex: 'HEAT_TREATMENT', key: 'HEAT_TREATMENT', width: 100 },
    // 其他	  VESSEL_NO 字段重复
    { title: '是否已打印质保书', dataIndex: 'CERT_RPT_FL', key: 'CERT_RPT_FL', width: 100 },
    { title: '设定日期', dataIndex: 'PRICE_GRD_DATE', key: 'PRICE_GRD_DATE', width: 100 },
    { title: '设定人员', dataIndex: 'IS_PERSONNEL', key: 'IS_PERSONNEL', width: 100 },
    // 标识	
    { title: '钢种', dataIndex: 'STLGRD', key: 'STLGRD', width: 120 },
    { title: '认证标识', dataIndex: 'R_IDENT', key: 'R_IDENT', width: 100 },
    { title: '加喷内容', dataIndex: 'VESSEL_NO', key: 'VESSEL_NO', width: 150 },
    { title: '侧喷加喷', dataIndex: 'SIDEMARK', key: 'SIDEMARK', width: 150 },
    { title: '冲印加喷', dataIndex: 'SEALMEMO', key: 'SEALMEMO', width: 100 },
    { title: '订单备注', dataIndex: 'BEIZHU_MEMO', key: 'BEIZHU_MEMO', width: 100 },
    { title: '尺寸是否合格', dataIndex: 'INSP_WGT_GRD', key: 'INSP_WGT_GRD', width: 110 },
    { title: '寄仓时间', dataIndex: 'BAOXIN_IF_DATE', key: 'BAOXIN_IF_DATE', width: 100 },
    { title: '订单规格', dataIndex: 'SPECIFICATION', key: 'SPECIFICATION', width: 150 },
    { title: '订单宽度', dataIndex: 'ORD_WID', key: 'ORD_WID', width: 100 },
    { title: '订单厚度', dataIndex: 'ORD_THK', key: 'ORD_THK', width: 100 },
    { title: '订单长度', dataIndex: 'ORD_LEN', key: 'ORD_LEN', width: 100 },
    // 是否单排道	 
    //{ title: '板坯切割指示', dataIndex: 'PLAN_SLAB_CUT_FL', key: 'PLAN_SLAB_CUT_FL', width: 100 },
    //{ title: '切割块数', dataIndex: 'PLAN_SLAB_CUT_CNT', key: 'PLAN_SLAB_CUT_CNT', width: 100 },
    { title: '轧制工厂', dataIndex: 'PLT', key: 'PLT', width: 100 },
    { title: '订单投入日期', dataIndex: 'RELEASE_DATE', key: 'RELEASE_DATE', width: 120 },
    // 是否零散订单	 
    { title: '否紧急订单', dataIndex: 'URGNT_FL', key: 'URGNT_FL', width: 100 },
    // 未处理天数	 
    { title: '重点合同', dataIndex: 'IMP_CONT', key: 'IMP_CONT', width: 100 },
    { title: '订单轧制工厂', dataIndex: 'CFM_MILL_PLT', key: 'CFM_MILL_PLT', width: 120 },
    // 原始交货期	 
    { title: '控制号', dataIndex: 'CR_CD', key: 'CR_CD', width: 100 },
    { title: '试样备注', dataIndex: 'SAMPLE_MEMO', key: 'SAMPLE_MEMO', width: 100 },
    { title: '尺寸备注', dataIndex: 'SIZE_MEMO', key: 'SIZE_MEMO', width: 100 },
    { title: '打包备注', dataIndex: 'PACK_MEMO', key: 'PACK_MEMO', width: 100 },
    { title: '表面客户要求', dataIndex: 'SURFACE_REQUESTS', key: 'SURFACE_REQUESTS', width: 120 },
    { title: '长度公差上限', dataIndex: 'LEN_UP', key: 'LEN_UP', width: 120 },
    { title: '长度公差下限', dataIndex: 'LEN_DOWN', key: 'LEN_DOWN', width: 120 },
    { title: '下限', dataIndex: 'CAL_FLOOR', key: 'CAL_FLOOR', width: 100 },
    { title: '钢板不平度1', dataIndex: 'FLT_UNIT_MAX', key: 'FLT_UNIT_MAX', width: 100 },
    { title: '测量长度1', dataIndex: 'FLT_LEN', key: 'FLT_LEN', width: 100 },
    { title: '钢板不平度2', dataIndex: 'FLT_UNIT_MAX2', key: 'FLT_UNIT_MAX2', width: 100 },
    { title: '测量长度2', dataIndex: 'FLT_LEN2', key: 'FLT_LEN2', width: 100 },
    { title: '客户分类', dataIndex: 'CUST_CLASS', key: 'CUST_CLASS', width: 100 },
    { title: '客户分级', dataIndex: 'CUST_LEVEL', key: 'CUST_LEVEL', width: 100 },
    { title: '宽度公差上限', dataIndex: 'WID_UP', key: 'WID_UP', width: 120 },
    { title: '宽度公差下限', dataIndex: 'WID_DOWN', key: 'WID_DOWN', width: 120 },
    { title: '特殊作业要求', dataIndex: 'SPECIAL_OPR_REQ', key: 'SPECIAL_OPR_REQ', width: 120 },
    //{ title: '板坯钢种', dataIndex: 'FP_STLGRD', key: 'FP_STLGRD', width: 100 },
    { title: '钢板性能', dataIndex: 'GP_PERFORMANCE', key: 'CUSTGP_PERFORMANCE_LEVEL', width: 100 },
    { title: '移垛时间', dataIndex: 'GPYD_UPD_DATE', key: 'GPYD_UPD_DATE', width: 150 },
    { title: '移跺人员', dataIndex: 'GPYD_UPD_EMP_CD', key: 'GPYD_UPD_EMP_CD', width: 100 },
    // 非计划	
    // 改判分类	 
    // 钢板剪切时间	
    { title: '最后表判人员', dataIndex: 'EMP_CD1', key: 'EMP_CD1', width: 120 },
    // 轧制标准	
    // 剪切班别	
    // 轧制坯重量	
    // 检验确认时间	 
    { title: '质保书编号', dataIndex: 'CERT_RPT_NO', key: 'CERT_RPT_NO', width: 100 },
    // 热处理工艺	
    // 余材单位	
    // 转库时间	
    // 船期	
    // 异常坯	
    // 首次降级时间	
    // 是否加严探伤	
    // 加严探伤代码	
    // 热处理工厂	
    // 热处理时间	
    // 是否超期	 
    //{ title: '标识标准', dataIndex: 'APLY_STDSPEC', key: 'APLY_STDSPEC', width: 150 },
    // 取样方式	
    // 取样重量	 
    { title: '钢板喷涂', dataIndex: 'STEEL_SPRAY', key: 'STEEL_SPRAY', width: 100 },
    { title: '钢板抛丸', dataIndex: 'STEEL_SHOTBLAST', key: 'STEEL_SHOTBLAST', width: 100 },
    // 钢板打破口	 
    { title: '钢板打包', dataIndex: 'STEEL_PACK', key: 'STEEL_PACK', width: 100 },
    { title: '录入时间', dataIndex: 'INS_DATE', key: 'INS_DATE', width: 150 },

  ];

  // 统一设置 ellipsis 为 true
  columns.forEach((column: any) => {
    column.ellipsis = true;
  });

   // 统一设置 ellipsis 为 true
   column2s.forEach((column: any) => {
    column.ellipsis = true;
  });

  const onRangeChange = (value: any, dateString: any) => {
    setBegin(dateString[0]);
    setEnd(dateString[1]);
  };
  // 点击重置按钮
  const handleRest = (): any => {
    form.resetFields();
  };
  // 查询
  const onSearchClick = (): any => {
    setLoading(true);
    const pro = form.getFieldsValue();
    const obj = { START_TIME: begin, END_TIME: end };
    const sd = Object.assign(pro, obj);

    const res = request.post(`/ipdPsApi/GetTB_INVENTORY_ANALYSIS`, sd).then((res) => {
      if (res.data.code == '1') {
        const result = res.data.data.map((item: any, index: any) => ({
          ...item,
          PK: index,
        }));
        setDataSource(result);
        setLoading(false);
      } else {
        setDataSource([]);
        setLoading(false);
      }
    });

    const res2 = request.post(`/ipdPsApi/GetTB_INVENTORY_ANALYSIS_TOTAL`, sd).then((res2) => {
      if (res2.data.code == '1') {
        const result = res2.data.data.map((item: any, index: any) => ({
          ...item,
          PK: index,
        }));
        setDataSource2(result);
        setLoading(false);
      } else {
        setDataSource2([]);
        setLoading(false);
      }
    });

  };

  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]} style={{ marginBottom: '-25px' }}>
                    
                    <Col xs={24} sm={12} md={8} lg={6} xl={3}>
                      <Item
                        label="钢板号"
                        name="PLATE_NO"
                      >
                        <Input
                          prefix={<SearchOutlined />}
                          style={{ color: '#ccc' }}
                          allowClear
                          defaultValue=""
                          placeholder="请输入"
                        />
                      </Item>
                    </Col> 
                    <Col xs={24} sm={12} md={8} lg={6} xl={2}>
                      <Item
                        label="工厂"
                        name="PLT"
                      >
                        <Dictionary
                          placeholder="请选择"
                          style={{ color: '#ccc',with:'100%' }}
                          dict="B0033"
                          form={form}
                          valueName="PLT"
                          labelName="PLT"
                        />
                      </Item>
                    </Col> 
                    {/* <Col xs={24} sm={12} md={8} lg={6} xl={4}>
                      <Form.Item label="录入时间" name="">
                        <RangePicker
                          onChange={onRangeChange}
                          // style={{ width: '226px' }}
                          defaultValue={[moment(nowStartDate), moment(nowEndDate)]}
                        />
                      </Form.Item>
                    </Col> */}
                    <Col xs={24} sm={12} md={8} lg={6} xl={4}>
                      <Item
                        label="评估结果"
                        name="INVENTORY_TYPE"
                      >
                        <Dictionary
                          placeholder="请选择"
                          style={{ color: '#ccc',with:'100%' }}
                          dict="PGJG"
                          form={form}
                          valueName="INVENTORY_TYPE"
                          labelName="INVENTORY_TYPE"
                        />
                      </Item>
                    </Col>
                    <Col style={{ position: 'absolute', right: 25 }}>
                      <Space size={12} align="start">
                        <Button htmlType="submit" type="primary" icon={<SearchOutlined />}>
                          查询
                        </Button>
                        <Button danger onClick={handleRest} icon={<UndoOutlined />}>
                          重置
                        </Button>
                      </Space>
                    </Col>
                  </Row>
                </Panel>
              </Collapse>
            </Form>
          </Col>
        </Row>
      </Card>

 

      <Card style={{ marginTop: 20 }}>
        <Table
          bordered
          className={styles.benchtable}
          columns={columns}
          loading={loading}
          dataSource={dataSource}
          size="small"
          pagination={{ defaultPageSize: 50 }}
          onRow={(record: any) => {
            return {
              onClick: (event: any) => {
                event.currentTarget.getElementsByTagName('label')[0].click();
              },
            };
          }}
          // rowSelection={{
          //   columnWidth: '60px',
          //   onChange: (selectedRowKeys: any, selectedRows: any) => {
          //     setSelectedRowKeys(selectedRowKeys), setselectedRow(selectedRows);
          //   },
          //   selectedRowKeys,
          // }}
          rowKey={(record: any) => record.PLATE_NO}
          scroll={{
            y: 480,
            x: 100,
          }}
        ></Table>
      </Card>
      <Card style={{ marginTop: 20 }}>
        <ResizeTables
          bordered
          className={styles.benchtable}
          columns={column2s}
          loading={loading}
          dataSource={dataSource2}
          size="small"
          pagination={{ defaultPageSize: 50 }}
          onRow={(record: any) => {
            return {
              onClick: (event: any) => {
                event.currentTarget.getElementsByTagName('label')[0].click();
              },
            };
          }}
          // rowSelection={{
          //   columnWidth: '60px',
          //   onChange: (selectedRowKeys: any, selectedRows: any) => {
          //     setSelectedRowKeys(selectedRowKeys), setselectedRow(selectedRows);
          //   },
          //   selectedRowKeys,
          // }}
          rowKey={(record: any) => record.PLATE_NO}
          scroll={{
            y: 480,
            x: 100,
          }}
        ></ResizeTables>
      </Card>
    </>
  );
};
export default function () {
  return (
    <KeepAlive>
      <AlternativeProcess />
    </KeepAlive>
  );
}
