import React, { Fragment, PureComponent } from 'react';
import {
    DeleteOutlined,
    EditOutlined,
    PlusOutlined,
    SearchOutlined,
    RedoOutlined,
    DownOutlined,
    ExclamationCircleFilled,
    UpOutlined,
} from '@ant-design/icons';
import { connect, history } from '@umijs/max';
import { Button, Input, Card, Divider, Dropdown, message, Modal, Popconfirm, Space, Switch, Tag, Row, Col, Table } from 'antd';
const { TextArea } = Input;
import StandardTable from '@/components/StandardTable';

import { MyIcon } from "@/components/Icon"
import style from "@/global.less";
import TimeSheetCreateForm from './form/TimeSheetCreateForm'; //新增表单
import TimeSheetUpdateForm from './form/TimeSheetUpdateForm'; //修改表单
import TimeSheetViewForm from './form/TimeSheetViewForm'; //查看表单
import TimeSheetRenderSimpleForm from './form/TimeSheetRenderSimpleForm'; //简单查询表单
import TimeSheetRenderAdvancedForm from './form/TimeSheetRenderAdvancedForm'; //高级查询表单
import styles from './TimeSheetList.less';
import datadictionary from "@/utils/dataDictionary";
import { formatDate } from "@/utils/formatUtils";
import { formatDictText, checkButtonAuthority } from "@/utils/globalCommon";
import { globalPrompts } from "@/utils/globalPrompts";

const { confirm } = Modal;

//预约类型
const sex_type = datadictionary.sex
const user_status = datadictionary.user_status
const sys_user_post = datadictionary.sys_user_post

const mockData = {
    list: [
        {
            ygh: "A00001",
            xm: "员工1",
            rq: "2025/6/10",
            dw: "清河中医院",
            bm: "心内科",
            kqsc: 8,
            zysc: 7,
            kxsc: 1,
        },
        {
            ygh: "A00002",
            xm: "员工2",
            rq: "2025/6/10",
            dw: "清河中医院",
            bm: "心外科",
            kqsc: 8,
            zysc: 6,
            kxsc: 2,
        },
        {
            ygh: "A00003",
            xm: "员工3",
            rq: "2025/6/10",
            dw: "清河中医院",
            bm: "康复科",
            kqsc: 8,
            zysc: 8,
            kxsc: 0,
        },
        {
            ygh: "A00004",
            xm: "员工4",
            rq: "2025/6/10",
            dw: "清河中医院",
            bm: "心内科",
            kqsc: 8,
            zysc: 7,
            kxsc: 1,
        },
        {
            ygh: "A00005",
            xm: "员工5",
            rq: "2025/6/10",
            dw: "清河中医院",
            bm: "心外科",
            kqsc: 8,
            zysc: 6,
            kxsc: 2,
        },
        {
            ygh: "A00006",
            xm: "员工6",
            rq: "2025/6/10",
            dw: "清河中医院",
            bm: "康复科",
            kqsc: 8,
            zysc: 8,
            kxsc: 0,
        },
        {
            ygh: "A00007",
            xm: "员工7",
            rq: "2025/6/10",
            dw: "清河中医院",
            bm: "心内科",
            kqsc: 8,
            zysc: 7,
            kxsc: 1,
        },
        {
            ygh: "A00008",
            xm: "员工8",
            rq: "2025/6/10",
            dw: "清河中医院",
            bm: "心外科",
            kqsc: 8,
            zysc: 6,
            kxsc: 2,
        },
        {
            ygh: "A00009",
            xm: "员工9",
            rq: "2025/6/10",
            dw: "清河中医院",
            bm: "康复科",
            kqsc: 8,
            zysc: 8,
            kxsc: 0,
        },
        {
            ygh: "A000010",
            xm: "员工10",
            rq: "2025/6/10",
            dw: "清河中医院",
            bm: "心内科",
            kqsc: 8,
            zysc: 7,
            kxsc: 1,
        },
        {
            ygh: "A000011",
            xm: "员工11",
            rq: "2025/6/10",
            dw: "清河中医院",
            bm: "心外科",
            kqsc: 8,
            zysc: 6,
            kxsc: 2,
        },
        {
            ygh: "A000012",
            xm: "员工12",
            rq: "2025/6/10",
            dw: "清河中医院",
            bm: "康复科",
            kqsc: 8,
            zysc: 8,
            kxsc: 0,
        },
        {
            ygh: "A000013",
            xm: "员工13",
            rq: "2025/6/10",
            dw: "清河中医院",
            bm: "心内科",
            kqsc: 8,
            zysc: 7,
            kxsc: 1,
        },
        {
            ygh: "A000014",
            xm: "员工14",
            rq: "2025/6/10",
            dw: "清河中医院",
            bm: "心外科",
            kqsc: 8,
            zysc: 6,
            kxsc: 2,
        },
        {
            ygh: "A000015",
            xm: "员工15",
            rq: "2025/6/10",
            dw: "清河中医院",
            bm: "康复科",
            kqsc: 8,
            zysc: 8,
            kxsc: 0,
        },
        {
            ygh: "A000016",
            xm: "员工16",
            rq: "2025/6/10",
            dw: "清河中医院",
            bm: "心内科",
            kqsc: 8,
            zysc: 7,
            kxsc: 1,
        },
        {
            ygh: "A000017",
            xm: "员工17",
            rq: "2025/6/10",
            dw: "清河中医院",
            bm: "心外科",
            kqsc: 8,
            zysc: 6,
            kxsc: 2,
        },
        {
            ygh: "A000018",
            xm: "员工18",
            rq: "2025/6/10",
            dw: "清河中医院",
            bm: "康复科",
            kqsc: 8,
            zysc: 8,
            kxsc: 0,
        },
        {
            ygh: "A000019",
            xm: "员工19",
            rq: "2025/6/10",
            dw: "清河中医院",
            bm: "心内科",
            kqsc: 8,
            zysc: 7,
            kxsc: 1,
        },
        {
            ygh: "A000020",
            xm: "员工20",
            rq: "2025/6/10",
            dw: "清河中医院",
            bm: "心外科",
            kqsc: 8,
            zysc: 6,
            kxsc: 2,
        }
    ],
    pagination: {},
}
@connect(({ timesheet, loading }) => ({
    timesheet,
    loading: loading.models.timesheet,
}))

