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 { PostJobapplicantAdddesirearea, PostJobapplicantDeldesirearea, PostJobapplicantUpdatedesirearea, PostJobapplicantListdesirearea, PostJobapplicantDesireareadetail, GetDictTree , GetDictDetail} from '@/apis/api';

import { Imageprefix } from '@/constants';
import UploadModel from '@/components/Common/upload';


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

const PagesMainJobseekerListResumeIntentionArea: 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>([])
    const [optionLevel4, setOptionLevel4] = useState<any>([])

    return (
        <>
            <ConfigProvider
                theme={{
                    token: {
                        colorPrimary: '#4FBE70',
                    }
                }}
            >
                <EditableProTable
                    editableFormRef={editableFormRef}
                    actionRef={actionRef}
                    rowKey="id"
                    loading={false}
                    request={async () => {
                        let res = await PostJobapplicantListdesirearea({
                            customer_id: id.customer_id,
                            sortby: 'asc',
                            sort: 'id'
                        })
                        setList(res.data.jobapplicantareas)
                        setOriginList(res.data.jobapplicantareas)
                        setTotal(res.data.total)
                        return {
                            data: res.data.jobapplicantareas,
                            total: res.data.total,
                            success: true,
                        }

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

                    },
                        {
                            title: '省级',
                            dataIndex: 'level1',
                            render: (text, record) => (
                                <>
                                    <span>{record.level1_txt}</span>
                                </>
                            ),
                            valueType: 'select',
                            fieldProps: (form, config) => {
                                return {
                                    placeholder: '请选择省级',
                                    options: dictModel.areaList,
                                    fieldNames: selectfieldNames,
                                    onChange: async (value, option) => {
                                        let res = await GetDictTree({ code: option.code })
                                        setOptionLevel2(res.data.dicts)
                                        editableFormRef.current?.setRowData?.(config.entity.id, { level2: 0 });
                                        editableFormRef.current?.setRowData?.(config.entity.id, { level3: 0 });
                                        editableFormRef.current?.setRowData?.(config.entity.id, { level4: 0 });
                                    }
                                }

                            },
                        },
                        {
                            title: '市级',
                            dataIndex: 'level2',
                            render: (text, record) => (
                                <>
                                    <span>{record.level2_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, { level3: 0 });
                                        editableFormRef.current?.setRowData?.(config.entity.id, { level4: 0 });
                                    }
                                }

                            },

                        },
                        {
                            title: '乡镇',
                            dataIndex: 'level3',
                            render: (text, record) => (
                                <>
                                    <span>{record.level3_txt}</span>
                                </>
                            ),
                            valueType: 'select',
                            fieldProps: (form, config) => {
                                return {
                                    placeholder: '请选择乡镇',
                                    options: optionLevel3,
                                    fieldNames: selectfieldNames,
                                    onChange: async (value, option) => {
                                        let res = await GetDictTree({ code: option.code })
                                        setOptionLevel4(res.data.dicts)
                                        editableFormRef.current?.setRowData?.(config.entity.id, { level4: 0 });
                                    }
                                }
                            },

                        },
                        {
                            title: '社区',
                            dataIndex: 'level4',
                            render: (text, record) => (
                                <>
                                    <span>{record.level4_txt}</span>
                                </>
                            ),
                            valueType: 'select',
                            fieldProps: {
                                placeholder: '请选择社区',
                                options: optionLevel4,
                                fieldNames: selectfieldNames,
                            },
                        },
                        {
                            title: '操作',
                            valueType: 'option',
                            width: 200,
                            render: (text, record, _, action) => [
                                <a
                                    key="editable"
                                    onClick={async() => {
                                        if(record.level1) {
                                            let res = await GetDictDetail({ id: record.level1 })
                                            setOptionLevel2(res.data.childs)
                                        }
                                        if(record.level2) {
                                            let res = await GetDictDetail({ id: record.level2 })
                                            setOptionLevel3(res.data.childs)
                                        }
                                        if(record.level3) {
                                            let res = await GetDictDetail({ id: record.level3 })
                                            setOptionLevel4(res.data.childs)
                                        }
                                        action?.startEditable?.(record.id);
                                    }}
                                >
                                    编辑
                                </a>,
                                <a
                                    key="delete"
                                    onClick={() => {
                                    }}
                                >
                                    删除
                                </a>,
                            ],
                        },
                    ]}
                    editable={{
                        type: 'single',
                        editableKeys,
                        onSave: async (rowKey, data: ResumeType.intentionArea, row) => {
                            console.log(rowKey, data, row)
                            data.customer_id = id.customer_id;
                            delete data.index;
                            if (rowKey && originList.findIndex(item => item.id === rowKey) !== -1) {
                                data.id = rowKey;
                                let res = await PostJobapplicantUpdatedesirearea(data)
                                message.success('提交成功')
                                actionRef.current.reload();
                            } else {
                                delete data.id;
                                let res = await PostJobapplicantAdddesirearea(data)
                                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
}))(PagesMainJobseekerListResumeIntentionArea);