import React, { PureComponent } from 'react';
import {
    Modal,
    Form,
    Input,
    Select,
    InputNumber,
    Row,
    Col,
    message,
    DatePicker,
    TreeSelect
} from 'antd';
import {
    UserOutlined,
    TeamOutlined,
    ClockCircleOutlined,
    NumberOutlined
} from '@ant-design/icons';
import moment from 'moment';

const { Option } = Select;

class WorkReportAdd extends PureComponent {
    constructor(props) {
        super(props);
        this.formRef = React.createRef();
        
        // 组织架构树数据
        this.treeData = [
            {
                title: '飞利信科技有限公司',
                value: '0-0',
                key: '0-0',
                children: [
                    {
                        title: '技术部',
                        value: '技术部',
                        key: '0-0-0',
                        children: [
                            { title: '前端组', value: '前端组', key: '0-0-0-0' },
                            { title: '后端组', value: '后端组', key: '0-0-0-1' },
                            { title: '测试组', value: '测试组', key: '0-0-0-2' }
                        ],
                    },
                    {
                        title: '产品部',
                        value: '产品部',
                        key: '0-0-1',
                        children: [
                            { title: '产品设计组', value: '产品设计组', key: '0-0-1-0' },
                            { title: '用户体验组', value: '用户体验组', key: '0-0-1-1' },
                            { title: '产品运营组', value: '产品运营组', key: '0-0-1-2' }
                        ],
                    },
                    {
                        title: '运营部',
                        value: '运营部',
                        key: '0-0-2',
                        children: [
                            { title: '市场营销组', value: '市场营销组', key: '0-0-2-0' },
                            { title: '客户服务组', value: '客户服务组', key: '0-0-2-1' },
                            { title: '商务合作组', value: '商务合作组', key: '0-0-2-2' }
                        ],
                    },
                    {
                        title: '财务部',
                        value: '财务部',
                        key: '0-0-3',
                        children: [
                            { title: '会计组', value: '会计组', key: '0-0-3-0' },
                            { title: '审计组', value: '审计组', key: '0-0-3-1' }
                        ],
                    },
                    {
                        title: '人事部',
                        value: '人事部',
                        key: '0-0-4',
                        children: [
                            { title: 'HR专员组', value: 'HR专员组', key: '0-0-4-0' },
                            { title: '招聘组', value: '招聘组', key: '0-0-4-1' },
                            { title: '培训组', value: '培训组', key: '0-0-4-2' },
                            { title: '薪酬组', value: '薪酬组', key: '0-0-4-3' }
                        ],
                    },
                ],
            },
        ];
    }

    componentDidUpdate(prevProps) {
        // 当编辑数据发生变化时，更新表单值
        if (this.props.editData !== prevProps.editData && this.props.editData) {
            const editData = this.props.editData;
            this.formRef.current?.setFieldsValue({
                workType: editData.workType,
                workPerson: editData.workPerson,
                department: editData.department,
                workQuantity: editData.workQuantity,
                startTime: editData.startTime ? moment(editData.startTime) : null,
                endTime: editData.endTime ? moment(editData.endTime) : null,
                workDescription: editData.workDescription || '',
            });
        }
        
        // 当弹窗关闭时清空表单
        if (!this.props.visible && prevProps.visible) {
            this.formRef.current?.resetFields();
        }
    }

    // 提交表单
    handleSubmit = (values) => {
        const { editData } = this.props;
        const isEdit = !!editData;
        
        console.log(isEdit ? '编辑工作报告:' : '新增工作报告:', values);
        
        // 处理时间数据
        const formattedValues = {
            ...values,
            startTime: values.startTime ? values.startTime.format('YYYY-MM-DD HH:mm:ss') : null,
            endTime: values.endTime ? values.endTime.format('YYYY-MM-DD HH:mm:ss') : null,
        };
        
        // 计算持续时长
        if (values.startTime && values.endTime) {
            const duration = moment(values.endTime).diff(moment(values.startTime), 'hours', true);
            formattedValues.duration = `${duration.toFixed(1)}小时`;
        }
        
        // 如果是编辑，保留原有的id
        if (isEdit) {
            formattedValues.id = editData.id;
            formattedValues.key = editData.key;
        }
        
        // 这里可以调用API接口保存数据
        // 模拟保存成功
        message.success(isEdit ? '编辑工作报告成功！' : '新增工作报告成功！');
        
        // 重置表单
        this.formRef.current?.resetFields();
        
        // 调用父组件的回调函数
        if (this.props.onSuccess) {
            this.props.onSuccess(formattedValues);
        }
        
        // 关闭弹窗
        this.handleCancel();
    };