class TimeSheetList extends PureComponent {
    state = {
        modalVisible: false,
        updateModalVisible: false,
        viewModalVisible: false,
        expandForm: false,
        selectedRows: [],
        formValues: {},
        updateFormValues: {},
        viewFormValues: {},
        toggleExpand: false,
        selectedFile: null,
        fileName: '',
        apiResponseData: null,
        apiResponseStatus: '未调用',
        apiResponseError: null,
        loading: false, // 用于控制加载动画的状态
        reviewPrompt: globalPrompts.pdfReviewPrompt, // 从全局配置获取初始审阅提示词
    }

    columns = [
        {
            title: '序号',
            dataIndex: 'index',
            key: 'index',
            width: 50,
            fixed: 'left',
            render: (_, record, index) => index + 1,
        },
        {
            title: '员工号',
            dataIndex: 'ygh',
            key: 'ygh',
            width: 100,
            fixed: 'left',
        }, {
            title: '姓名',
            dataIndex: 'xm',
            key: 'xm',
            width: 100,
            fixed: 'left',
        }, {
            title: '日期',
            dataIndex: 'rq',
            key: 'rq',
            width: 100,
        }, {
            title: '单位',
            dataIndex: 'dw',
            key: 'dw',
            width: 150,
        }, {
            title: '部门',
            dataIndex: 'bm',
            key: 'bm',
            width: 150,
        }, {
            title: '考勤时长',
            dataIndex: 'kqsc',
            key: 'kqsc',
            width: 100,
        }, {
            title: '作业时长',
            dataIndex: 'zysc',
            key: 'zysc',
            width: 100,
        },
        {
            title: '空闲时长',
            dataIndex: 'kxsc',
            key: 'kxsc',
            width: 100,
        },
        {
            title: '比例图',
            dataIndex: 'blt',
            key: 'blt',
            width: 150,
            render: (text, record) => {
                let workRatio = record.zysc / (record.zysc + record.kxsc) * 100
                return (
                    <Fragment>
                        <div style={{ display: 'flex' }}>
                            <div style={{ height: 30, width: workRatio + '%', background: "#8ddd15" }}></div>
                            <div style={{ height: 30, width: 100 - workRatio + '%', background: "#cccccc" }}></div>
                        </div>
                    </Fragment>
                )
            },
        },
    ]

