import { useRef, useState, useEffect } from 'react';
import { connect } from '@umijs/max';
import type { ActionType, EditableFormInstance } from '@ant-design/pro-components';
import {
    EditableProTable,
    ProFormCascader,
} from '@ant-design/pro-components';
import { ConfigProvider, Flex, Space, message, Image, Row, Col, Cascader } from 'antd';
import {
    PostJobapplicantAdddesireposition,
    PostJobapplicantDeldesireposition,
    PostJobapplicantUpdatedesireposition,
    PostJobapplicantListdesireposition,
    PostJobapplicantDesirepositiondetail,
    GetDictTree,
    GetDictDetail
} from '@/apis/api';

const selectfieldNames = { label: 'name', value: 'id', children: 'childss' };

const PagesMainJobseekerListResumeIntentionPost: React.FC = ({ dispatch, dictModel, openModel, id }: any) => {
    const actionRef = useRef<ActionType>();
    const editableFormRef = useRef<EditableFormInstance>();

    const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
    const [list, setList] = useState<object[]>([])
    const [originList, setOriginList] = useState<object[]>([])
    const [total, setTotal] = useState<number>(0)

    useEffect(() => {
        dispatch({ type: 'dictModel/getList', payload: { code: 2009, type: 'setAreaList' } })
    }, [])


    const [optionLevel2, setOptionLevel2] = useState<any>([])
    const [optionLevel3, setOptionLevel3] = useState<any>([])

    return (
        <>
            <ConfigProvider
                theme={{
                    token: {
                        colorPrimary: '#4FBE70',
                    }
                }}
            >
                <EditableProTable
                    editableFormRef={editableFormRef}
                    actionRef={actionRef}
                    rowKey="id"
                    loading={false}
                    request={async () => {
                        let res = await PostJobapplicantListdesireposition({
                            customer_id: id.customer_id,
                            sortby: 'asc',
                            sort: 'id'
                        })
                        const updatedPositions = await Promise.all(
                            res.data.jobapplicantpositions.filter(item => item.level1 !== 0).map(async (item: any, index: number) => {
                                const res1 = await GetDictDetail({ id: item.level1 });
                                const res2 = await GetDictDetail({ id: res1.data.parent_id });
                                return {
                                    ...item,
                                    post_id: item.id,
                                    industry_txt: res2.data ? res2.data.name : '',
                                    industry: res2.data ? res2.data.id : ''
                                };
                            })
                        );
                        setList(updatedPositions)
                        setOriginList(updatedPositions)
                        setTotal(res.data.total)
                        return {
                            data: updatedPositions,
                            total: res.data.total,
                            success: true,
                        }

                    }}
                    columns={[  {
                        title: 'ID',
                        dataIndex: 'id',
                        editable: false,
                        width: 100

                    },
                        {
                            title: '行业大类',
                            dataIndex: 'industry',
                            render: (text, record) => (
                                <>
                                    <span>{record.industry_txt}</span>
                                </>
                            ),
                            valueType: 'select',
                            fieldProps: (form, config) => {
                                return {
                                    placeholder: '请选择行业大类',
                                    options: dictModel.industryPostList,
                                    fieldNames: selectfieldNames,
                                    onChange: async (value, option) => {
                                        let res = await GetDictTree({ code: option.code })
                                        setOptionLevel2(res.data.dicts)
                                        editableFormRef.current?.setRowData?.(config.entity.id, { level1: 0 });
                                        editableFormRef.current?.setRowData?.(config.entity.id, { level2: 0 });
                                    }
                                }
                            },
                        },
                        {
                            title: '行业二类',
                            dataIndex: 'level1',
                            render: (text, record) => (
                                <>
                                    <span>{record.level1_txt}</span>
                                </>
                            ),
                            valueType: 'select',
                            fieldProps: (form, config) => {
                                return {
                                    placeholder: '请选择行业二类',
                                    options: optionLevel2,
                                    fieldNames: selectfieldNames,
                                    onChange: async (value, option) => {
                                        let res = await GetDictTree({ code: option.code })
                                        setOptionLevel3(res.data.dicts)
                                        editableFormRef.current?.setRowData?.(config.entity.id, { level2: 0 });
                                    }
                                }
                            },
                        },
                        {
                            title: '职位',
                            dataIndex: 'level2',
                            render: (text, record) => (
                                <>
                                    <span>{record.level2_txt}</span>
                                </>
                            ),
                            valueType: 'select',
                            fieldProps: (form, config) => {
                                return {
                                    placeholder: '请选择职位',
                                    options: optionLevel3,
                                    fieldNames: selectfieldNames,
                                }
                            },

                        },
                        {
                            title: '操作',
                            valueType: 'option',
                            width: 200,
                            render: (text, record, _, action) => [
                                <a
                                    key="editable"
                                    onClick={async () => {
                                        console.log(record)
                                        if (record.level1) {
                                            const res1 = await GetDictDetail({ id: record.level1 });
                                            const res2 = await GetDictDetail({ id: res1.data.parent_id });
                                            setOptionLevel2(res2.data.childs)
                                        }
                                        if (record.level2) {
                                            let res1 = await GetDictDetail({ id: record.level2 })
                                            let res2 = await GetDictDetail({ id: res1.data.parent_id })
                                            setOptionLevel3(res2.data.childs)
                                        }
                                        action?.startEditable?.(record.id);
                                    }}
                                >
                                    编辑
                                </a>,
                                <a
                                    key="delete"
                                    onClick={() => {
                                    }}
                                >
                                    删除
                                </a>,
                            ],
                        },
                    ]}
                    editable={{
                        type: 'single',
                        editableKeys,
                        onSave: async (rowKey, data: ResumeType.intentionPosition, row) => {
                            console.log(rowKey, data, row)
                            data.customer_id = id.customer_id;
                            if (rowKey && originList.findIndex(item => item.id === rowKey) !== -1) {
                                data.id = rowKey;
                                let res1 = await PostJobapplicantUpdatedesireposition({ id: data.id, customer_id: data.customer_id, level1: data.level1, level2: data.level2 })
                                message.success('提交成功')
                                actionRef.current.reload();
                            } else {
                                let res1 = await PostJobapplicantAdddesireposition({ customer_id: data.customer_id, level1: data.level1, level2: data.level2 })
                                message.success('提交成功')
                                actionRef.current.reload();
                            }
                        },
                        onChange: setEditableRowKeys
                    }}
                    recordCreatorProps={
                        {
                            position: 'bottom',
                            record: () => ({ id: list.length > 0 ? (list[list.length - 1].id + 1).toFixed(0) : 0 }),
                        }
                    }
                />
            </ConfigProvider>
        </>
    );
};



export default connect(({ dictModel, openModel }: any) => ({
    dictModel, openModel
}))(PagesMainJobseekerListResumeIntentionPost);