    // 取消操作
    handleCancel = () => {
        // 重置表单
        this.formRef.current?.resetFields();
        
        // 调用父组件的关闭回调
        if (this.props.onCancel) {
            this.props.onCancel();
        }
    };

    render() {
        const { visible, loading = false, editData } = this.props;
        const isEdit = !!editData;

        return (
            <Modal
                title={isEdit ? "编辑工作报告" : "新增工作报告"}
                open={visible}
                onOk={() => this.formRef.current?.submit()}
                onCancel={this.handleCancel}
                width={800}
                confirmLoading={loading}
                destroyOnClose={true}
                maskClosable={false}
            >
                <Form
                    ref={this.formRef}
                    layout="vertical"
                    onFinish={this.handleSubmit}
                    initialValues={{
                        department: '人事部'
                    }}
                >
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item
                                name="workType"
                                label="作业类型"
                                rules={[
                                    { required: true, message: '请选择作业类型' }
                                ]}
                            >
                                <Select placeholder="请选择作业类型">
                                    <Option value="招聘面试">招聘面试</Option>
                                    <Option value="培训组织">培训组织</Option>
                                    <Option value="绩效考核">绩效考核</Option>
                                    <Option value="薪酬核算">薪酬核算</Option>
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                name="workPerson"
                                label="作业人员"
                                rules={[
                                    { required: true, message: '请输入作业人员姓名' },
                                    { min: 2, max: 10, message: '姓名长度为2-10个字符' }
                                ]}
                            >
                                <Input
                                    placeholder="请输入作业人员姓名"
                                    prefix={<UserOutlined />}
                                />
                            </Form.Item>
                        </Col>
                    </Row>

                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item
                                name="department"
                                label="部门"
                                rules={[
                                    { required: true, message: '请选择部门' }
                                ]}
                            >
                                <TreeSelect
                                    placeholder="请选择部门"
                                    treeData={this.treeData}
                                    style={{ width: '100%' }}
                                    dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                                    treeDefaultExpandAll
                                    showSearch
                                    treeNodeFilterProp="title"
                                    allowClear
                                    suffixIcon={<TeamOutlined />}
                                />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                name="workQuantity"
                                label="作业数量"
                                rules={[
                                    { required: true, message: '请输入作业数量' }
                                ]}
                            >
                                <InputNumber
                                    placeholder="请输入作业数量"
                                    min={1}
                                    max={100}
                                    style={{ width: '100%' }}
                                    prefix={<NumberOutlined />}
                                />
                            </Form.Item>
                        </Col>
                    </Row>

                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item
                                name="startTime"
                                label="开始时间"
                                rules={[
                                    { required: true, message: '请选择开始时间' }
                                ]}
                            >
                                <DatePicker
                                    showTime
                                    placeholder="请选择开始时间"
                                    style={{ width: '100%' }}
                                    format="YYYY-MM-DD HH:mm:ss"
                                    suffixIcon={<ClockCircleOutlined />}
                                />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                name="endTime"
                                label="结束时间"
                                rules={[
                                    { required: true, message: '请选择结束时间' }
                                ]}
                            >
                                <DatePicker
                                    showTime
                                    placeholder="请选择结束时间"
                                    style={{ width: '100%' }}
                                    format="YYYY-MM-DD HH:mm:ss"
                                    suffixIcon={<ClockCircleOutlined />}
                                />
                            </Form.Item>
                        </Col>
                    </Row>

                    <Row gutter={16}>
                        <Col span={24}>
                            <Form.Item
                                name="workDescription"
                                label="工作描述"
                            >
                                <Input.TextArea
                                    placeholder="请输入具体的工作内容描述（可选）"
                                    rows={3}
                                    maxLength={500}
                                    showCount
                                />
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </Modal>
        );
    }
}

export default WorkReportAdd;