    componentDidMount() {
        // 调用指定接口
        // this.fetchRunCheckDocData();
        
        // 从localStorage读取保存的审阅提示词
        const savedPrompt = localStorage.getItem('pdfReviewPrompt');
        if (savedPrompt) {
            this.setState({ reviewPrompt: savedPrompt });
        }
        
        // 优先检查localStorage中的document_update_data
        const savedUpdateData = localStorage.getItem('document_update_data');
        if (savedUpdateData) {
            try {
                const parsedData = JSON.parse(savedUpdateData);
                if (Array.isArray(parsedData) && parsedData.length > 0) {
                    // 转换document_update_data格式为表格需要的格式
                    const formattedData = {
                        data: JSON.stringify(parsedData.map(item => ({
                            context: item.original || '无原文',
                            update: item.modified || '无修改建议'
                        })))
                    };
                    
                    this.setState({
                        apiResponseData: formattedData,
                        apiResponseStatus: '已从本地更新数据加载',
                        apiResponseError: null
                    });
                    console.log('已从本地加载document_update_data数据');
                    return; // 已找到更新数据，不再检查其他数据
                }
            } catch (error) {
                console.error('解析本地保存的document_update_data失败:', error);
            }
        }
        
        // 如果没有找到document_update_data，则检查document_review_data
        const savedReviewData = localStorage.getItem('document_review_data');
        if (savedReviewData) {
            try {
                const parsedData = JSON.parse(savedReviewData);
                // 确保数据格式正确 - 从之前保存的结构中提取data字段
                const dataToShow = parsedData && parsedData.data ? parsedData : {
                    data: savedReviewData // 如果没有data字段，可能是之前直接保存的完整数据
                };
                
                this.setState({
                    apiResponseData: dataToShow,
                    apiResponseStatus: '已从本地审阅数据加载',
                    apiResponseError: null
                });
                console.log('已从本地加载文档审阅数据');
            } catch (error) {
                console.error('解析本地保存的文档审阅数据失败:', error);
                // 尝试直接使用mock数据作为后备选项
                const mockData = {
                    data: JSON.stringify([
                        {
                            context: "这是一段原始文本，存在一些语法问题。",
                            update: "这是一段原始文本，不存在语法问题。"
                        },
                        {
                            context: "我们需要尽快完成这项工作，但是时间已经不够了。",
                            update: "我们需要尽快完成这项工作，因为时间已经不够了。"
                        }
                    ])
                };
                this.setState({
                    apiResponseData: mockData,
                    apiResponseStatus: '使用本地默认数据',
                    apiResponseError: null
                });
            }
        }
    }

    // 调用接口获取数据并显示 - 接收文件对象并以FormData形式上传
    fetchRunCheckDocData = async (file = null) => {
        try {
            // 设置加载状态为true
            this.setState({ loading: true });
            message.loading('正在调用接口获取数据...', 0); // 设置0表示不会自动关闭
            
            // 创建FormData对象用于文件上传
            const formData = new FormData();
            // 添加prompt参数，从localStorage获取或使用默认值
            formData.append('prompt', this.getCurrentReviewPrompt());
            // 如果提供了文件参数，则添加到FormData中
            if (file) {
                formData.append('file', file);
            }
            
            // 使用相对路径，通过代理解决跨域问题
            // 注意：使用FormData时不需要设置Content-Type，浏览器会自动设置
            const response = await fetch('/api/upload/runflow ', {
                method: 'POST',
                body: formData
            });
            
            if (response.ok) {
                const data = await response.json();
                message.destroy(); // 销毁之前的loading消息
                message.success('接口调用成功！');
                // 存储返回的数据到状态
                this.setState({
                    apiResponseData: data,
                    apiResponseStatus: `成功 - HTTP ${response.status}`,
                    apiResponseError: null,
                    loading: false // 请求结束，设置加载状态为false
                });
                
                // 同时更新全局状态，以便文档修改页面可以获取到这些数据
                // 注意：将data对象转换为JSON字符串，以便在不同页面间正确传递
                this.props.dispatch({
                    type: 'globaldata/updateDocumentReviewData',
                    payload: {
                        data: JSON.stringify(data),
                        status: `成功 - HTTP ${response.status}`,
                        error: null
                    }
                });
                
                // 保存数据到localStorage
                localStorage.setItem('document_review_data', JSON.stringify({ data: JSON.stringify(data) }));
                // 同时保存为document_update_data格式，确保文档修改页面也能直接从localStorage读取
                try {
                    const comparisonData = data.data ? JSON.parse(data.data).map(item => ({
                        original: item.context || '无原文',
                        modified: item.update || item.context || '无内容'
                    })) : [];
                    localStorage.setItem('document_update_data', JSON.stringify(comparisonData));
                    console.log('已保存文档修改数据到本地:', comparisonData);
                } catch (error) {
                    console.error('格式化文档修改数据失败:', error);
                }
                console.log('已保存文档审阅数据到本地');
                console.log('接口返回数据:', data);
            } else {
                // 处理非200响应
                const errorText = await response.text();
                throw new Error(`请求失败，状态码: ${response.status}, 错误信息: ${errorText}`);
            }
        } catch (error) {
            message.destroy(); // 销毁之前的loading消息
            message.error('接口调用失败，使用模拟数据：' + error.message);
            // 提供mock数据以便前端开发和测试 - 格式匹配组件期望的结构
            const mockData = {
                data: JSON.stringify([
                    {
                        context: "这是一段原始文本，存在一些语法问题。",
                        update: "这是一段原始文本，不存在语法问题。"
                    },
                    {
                        context: "我们需要尽快完成这项工作，但是时间已经不够了。",
                        update: "我们需要尽快完成这项工作，因为时间已经不够了。"
                    },
                    {
                        context: "他每天都在努力工作，希望能够得到晋升。",
                        update: "他每天都在努力工作，希望能够获得晋升机会。"
                    },
                    {
                        context: "项目进展顺利，所有任务都已按时完成。",
                        update: "项目进展顺利，所有任务都已按时完成。"
                    }
                ])
            };
            this.setState({
                apiResponseData: mockData,
                apiResponseStatus: '使用模拟数据',
                apiResponseError: error.message,
                loading: false // 请求结束，设置加载状态为false
            });
            
            // 即使使用模拟数据，也保存到localStorage，确保两个页面都能读取到
            try {
                localStorage.setItem('document_review_data', JSON.stringify(mockData));
                
                // 同时保存为document_update_data格式
                const comparisonData = mockData.data ? JSON.parse(mockData.data).map(item => ({
                    original: item.context || '无原文',
                    modified: item.update || item.context || '无内容'
                })) : [];
                localStorage.setItem('document_update_data', JSON.stringify(comparisonData));
                console.log('已保存模拟文档数据到本地');
            } catch (saveError) {
                console.error('保存模拟数据到本地失败:', saveError);
            }
            
            console.error('接口调用错误:', error);
        } finally {
            // 无论请求成功或失败，最终都要设置加载状态为false
            if (this.state.loading) {
                this.setState({ loading: false });
                message.destroy(); // 确保销毁loading消息
            }
        }
    }

