import { connect } from "umi";
import type { ConnectState } from "@/models/connect";
import { Button, Descriptions, FormInstance, Modal } from "antd";
import { useRef, useState } from "react";
import React from "react";
import Draggable from "react-draggable";
import ProTable, { ActionType } from "@ant-design/pro-table";
import { handleGetBACKCOMMODITYDetail, handleGetBACKCOMMODITYList, handleGetSALESTOREPROINSTDetail } from "../../service";
import { handleNewPrint, handleNewPrintAHJG } from "@/utils/format";
import { highlightText } from "@/utils/highlightText";

type DetailProps = {
    showDetail: boolean;
    parentRow: any;
    onCencel: any;
    searchParams?: any
}
const ReturnGoodsTable = ({ showDetail, parentRow, onCencel, searchParams }: DetailProps) => {
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();
    const draggleRef = React.createRef<any>()

    // 弹出框拖动效果
    const [bounds, setBounds] = useState<{ left: number, right: number, top: number, bottom: number }>() // 移动的位置
    const [disabled, setDraggleDisabled] = useState<boolean>() // 是否拖动
    const onDraggaleStart = (event, uiData) => {
        const { clientWidth, clientHeight } = window.document.documentElement;
        const targetRect = draggleRef.current?.getBoundingClientRect();
        if (!targetRect) {
            return;
        }
        setBounds({
            left: -targetRect.left + uiData.x,
            right: clientWidth - (targetRect.right - uiData.x),
            top: -targetRect.top + uiData.y,
            bottom: clientHeight - (targetRect.bottom - uiData.y),
        });
    };
    // 当前查到的退货单详情
    const [currentModalDetail, setCurrentModalDetail] = useState<any>()

    const columns: any = [
        {
            title: "序号",
            width: 80,
            valueType: 'index',
            dataIndex: "index",
            align: 'center'
        },
        {
            title: "商品条码",
            width: 120,
            dataIndex: "COMMODITY_BARCODE",
            align: 'center',
            ellipsis: true,
            render: (_, record) => {
                return highlightText(record?.COMMODITY_BARCODE, searchParams?.searchText)
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>商品名称</div>,
            width: 250,
            dataIndex: "COMMODITY_NAME",
            align: 'left',
            ellipsis: true,
            render: (_, record) => {
                return highlightText(record?.COMMODITY_NAME, searchParams?.searchText)
            }
        },
        {
            title: '退货门店',
            width: 150,
            dataIndex: "SHOPNAME",
            align: 'center',
            ellipsis: true
        },
        {
            title: <div style={{ textAlign: 'center' }}>供应商名</div>,
            width: 250,
            dataIndex: "SUPPLIER_NAME",
            align: 'left',
            ellipsis: true
        },
        {
            title: <div style={{ textAlign: 'center' }}>退货数量</div>,
            width: 100,
            dataIndex: "BACK_COUNT",
            valueType: 'digit',
            align: 'right',
            ellipsis: true
        },
        {
            title: <div style={{ textAlign: 'center' }}>税率</div>,
            width: 100,
            dataIndex: "DUTY_PARAGRAPH",
            align: 'right',
            ellipsis: true
        },
        {
            title: <div style={{ textAlign: 'center' }}>含税进价</div>,
            width: 100,
            dataIndex: "PURCHASE_TAXPRICE",
            valueType: 'digit',
            align: 'right',
            ellipsis: true
        },
        {
            title: <div style={{ textAlign: 'center' }}>含税金额</div>,
            width: 100,
            dataIndex: "BACKTAXPRICE",
            valueType: 'digit',
            align: 'right',
            ellipsis: true
        },
        {
            title: '退货时间',
            width: 150,
            dataIndex: "BACK_DATE",
            align: 'center',
            ellipsis: true
        },
        {
            title: <div style={{ textAlign: 'center' }}>退货原由</div>,
            width: 250,
            dataIndex: "BACK_DESC",
            align: 'left',
            ellipsis: true
        }
    ]

    return (
        <div>
            <Modal
                title={
                    <div
                        className="returnGoodsTableTitle"
                        style={{
                            width: '100%',
                            cursor: 'move',
                        }}
                        onMouseOver={() => {
                            if (disabled) {
                                setDraggleDisabled(false)
                            }
                        }}
                        onMouseOut={() => {
                            setDraggleDisabled(true)
                        }}

                        onFocus={() => { }}
                        onBlur={() => { }}
                    >退货表单</div>
                }
                destroyOnClose={true}
                width={'80%'}
                bodyStyle={{
                    height: '700px', // 你可以根据需要调整高度
                    overflowY: 'auto',
                }}
                visible={showDetail}
                onCancel={() => {
                    if (onCencel) {
                        onCencel()
                    }
                }}
                footer={false}
                modalRender={(modal) => {
                    return <Draggable
                        disabled={disabled}
                        bounds={bounds}
                        onStart={(event, uiData) => onDraggaleStart(event, uiData)}
                        handle=".returnGoodsTableTitle"
                    >
                        <div ref={draggleRef}>{modal}</div>
                    </Draggable>
                }}
            >
                <div style={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'flex-end', boxSizing: 'border-box', padding: '0 24px' }}>
                    <Button type={'primary'} onClick={() => {
                        const printName: string = `${parentRow?.DEPT_NAME || ''}自采退货单`;

                        // 获取页面所有样式
                        const styles = Array.from(document.styleSheets)
                            .map((sheet: any) =>
                                Array.from(sheet.cssRules || []).map((rule: any) => rule.cssText).join('\n')
                            )
                            .join('\n');

                        // 克隆表格 DOM
                        const originalTable: any = document.getElementsByClassName('returnGoodsTable')[0];
                        const clonedTable = originalTable.cloneNode(true) as HTMLElement;
                        clonedTable.style.display = 'block';

                        // 🔧 移除测量行（解决间距问题）
                        const measureRows = clonedTable.querySelectorAll('.ant-table-measure-row');
                        measureRows.forEach(row => row.remove());

                        // 保持你原有的字体设置
                        const setFontSizeRecursively = (element: HTMLElement) => {
                            element.style.fontSize = '10px';
                            element.style.padding = '4px';
                            Array.from(element.children).forEach((child) =>
                                setFontSizeRecursively(child as HTMLElement)
                            );
                        };
                        const tableCells = clonedTable.querySelectorAll('thead th, tbody td, tfoot td');
                        tableCells.forEach((cell) => setFontSizeRecursively(cell as HTMLElement));

                        // 获取克隆后的 HTML 内容
                        const clonedHTML = clonedTable.getElementsByClassName('ant-table')[0].innerHTML;

                        // 页眉（标题 + 描述）
                        let neckList: any = [
                            { label: "退货单号", value: parentRow?.ACCEPT_CODE || '' },
                            { label: "退货数量", value: parentRow?.OPERATE_COUNT || '' },
                            { label: "退货金额", value: parentRow?.OPERATE_TAXAMOUNT || '' },
                            { label: "申请人员", value: parentRow?.STAFF_NAME || '' },
                            { label: "退货说明", value: parentRow?.PROINST_DESC || '' },
                        ];

                        // 🔧 只添加这些：测量行隐藏 + 宽度自适应 + 水平居中
                        const fineBorderStyles = `
      @media print {
          /* 1. 隐藏测量行 */
          .ant-table-measure-row { 
              display: none !important; 
              height: 0 !important; 
          }
          
          /* 2. 表格宽度自适应 + 水平居中 */
          .handlePrintBox .tableBox {
              width: auto !important;
              max-width: 100% !important;
              margin: 0 auto !important;
          }
          
          .handlePrintBox .tableBox table {
              width: auto !important;
              max-width: 100% !important;
              table-layout: auto !important;
              margin: 0 auto !important;
              position: relative !important;
              left: 50% !important;
              transform: translateX(-50%) !important;
          }
          
          /* 3. 精细边框统一 - 使用1px避免过粗 */
          .handlePrintBox .tableBox table {
              border-collapse: separate !important;
              border-spacing: 0 !important;
              border: 1px solid #000 !important;
          }
          
          /* 精确控制每个边框 - 统一使用1px */
          .handlePrintBox .tableBox .ant-table-thead tr th {
              border: 1px solid #000 !important;
              border-bottom: 1px solid #000 !important;
              border-right: 1px solid #000 !important;
              background-color: transparent !important;
              margin: 0 !important;
              padding: 4px !important;
          }
          
          .handlePrintBox .tableBox .ant-table-tbody tr td {
              border: 1px solid #000 !important;
              border-right: 1px solid #000 !important;
              border-bottom: 1px solid #000 !important;
              margin: 0 !important;
              padding: 4px !important;
          }
          
          /* 边框连接处统一 - 都使用1px */
          .handlePrintBox .tableBox .ant-table-thead tr:first-child th {
              border-top: 1px solid #000 !important;
          }
          
          .handlePrintBox .tableBox .ant-table-thead tr th:first-child,
          .handlePrintBox .tableBox .ant-table-tbody tr td:first-child {
              border-left: 1px solid #000 !important;
          }
          
          .handlePrintBox .tableBox .ant-table-thead tr th:last-child,
          .handlePrintBox .tableBox .ant-table-tbody tr td:last-child {
              border-right: 1px solid #000 !important;
          }
          
          .handlePrintBox .tableBox .ant-table-tbody tr:last-child td {
              border-bottom: 1px solid #000 !important;
          }
          
          /* 4. 页边距优化 */
          @page {
              margin: 10mm auto !important;
              size: A4 landscape;
          }
      }
  `;

                        // 合并样式
                        const combinedStyles = styles + fineBorderStyles;

                        // 调用原有打印方法
                        handleNewPrintAHJG(printName, `${parentRow?.DEPT_NAME || ''}自采退货单`, neckList, combinedStyles, clonedHTML, '');
                        console.log('parentRowparentRowparentRow', parentRow);

                    }}>
                        打印退货单
                    </Button>
                </div>

                <div style={{ width: "100%", display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: "24px", fontWeight: 500 }}>
                    {`${parentRow?.DEPT_NAME}自采退货单`}
                </div>

                <ProTable
                    actionRef={actionRef}
                    className="returnGoodsTable"
                    formRef={formRef}
                    bordered
                    search={false}
                    pagination={false}
                    columns={columns}
                    options={false}
                    scroll={{ x: "100%" }}
                    request={async () => {
                        console.log('parentRow', parentRow);
                        if (!parentRow?.SALESTOREPROINST_ID) {
                            return
                        }

                        const req: any = {
                            SearchParameter: {
                                SALESTOREPROINST_IDS: parentRow?.SALESTOREPROINST_ID,
                            },
                            PageIndex: 1,
                            PageSize: 999999
                        }

                        const data = await handleGetBACKCOMMODITYList(req)
                        console.log('退货单详情', data);
                        if (data && data.length > 0) {
                            return { data, success: true }
                        }
                        return { data: [], success: true }
                    }}
                    tableExtraRender={(_, data) => {
                        return <div style={{ width: '100%', boxSizing: 'border-box', padding: '24px' }}>
                            <Descriptions
                                size="small" column={4}
                                className="commity-sale-description"
                                contentStyle={{ fontWeight: "bolder" }} labelStyle={{ color: "#00000073" }}
                            >
                                <Descriptions.Item label="退货单号">{parentRow?.ACCEPT_CODE || ""}</Descriptions.Item>
                                <Descriptions.Item label="退货数量">{parentRow?.OPERATE_COUNT || ""}</Descriptions.Item>
                                <Descriptions.Item label="退货金额">{parentRow?.OPERATE_TAXAMOUNT || ""}</Descriptions.Item>
                                <Descriptions.Item label="申请人员">{parentRow?.STAFF_NAME || ""}</Descriptions.Item>

                                <Descriptions.Item label="退货说明">{parentRow?.PROINST_DESC || ""}</Descriptions.Item>
                            </Descriptions>
                        </div>
                    }}
                />
            </Modal >
        </div >
    )
}

export default connect(({ user, }: ConnectState) => ({
    currentUser: user.currentUser,
}))(ReturnGoodsTable);
