import { ConnectState } from "@/models/global";
import { FormInstance, ProForm, ProFormDigit, ProFormList, ProFormRadio, ProFormSwitch, ProFormText, ProFormTextArea, ProFormTreeSelect } from "@ant-design/pro-components";
import { useImperativeHandle, useRef, useState } from "react";
import { connect } from "umi";
import { Col, message, Modal, Row } from "antd";
import { handleGetExamineTypeList, handleGetExamineTypeTreeList } from "../../index/service";
import { handleAddQuestion, handleEditQuestion } from "../service";


type DetailProps = {
    parentRow: any
    onRef: any
    currentUser?: any
    showQuestionModal: boolean
    setShowQuestionModal?: any
    parentActionRef?: any
    setCurrentRow?: any
    afterAdd?: any
}
const addQuestion = ({ parentRow, onRef, currentUser, showQuestionModal, setShowQuestionModal, parentActionRef, setCurrentRow, afterAdd }: DetailProps) => {

    // 弹出框的表单实例
    const modalRef = useRef<FormInstance>()
    const [categoryIdObj, setCategoryIdObj] = useState<any>()


    useImperativeHandle(onRef, () => ({
        modalRef,
        categoryIdObj
    }));


    return (
        <div>
            <Modal
                width={800}
                title={`${parentRow?.id ? '编辑' : '创建'}问题`}
                open={showQuestionModal}
                destroyOnClose
                onOk={() => {
                    modalRef.current?.validateFields().then(async (res) => {
                        let req = {}
                        let data = {}
                        if (parentRow?.id) {
                            req = {
                                ...parentRow,
                                categoryId: res.categoryId,// 题目id
                                type: `${res.selectType === 1 ? 'radio' : 'checked'}_choice`,// 题目类型
                                title: res.title,// 问题内容
                                required: res.required,// 是否必填
                                options: res.options,
                                status: res.status,
                                operator: currentUser?.operator,
                                description: `${res.categoryId && categoryIdObj ? categoryIdObj[res.categoryId] : ''}`,
                                category: undefined
                            }
                            console.log('req', req);

                            data = await handleEditQuestion(req)
                        } else {
                            req = {
                                categoryId: res.categoryId,// 题目id
                                type: `${res.selectType === 1 ? 'radio' : 'checked'}_choice`,// 题目类型
                                title: res.title,// 问题内容
                                required: res.required,// 是否必填
                                options: res.options,
                                sortOrder: 1,
                                status: res.status,
                                operator: currentUser?.operator,
                                defaultScore: 0,
                                images: [],
                                description: `${res.categoryId && categoryIdObj ? categoryIdObj[res.categoryId] : ''}`
                            }
                            data = await handleAddQuestion(req)
                        }
                        console.log('datadsadsa', data);
                        if (data.Result_Code === 100) {
                            if (modalRef) {
                                modalRef.current?.resetFields()
                            }
                            message.success(data.Result_Desc)
                            setShowQuestionModal(false)
                            if (parentActionRef) {
                                parentActionRef.current?.reload()
                            }
                            if (setCurrentRow) {
                                setCurrentRow(undefined)
                            }
                            if (afterAdd) {
                                afterAdd()
                            }
                        } else {
                            message.error(data.Result_Desc)
                        }

                    })

                }}
                onCancel={() => {
                    if (modalRef) {
                        modalRef.current?.resetFields()
                    }
                    setShowQuestionModal(false)
                    if (setCurrentRow) {
                        setCurrentRow(undefined)
                    }
                }}
            >
                <ProForm formRef={modalRef} submitter={false} request={() => {
                    console.log('currentRow', parentRow);
                    return {
                        ...parentRow,
                        selectType: parentRow.type.split('_')[0] === 'checked' ? 2 : 1
                    }
                }}>
                    <Row gutter={8}>
                        <Col span={12}>
                            <ProFormTreeSelect
                                label={"问题分类"}
                                name={"categoryId"}
                                rules={[
                                    { required: true, message: '请选择问题分类！' }
                                ]}
                                request={async () => {


                                    const req = {}
                                    const data = await handleGetExamineTypeTreeList(req)
                                    console.log('dsadas', data);
                                    let res = [
                                        {
                                            name: '/',
                                            id: 0,
                                            children: data
                                        }
                                    ]
                                    let obj: any = {}
                                    const labelList = await handleGetExamineTypeList()
                                    if (labelList && labelList.length > 0) {
                                        labelList.forEach((item: any) => {
                                            obj[item.id] = item.name
                                        })
                                    }
                                    console.log('objobjobjobj', obj);

                                    setCategoryIdObj(obj)
                                    return data
                                }}
                                fieldProps={{
                                    treeDefaultExpandAll: true,
                                    // treeDefaultExpandedKeys: [0],
                                    fieldNames: {
                                        label: "name",
                                        value: "id"
                                    },
                                    showSearch: true,
                                    filterTreeNode: (input, treeNode) => {
                                        return (treeNode?.name ?? '').toLowerCase().indexOf(input.toLowerCase()) >= 0;
                                    },
                                    treeNodeFilterProp: 'name'
                                }}
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormText
                                label={"问题内容"}
                                name={"title"}
                                rules={[
                                    { required: true, message: '请输入问题！' }
                                ]}
                            />
                        </Col>

                        <Col span={6}>
                            <ProFormSwitch
                                label={"是否必填"}
                                name={"required"}
                                initialValue={parentRow?.id ? parentRow.required : true}
                            />
                        </Col>
                        <Col span={6}>
                            <ProFormSwitch
                                label={"有效状态"}
                                name={"status"}
                                initialValue={parentRow?.id ? parentRow.status : true}
                            />
                        </Col>
                        <Col span={6}>
                            <ProFormRadio.Group
                                label={"题目类型"}
                                name={"selectType"}
                                fieldProps={{
                                    options: [{ label: "单选", value: 1 }, { label: "多选", value: 2 }],
                                }}
                                initialValue={1}
                            />
                        </Col>
                        <Col span={24}>
                            <ProFormList
                                name="options"
                                label="选项内容"
                                initialValue={[]}
                                creatorButtonProps={{
                                    position: 'bottom',
                                    creatorButtonText: '添加选项'
                                }}
                                copyIconProps={false}
                                style={{ width: '100%' }}
                                itemContainerStyle={{ width: '100%' }}
                                itemRender={({ listDom, action }, { record, index }) => (
                                    <div style={{ width: '100%', display: 'flex', alignItems: 'flex-start', marginBottom: '10px' }}>
                                        <div style={{ flex: 1, width: '100%' }}>{listDom}</div>
                                        <div style={{ marginLeft: '8px', marginTop: '30px' }}>{action}</div>
                                    </div>
                                )}
                            >
                                <Row gutter={6} style={{ width: '100%', margin: 0 }}>
                                    <Col span={16}>
                                        <ProFormTextArea
                                            name="text"
                                            label="选项"
                                            fieldProps={{
                                                style: { width: '100%' }
                                            }}
                                        />
                                    </Col>
                                    <Col span={8}>
                                        <ProFormDigit
                                            name="mark"
                                            label="分值"
                                            fieldProps={{
                                                style: { width: '100%' },
                                                defaultValue: 0
                                            }}
                                        />
                                    </Col>
                                </Row>
                            </ProFormList>
                        </Col>
                    </Row>
                </ProForm>
            </Modal>



        </div>
    )
}

export default connect(({ user }: ConnectState) => ({
    currentUser: user.data
}))(addQuestion);