    handleStandardTableChange = (pagination, sorter) => {
        const { dispatch } = this.props
        const { formValues } = this.state

        const params = {
            currentPage: pagination.current,
            pageSize: pagination.pageSize,
            ...formValues
        }

        sorter.field && (params.sorter = `${sorter.field}_${sorter.order}`)

        // dispatch({
        //     type: 'prouser/query_page_for_prouser',
        //     payload: params
        // })
    }

    handleFormReset = () => {
        const { dispatch } = this.props
        this.setState({
            formValues: {}
        })

        // dispatch({
        //     type: 'prouser/query_page_for_prouser',
        //     payload: {
        //         resetFlag: true
        //     }
        // })
    }

    toggleForm = () => {
        const { expandForm } = this.state
        this.setState({
            expandForm: !expandForm
        })
    }

    handleSelectRows = rows => {
        this.setState({
            selectedRows: rows
        })
    }

    handleSearch = values => {
        const { dispatch } = this.props
        const { expandForm } = this.state

        this.setState({
            formValues: values
        })

        // dispatch({
        //     type: 'prouser/query_page_for_prouser',
        //     payload: {
        //         ...values,
        //         resetFlag: true,
        //         expandForm
        //     }
        // })
    }

    handleModalVisible = flag => {
        this.setState({
            modalVisible: !!flag
        })
    }

    handleUpdateModalVisible = (flag, record) => {
        this.setState({
            updateModalVisible: !!flag,
            updateFormValues: record || {}
        })
    }

    handleViewModalVisible = (flag, record) => {
        this.setState({
            viewModalVisible: !!flag,
            viewFormValues: record || {}
        })
    }

    handleAdd = fields => {
        const { dispatch } = this.props

        dispatch({
            type: 'prouser/insert_for_prouser',
            payload: {
                user_id: fields.user_id,
                user_name: fields.user_name,
                user_name_cn: fields.user_name_cn,
                user_name_en: fields.user_name_en,
                password: fields.password,
                email: fields.email,
                phone: fields.phone,
                landline: fields.landline,
                sex: fields.sex,
                avatar: fields.avatar,
                sign: fields.sign,
                tags: fields.tags,
                id_card: fields.id_card,
                birthday: fields.birthday,
                job_status: fields.job_status,
                hiredate: fields.hiredate,
                departure_time: fields.departure_time,
                user_type: fields.user_type,
                emp_no: fields.emp_no,
                access_card_no: fields.access_card_no,
                country: fields.country,
                province: fields.province,
                city: fields.city,
                address: fields.address,
                work_addr: fields.work_addr,
                floor: fields.floor,
                inprovince: fields.inprovince,
                // dept_code: fields.dept_code,
                // dept_name: fields.dept_name,
                inner_dept_code: fields.inner_dept_code,
                org_code: fields.org_code,
                org_name: fields.org_name,
                inner_org_code: fields.inner_org_code,
                posts: fields.posts,
                wx_openid: fields.wx_openid,
                wx_mpopenid: fields.wx_mpopenid,
                wx_miniopenid: fields.wx_miniopenid,
                wx_unionid: fields.wx_unionid,
                mobile_imei: fields.mobile_imei,
                device_num: fields.device_num,
                al_taobao: fields.al_taobao,
                al_alipay: fields.al_alipay,
                al_dingding: fields.al_dingding,
                is_system_user: fields.is_system_user,
                mgr_type: fields.mgr_type,
                pwd_security_level: fields.pwd_security_level,
                pwd_update_date: fields.pwd_update_date,
                last_login_ip: fields.last_login_ip,
                last_login_date: fields.last_login_date,
                freeze_date: fields.freeze_date,
                freeze_cause: fields.freeze_cause,
                zindex: fields.zindex,
                wx_msg: fields.wx_msg,
                email_msg: fields.email_msg,
                system_msg: fields.system_msg,
                remarks: fields.remarks,
                status: fields.status,
                creator: fields.creator,
                create_date: fields.create_date,
                updater: fields.updater,
                update_date: fields.update_date
            },
            callback: (res) => {
                if (res.success == true) {
                    message.success('添加成功')
                    this.handleModalVisible()
                }
            }
        })
    }

    handleDeleteRecord = record => {
        const { dispatch } = this.props

        dispatch({
            type: 'prouser/delete_by_primarykey_for_prouser',
            payload: {
                recordid: record.user_id
            },
            callback: res => {
                if (res.success) {
                    message.success('删除成功')

                    this.setState({
                        selectedRows: []
                    })
                }
            }
        })
    }

    handleUpdate = fields => {
        const { dispatch } = this.props

        dispatch({
            type: 'prouser/update_for_prouser',
            payload: {
                user_id: fields.user_id,
                user_name: fields.user_name,
                user_name_cn: fields.user_name_cn,
                user_name_en: fields.user_name_en,
                password: fields.password,
                email: fields.email,
                phone: fields.phone,
                landline: fields.landline,
                sex: fields.sex,
                avatar: fields.avatar,
                sign: fields.sign,
                tags: fields.tags,
                id_card: fields.id_card,
                birthday: fields.birthday,
                job_status: fields.job_status,
                hiredate: fields.hiredate,
                departure_time: fields.departure_time,
                user_type: fields.user_type,
                emp_no: fields.emp_no,
                access_card_no: fields.access_card_no,
                country: fields.country,
                province: fields.province,
                city: fields.city,
                address: fields.address,
                work_addr: fields.work_addr,
                floor: fields.floor,
                inprovince: fields.inprovince,
                // dept_code: fields.dept_code,
                // dept_name: fields.dept_name,
                inner_dept_code: fields.inner_dept_code,
                org_code: fields.org_code,
                org_name: fields.org_name,
                inner_org_code: fields.inner_org_code,
                posts: fields.posts,
                wx_openid: fields.wx_openid,
                wx_mpopenid: fields.wx_mpopenid,
                wx_miniopenid: fields.wx_miniopenid,
                wx_unionid: fields.wx_unionid,
                mobile_imei: fields.mobile_imei,
                device_num: fields.device_num,
                al_taobao: fields.al_taobao,
                al_alipay: fields.al_alipay,
                al_dingding: fields.al_dingding,
                is_system_user: fields.is_system_user,
                mgr_type: fields.mgr_type,
                pwd_security_level: fields.pwd_security_level,
                pwd_update_date: fields.pwd_update_date,
                last_login_ip: fields.last_login_ip,
                last_login_date: fields.last_login_date,
                freeze_date: fields.freeze_date,
                freeze_cause: fields.freeze_cause,
                zindex: fields.zindex,
                wx_msg: fields.wx_msg,
                email_msg: fields.email_msg,
                system_msg: fields.system_msg,
                remarks: fields.remarks,
                status: fields.status,
                creator: fields.creator,
                create_date: fields.create_date,
                updater: fields.updater,
                update_date: fields.update_date
            },
            callback: (res) => {
                if (res.success === true) {
                    message.success('修改成功')
                    this.handleUpdateModalVisible()
                }
            }
        })
    }

    // 修改用户状态
    handleUpdateUserStatus = (fields, status, msg) => {
        const { dispatch } = this.props

        confirm({
            title: `确定要 ${msg} 当前用户的吗?`,
            icon: <ExclamationCircleFilled />,
            onOk() {
                dispatch({
                    type: 'prouser/update_for_prouser',
                    payload: {
                        user_id: fields.user_id,
                        status: status,
                    },
                    callback: (res) => {
                        if (res.success === true) {
                            message.success('修改成功')
                        }
                    }
                })
            }
        })
    }

    // 修改用户密码
    handleUpdateUserPassword = fields => {
        const { dispatch } = this.props
        confirm({
            title: '确定要重置当前用户的密码吗?',
            icon: <ExclamationCircleFilled />,
            onOk() {
                dispatch({
                    type: 'prouser/resetpwd_for_prouser',
                    payload: {
                        user_id: fields.user_id
                    },
                    callback: (res) => {
                        if (res.success === true) {
                            message.success('重置成功')
                        }
                    }
                })
            }
        })
    }

    renderSimpleForm() {
        const { timesheet: { params } } = this.props
        const parentMethods = {
            handleSearch: this.handleSearch,
            handleFormReset: this.handleFormReset,
            toggleForm: this.toggleForm,
            params
        }

        return <TimeSheetRenderSimpleForm {...parentMethods} />
    }

    renderAdvancedForm() {
        const { dispatch, prouser: { selectDeptTree, selectOrganTree, params } } = this.props
        const parentMethods = {
            handleSearch: this.handleSearch,
            handleFormReset: this.handleFormReset,
            toggleForm: this.toggleForm,
            dispatch: dispatch,
            selectDeptTree: selectDeptTree,
            selectOrganTree: selectOrganTree,
            params
        }

        return <TimeSheetRenderAdvancedForm {...parentMethods} />
    }

    renderForm() {
        const { expandForm } = this.state
        return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm()
    }

    handleCollapse = () => {
        const { toggleExpand } = this.state
        this.setState({
            toggleExpand: !toggleExpand
        })
    }

    // 处理文件选择
    handleFileSelect = (e) => {
        const file = e.target.files[0];
        if (file) {
            this.setState({ 
                selectedFile: file, 
                fileName: file.name 
            }, () => {
                // 选择文件后直接触发接口调用，以FormData形式上传文件
                this.fetchRunCheckDocData(file);
            });
        }
    }

    // 点击按钮触发文件选择
    triggerFileSelect = () => {
        this.fileInputRef.current.click();
    }

    // 文件上传
    uploadFile = async () => {
        const { selectedFile } = this.state;
        if (!selectedFile) return;

        try {
            const formData = new FormData();
            formData.append('file', selectedFile);

            message.loading('文件上传中...');
            
            // 调用上传接口
            const response = await fetch('http://192.168.13.131:8080/api/upload/word', {
                method: 'POST',
                body: formData,
            });

            if (response.ok) {
                const data = await response.json();
                message.success('文件上传成功！');
                console.log('上传成功，返回数据:', data);
                // 可以在这里处理上传成功后的逻辑
            } else {
                throw new Error('上传失败');
            }
        } catch (error) {
            message.error('文件上传失败：' + error.message);
            console.error('上传错误:', error);
        }
    }

    // 获取当前使用的审阅提示词
    getCurrentReviewPrompt = () => {
        // 优先从localStorage获取
        const savedPrompt = localStorage.getItem('pdfReviewPrompt');
        if (savedPrompt) {
            return savedPrompt;
        }
        
        // 如果没有保存的提示词，使用默认提示词
        const defaultPrompt = "请审阅此PDF文档，检查以下内容：\n 1. 文档结构完整性\n 2. 图表与文字的对应关系\n 3. 版权和引用规范性\n 4. 是否符合行业标准";
        return defaultPrompt;
    }

    // 保存审阅提示词配置（保留方法但实际已移至系统设置页面）
    handleSavePrompt = () => {
        const { reviewPrompt } = this.state;
        try {
            // 将审阅提示词保存到localStorage，实现持久化存储
            localStorage.setItem('pdfReviewPrompt', reviewPrompt);
            
            // 显示保存成功提示
            message.success('审阅提示词配置保存成功！');
            console.log('保存的提示词:', reviewPrompt);
        } catch (error) {
            message.error('保存失败：' + error.message);
            console.error('保存错误:', error);
        }
    }

    // 创建一个文件输入框的引用
    fileInputRef = React.createRef();

    render() {
        const {
            timesheet: {
                data,
                selectDeptTree,
                selectOrganTree
            },
            loading,
            dispatch
        } = this.props
        const {
            selectedRows,
            modalVisible,
            updateModalVisible,
            viewModalVisible,
            updateFormValues,
            viewFormValues,
            toggleExpand,
            fileName
        } = this.state

        const parentMethods = {
            handleAdd: this.handleAdd,
            handleModalVisible: this.handleModalVisible,
            dispatch: dispatch,
            loading,
            selectDeptTree: selectDeptTree,
            selectOrganTree: selectOrganTree
        }

        const updateMethods = {
            handleUpdateModalVisible: this.handleUpdateModalVisible,
            handleUpdate: this.handleUpdate,
            dispatch: dispatch,
            loading,
            selectDeptTree: selectDeptTree,
            selectOrganTree: selectOrganTree
        }

        const viewMethods = {
            handleViewModalVisible: this.handleViewModalVisible
        }

        return (
            <>
                <Card bordered={false}>
                    <div style={{ padding: '15px', border: '1px solid #ddd', borderRadius: 5, marginBottom: 15 }}>
                        <h2 style={{ fontWeight: 600 }}>上传文档进行自动审阅</h2>
                        <div className={styles.documentUploadSection}>
                            {/* 隐藏的文件输入框 */}
                            <input
                                type="file"
                                ref={this.fileInputRef}
                                style={{ display: 'none' }}
                                onChange={this.handleFileSelect}
                                accept=".doc,.docx,.pdf,.ppt,.pptx"
                            />
                            <Button 
                                type='primary' 
                                style={{ background: '#4CAF50' }}
                                onClick={this.triggerFileSelect}
                                loading={this.state.loading}
                            >
                                选择文档
                            </Button>
                            {/* 显示已选择的文件名 */}
                            {this.state.fileName && (
                                <span style={{ marginLeft: '10px', color: '#666' }}>
                                    {this.state.fileName}
                                </span>
                            )}
                            <Button type='primary' htmlType='submit' style={{ background: '#4CAF50', marginLeft: '10px' }}
                                loading={this.state.loading}>
                                开始审阅
                            </Button>
                            或
                            <Input placeholder='输入文档链接' style={{ width: 200, marginLeft: '10px' }} />
                            <Button type='primary' htmlType='submit' style={{ background: '#4CAF50', marginLeft: '10px' }}
                                loading={this.state.loading}>
                                通过链接审阅
                            </Button>
                            <Button type='primary' htmlType='submit' style={{ background: '#4CAF50', marginLeft: '10px' }}
                                loading={this.state.loading}>
                                提交参考文件
                            </Button>
                            <Button type='primary' htmlType='submit' style={{ marginLeft: '10px' }}
                                loading={this.state.loading}>
                                下载原文档
                            </Button>
                        </div>
                    </div>
                    
                    {/* 审阅任务配置已移至系统设置页面，此处不再显示编辑区域 */}
                    <div style={{ marginBottom:'15px',display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <div>
                            <h2 style={{fontWeight: 600}}>审阅问题点与建议</h2>
                        </div>
                        <div style={{gap:'10px'}}>
                            <Button type='primary' htmlType='submit' style={{ marginRight:'10px',background: '#4CAF50' }}>
                                提交参考文件
                            </Button>
                            <Button type='primary' htmlType='submit'>
                                下载原文档
                            </Button>
                        </div>
                    </div>
                    <Table
                      columns={[
                        {
                          title: '序号',
                          dataIndex: 'id',
                          key: 'id',
                          width: 60,
                          align: 'center',
                        },
                        {
                          title: '原文问题',
                          dataIndex: 'originalText',
                          key: 'originalText',
                        },
                        {
                          title: '问题描述',
                          dataIndex: 'description',
                          key: 'description',
                        },
                        {
                          title: '修改建议',
                          dataIndex: 'suggestion',
                          key: 'suggestion',
                        },
                      ]}
                      dataSource={this.state.apiResponseData && this.state.apiResponseData.data ? 
                        // 确保解析后的数据是数组，如果不是则返回空数组
                        Array.isArray(JSON.parse(this.state.apiResponseData.data)) ? 
                        JSON.parse(this.state.apiResponseData.data).map((item, index) => ({
                          id: index + 1,
                          originalText: item.context || '无原文',
                          description: '标点符号使用不规范，影响语句通顺性',
                          suggestion: item.update || '无修改建议',
                          key: index + 1,
                        })) : [] : []}
                      pagination={false}
                      style={{ marginTop: '20px' }}
                      loading={this.state.loading}
                    />
                    {/* <div className={styles.proUsertableList}>
                        <div className={styles.proUsertableListForm}>{this.renderForm()}</div>
                        <div style={{ fontWeight: 500 }}>汇总信息</div>
                        <Divider style={{ borderColor: '#cccccc', margin: 0 }}>
                            <div className={styles.summaryButton} onClick={() => this.handleCollapse()}>
                                {toggleExpand ? <><UpOutlined /> 收起</> : <><DownOutlined /> 展开</>}
                            </div>
                        </Divider>
                        <div style={{ display: toggleExpand ? 'block' : 'none' }}>
                            <Row gutter={{ md: 8, lg: 24, xl: 48 }} className={styles.summaryContent}>
                                <Col md={5} sm={24}>
                                    <div>
                                        <span>单位: </span>
                                        <span>清河中医院</span>
                                    </div>
                                </Col>

                                <Col md={5} sm={24}>
                                    <span>部门: </span>
                                    <span>心内科</span>
                                </Col>

                                <Col md={5} sm={24}>
                                    <div>
                                        <span>总人数: </span>
                                        <span>300</span>
                                    </div>
                                </Col>
                            </Row>
                            <Row gutter={{ md: 8, lg: 24, xl: 48 }} className={styles.summaryContent}>
                                <Col md={5} sm={24}>
                                    <span>总作业数量: </span>
                                    <span>600</span>
                                </Col>

                                <Col md={5} sm={24}>
                                    <span>总考勤工时: </span>
                                    <span>2300</span>
                                </Col>

                                <Col md={5} sm={24}>
                                    <span>总作业工时: </span>
                                    <span>2000</span>
                                </Col>
                                <Col md={5} sm={24}>
                                    <span>总空闲工时: </span>
                                    <span>200</span>
                                </Col>
                            </Row>
                            <Row gutter={{ md: 8, lg: 24, xl: 48 }} className={styles.summaryContent}>
                                <Col md={5} sm={24}>
                                    <span>直接作业占比: </span>
                                    <span>86.96%</span>
                                </Col>

                                <Col md={5} sm={24}>
                                    <span>空闲工时占比: </span>
                                    <span>13.04%</span>
                                </Col>
                            </Row>
                        </div>
                        <div style={{ display: 'flex', justifyContent: "space-between" }}>
                            <div>共20项</div>
                            <div style={{ marginRight: 30 }}>
                                图例：
                                <div style={{ display: 'inline-block', width: 65, height: 20, textAlign: 'center', background: '#8ddd15' }}>作业时长</div>
                                <div style={{ display: 'inline-block', width: 65, height: 20, textAlign: 'center', background: '#cccccc', }}>空闲时长</div>
                            </div>
                        </div>
                        <StandardTable
                            rowKey={'user_id'}
                            selectedRows={selectedRows}
                            loading={loading}
                            data={mockData}
                            columns={this.columns}
                            onSelectRow={this.handleSelectRows}
                            onChange={this.handleStandardTableChange}
                            scroll={{ x: 1000, y: 600 }}
                            showTotal={(total, range) => total}
                        />
                    
                    {/* 显示接口返回数据的区域 */}
                    {/* <Card title="接口返回数据展示" bordered={false} style={{ marginTop: '20px' }}>
                        <div style={{ marginBottom: '10px' }}>
                            <strong>调用状态：</strong>
                            <Tag color={this.state.apiResponseStatus === '成功 - HTTP 200' ? 'green' : 'red'}>
                                {this.state.apiResponseStatus}
                            </Tag>
                        </div>
                        
                        {this.state.apiResponseError && (
                            <div style={{ marginBottom: '10px', color: 'red' }}>
                                <strong>错误信息：</strong>{this.state.apiResponseError}
                            </div>
                        )}
                        
                        {this.state.apiResponseData && (
                            <div>
                                <strong>返回数据：</strong>
                                <pre style={{ backgroundColor: '#f5f5f5', padding: '10px', borderRadius: '4px', overflow: 'auto' }}>
                                    {JSON.stringify(this.state.apiResponseData, null, 2)}
                                </pre>
                            </div>
                        )}
                    </Card> */}
                </Card>

                {modalVisible && <TimeSheetCreateForm {...parentMethods} modalVisible={modalVisible} />}

                {updateFormValues && Object.keys(updateFormValues).length ? (
                    <TimeSheetUpdateForm
                        {...updateMethods}
                        updateModalVisible={updateModalVisible}
                        values={updateFormValues}
                    />
                ) : null}

                {viewFormValues && Object.keys(viewFormValues).length ? (
                    <TimeSheetViewForm
                        {...viewMethods}
                        viewModalVisible={viewModalVisible}
                        values={viewFormValues}
                    />
                ) : null}
            </>
        )
    }
}

export default TimeSheetList
