import { ConnectState } from "@/models/global";
import { ActionType, FormInstance, ProTable } from "@ant-design/pro-components";
import { useRef, useState } from "react";
import { connect } from "umi";
import moment from "moment";
import { Button, Drawer, Image, message, Popconfirm, Space } from "antd";
import { handleGetServerpartDDL } from "@/components/leftSelectTree/service";
import LeftSelectTree from "@/components/leftSelectTree/leftSelectTree";
import RecordDetail from "../record/components/recordDetail";
import { handleDeleteRecord, handleGetRecordTreeList, handleUpdateExtend } from "../record/service";

const ErrorRecord: React.FC<{ currentUser: any }> = (props) => {
    const { currentUser } = props

    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();
    const recordDetailRef = useRef<any>()
    // 显示的附件数据
    const [showImgList, setShowImgList] = useState<string[]>([])
    // 预览图片
    const [imagePreviewVisible, setImagePreviewVisible] = useState<boolean>(false)
    // 预览的索引
    const [previewIndex, setPreviewIndex] = useState<number>(0)
    // 当行数据 
    const [currentRow, setCurrentRow] = useState<any>()
    // 显示详情抽屉
    const [showDetail, setShowDetail] = useState<boolean>(false)
    // 判断是否点了出现的是异常处理的抽屉
    const [showAbnormal, setShowAbnormal] = useState<boolean>(false)
    // 树相关的属性和方法
    const [selectedId, setSelectedId] = useState<string[]>()
    const [columnsStateMap, setColumnsStateMap] = useState<any>({
        score: { show: false }
    })
    const [collapsible, setCollapsible] = useState<boolean>(false)

    const columns: any = [
        // {
        //     title: "统计月份",
        //     dataIndex: "search_months",
        //     hideInTable: true,
        //     valueType: "date",
        //     initialValue: moment().subtract('1', 'd'),
        //     fieldProps: {
        //         picker: "month",
        //         format: 'YYYY-MM',
        //     }
        // },
        // {
        //     title: "统计日期",
        //     dataIndex: "staticDate",
        //     hideInTable: true,
        //     valueType: "dateRange",
        //     initialValue: [moment().startOf('M'), moment()],
        //     search: {
        //         transform: (value: any) => {
        //             return {
        //                 startTime: moment(value[0]).format('YYYY-MM-DD'),
        //                 endTime: moment(value[1]).format('YYYY-MM-DD')
        //             };
        //         },
        //     },
        //     fieldProps: {
        //         picker: "day",
        //         format: 'YYYY-MM-DD',
        //     }
        // },
        // {
        //     title: "服务区",
        //     dataIndex: "serverPartId",
        //     hideInTable: true,
        //     valueType: "select",
        //     request: async () => {
        //         const req = {
        //             ProvinceCode: currentUser?.provinceCode,
        //             StatisticsType: 1000
        //         }
        //         const data = await handleGetServerpartDDL(req)
        //         return data
        //     }
        // },
        // {
        //     title: "巡查类型",
        //     dataIndex: "inspectionType",
        //     hideInTable: true,
        //     valueType: "select",
        //     valueEnum: {
        //         "1": '异常',
        //         "0": "正常"
        //     }
        // },
        {
            title: <div style={{ textAlign: 'center' }}>服务区名称</div>,
            dataIndex: "serverPartName",
            hideInSearch: true,
            width: 200,
            ellipsis: true,
            render: (_, record) => {
                return record?.type === 'district' || record?.type === 'servicePart' ? record?.name :
                    record?.template ? record?.template.title : "-"



                // return record?.name ? record?.name : record?.template && record?.serverPartName ? record?.serverPartName : "-"
            }
        },
        // {
        //     title: <div style={{ textAlign: 'center' }}>站点名称</div>,
        //     dataIndex: "placeName",
        //     hideInSearch: true,
        //     width: 150,
        //     ellipsis: true,
        //     render: (_, record) => {
        //         return record?.template && record?.template.title ? record?.template.title : "-"
        //     }
        // },
        {
            title: <div style={{ textAlign: 'center' }}>巡查类型</div>,
            dataIndex: "placeName",
            hideInSearch: true,
            width: 100,
            align: 'center',
            ellipsis: true,
            render: (_, record) => {
                // let res: any = record.extend ? JSON.parse(record.extend) : "-"
                return <span style={{ color: record.situation === 1 ? "red" : "" }}>{record.situation === 1 ? '异常' : record.situation === 0 ? '正常' : ''}</span>
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>巡查内容</div>,
            dataIndex: "uploadResult",
            hideInSearch: true,
            width: 200,
            ellipsis: true,
            render: (_, record) => {
                // let extendObj = record?.extend ? JSON.parse(record?.extend) : ""
                return record?.uploadResult ? record?.uploadResult : "-"
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>巡查结果</div>,
            dataIndex: "uploadResult",
            hideInSearch: true,
            width: 350,
            ellipsis: true,
            render: (_, record) => {
                let str: string = ''
                if (record?.questionResponses && record?.questionResponses.length > 0) {
                    record?.questionResponses.forEach((item: any, index: number) => {
                        let anwers: string = ''
                        if (item.choiceResponse && item.choiceResponse.length > 0) {
                            item.choiceResponse.forEach((subItem: string, subIndex: number) => {
                                anwers += `${subIndex > 0 ? '，' : ''}${subItem}`
                            })
                        }
                        str += `${index > 0 ? '，' : ''}考核内容：${item.question.title}，考核结果：${anwers}`
                    })
                }
                return str || ''
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>巡查总分</div>,
            dataIndex: "score",
            hideInSearch: true,
            valueType: 'digit',
            width: 100,
            align: 'center',
        },
        {
            title: <div style={{ textAlign: 'center' }}>处理状态</div>,
            dataIndex: "errorStatus",
            // hideInSearch: true,
            width: 100,
            valueType: 'select',
            valueEnum: {
                "0": "待处理",
                "1": "处理中",
                "2": "已处理",
            },
            ellipsis: true,
            align: 'center',
            render: (_, record) => {
                // let res: any = record.extend ? JSON.parse(record.extend) : "-"
                return record?.situation !== 0 ? <span style={{ color: record.errorStatus === 0 ? "red" : record.errorStatus === 1 ? "#1677ff" : "" }}>{
                    record.errorStatus === 0
                        ? "待处理"
                        : record.errorStatus === 1
                            ? "处理中"
                            : record.errorStatus === 2
                                ? "已处理"
                                : "-"
                }</span> : ""
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>巡查时间</div>,
            dataIndex: "createdAt",
            hideInSearch: true,
            width: 150,
            ellipsis: true,
            align: 'center',
            render: (_, record) => {
                return record?.createdAt ? moment(record?.createdAt).format('YYYY-MM-DD HH:mm:ss') : '-'
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>巡查人</div>,
            dataIndex: "userName",
            hideInSearch: true,
            width: 100,
            ellipsis: true,
            align: 'center',
        },
        {
            title: <div style={{ textAlign: 'center' }}>现场图片</div>,
            dataIndex: "placeName",
            hideInSearch: true,
            width: 150,
            ellipsis: true,
            align: 'center',
            render: (_, record) => {
                // let extendObj = record?.extend ? JSON.parse(record?.extend) : ""
                let imgList = record.imgsList
                return imgList && imgList.length > 0 ?
                    <Button type="primary" onClick={() => {
                        setShowImgList(imgList)
                        setImagePreviewVisible(true)
                    }}>查看附件</Button> : "-"
            }
        },
        {
            title: '操作',
            dataIndex: 'option',
            align: 'center',
            fixed: "right",
            hideInSearch: true,
            width: 150,
            render: (_: any, record: any) => {
                // let res: any = record.extend ? JSON.parse(record.extend) : "-"

                return record?.type === 'district' || record?.type === 'servicePart' ? '' : <Space>
                    {
                        record.situation === 1 ?
                            <a onClick={
                                () => {
                                    setCurrentRow({
                                        ...record,
                                    })
                                    setShowAbnormal(true)
                                    setShowDetail(true)
                                }
                            }>异常处理</a> : < a onClick={() => {
                                setCurrentRow({
                                    ...record,
                                })
                                setShowDetail(true)
                            }}>   详情
                            </a >
                    }


                    {/* <Popconfirm
                        title={"确认删除？"}
                        onConfirm={async () => {
                            deleteRecord(record?.id)
                        }}
                    >
                        <a>删除</a>
                    </Popconfirm> */}

                </Space >
            }
        }
    ]

    // 删除记录
    const deleteRecord = async (id: any) => {
        const data = await handleDeleteRecord({ id: id })
        if (data.Result_Code === 100) {
            message.success(data.Result_Desc)
            actionRef.current?.reload()
        }
    }

    return (
        <div style={{ backgroundColor: '#fff', display: 'flex' }}>
            <LeftSelectTree setSelectedId={setSelectedId} setCollapsible={setCollapsible} collapsible={collapsible} currentUser={currentUser} />


            <div style={{
                width: !collapsible ? 'calc(100% - 300px)' : 'calc(100% - 60px)',
                // width: "100%",
                paddingTop: 0,
                paddingBottom: 0,
                paddingRight: 0
            }}>
                <ProTable
                    actionRef={actionRef}
                    formRef={formRef}
                    columns={columns}
                    bordered
                    expandable={{
                        expandRowByClick: true
                    }}
                    rowKey={(record) => {
                        return `${record?.id}-${record?.code}-${record?.templateId}`
                    }}
                    scroll={{ x: "100%", y: 'calc(100vh - 400px)' }}
                    headerTitle={<span style={{ color: "#1890ff", fontSize: 14, fontWeight: 600 }}>考核异常记录</span>}
                    search={{ span: 6 }}
                    request={async (params) => {
                        // selectedId
                        console.log('params', params);
                        console.log('selectedId', selectedId);
                        if (!(selectedId && selectedId.length > 0)) {
                            return
                        }

                        const req: any = {
                            serverPartIds: selectedId && selectedId.length > 0 ? selectedId : [],
                            // startTime: params?.search_months ? `${moment(params?.search_months).startOf('M').format('YYYY-MM-DD')}` : "",
                            // endTime: params?.search_months ? `${moment(params?.search_months).endOf('M').format('YYYY-MM-DD')}` : "",
                            // serverPartId: params?.serverPartId ? params?.serverPartId : undefined,
                            extend: params?.errorStatus ? [{
                                key: "situation",
                                value: '1'
                            },
                            {
                                key: "errorStatus",
                                value: params?.errorStatus
                            }
                            ] : [{
                                key: "situation",
                                value: '1'
                            }]

                        }
                        console.log('req', req);
                        const data = await handleGetRecordTreeList(req)
                        console.log('data', data);

                        if (data && data.length > 0) {
                            return { data, success: true }
                        }
                        return { data: [], success: true }
                    }}
                    toolbar={{

                    }}
                    columnsState={{
                        value: columnsStateMap,
                        onChange: setColumnsStateMap,
                    }}
                >
                </ProTable>
            </div>

            {
                showImgList && showImgList.length > 0 && <div style={{ display: 'none' }}>

                    <Image.PreviewGroup

                        preview={{
                            visible: imagePreviewVisible,
                            onVisibleChange: vis => {
                                setImagePreviewVisible(vis)
                            },
                            current: previewIndex
                        }}>
                        {
                            showImgList.map((n) =>
                                <Image src={n} key={n} />
                            )
                        }
                    </Image.PreviewGroup>


                </div>
            }


            <Drawer
                title={false}
                closeIcon={false}
                onClose={() => {
                    setShowDetail(false)
                    setShowAbnormal(false)
                }}
                open={showDetail}
                destroyOnClose
                width={'60%'}
                footer={showAbnormal && currentRow?.errorStatus !== 2 ? <div style={{ width: "100%", boxSizing: 'border-box', padding: "0 24px", display: 'flex', justifyContent: 'flex-end' }}>
                    <Button type="primary" onClick={() => {
                        console.log('recordDetailRef.current?.formRes.errorStatus', recordDetailRef.current?.formRes.errorStatus);


                        if (recordDetailRef.current?.formRes.errorStatus === 0) {
                            recordDetailRef.current?.errorStatusFormRef.current?.validateFields().then(async (res: any) => {
                                console.log('res', res);
                                let extendObj = JSON.parse(recordDetailRef.current?.formRes.extend)
                                let personObj: any = {}
                                let personList: any = recordDetailRef.current?.selectPersonList
                                if (personList && personList.length > 0) {
                                    personList.forEach((item: any) => {
                                        if (item.STAFF_ID === res.personIndex) {
                                            personObj = item
                                        }
                                    })
                                }

                                console.log('personObj', personObj);


                                const req = {
                                    ...extendObj,
                                    // person: personObj,
                                    questionnaireResponsesId: recordDetailRef.current?.formRes.id,
                                    personId: personObj.STAFF_ID,
                                    personMemberShipId: personObj.MEMBERSHIP_ID,
                                    personMemberShipName: personObj.MEMBERSHIP_NAME,
                                    personName: personObj.STAFF_NAME,
                                    errorStatus: 1,
                                    suggestion: res.suggestion,
                                    suggestTime: moment().format('YYYY-MM-DD HH:mm:ss'), // 选处理人的时间
                                    // suggestPerson: {
                                    //     STAFF_NAME: currentUser.adminName,
                                    //     STAFF_ID: currentUser.id,
                                    //     MEMBERSHIP_NAME: currentUser.adminName,
                                    //     MEMBERSHIP_ID: currentUser.id,
                                    // },
                                    suggestMemberShipId: currentUser.id,
                                    suggestMemberShipName: currentUser.adminName,
                                    suggestPersonId: currentUser.id,
                                    suggestPersonName: currentUser.adminName,
                                };

                                const data = await handleUpdateExtend(req)
                                if (data.Result_Code === 100) {
                                    message.success('提交成功')
                                    setShowDetail(false)
                                    setShowAbnormal(false)
                                    actionRef.current?.reload()
                                    setCurrentRow(undefined)
                                } else {
                                    message.error(data.Result_Desc)
                                }
                            })
                        }

                        if (recordDetailRef.current?.formRes.errorStatus === 1) {
                            recordDetailRef.current?.errorStatusFormReflast.current?.validateFields().then(async (res: any) => {
                                console.log('res', res);
                                let extendObj = JSON.parse(recordDetailRef.current?.formRes.extend)

                                console.log('recordDetailRef.current?.fileList', recordDetailRef.current?.fileList);
                                let fileList: any = []
                                if (recordDetailRef.current?.fileList && recordDetailRef.current?.fileList.length > 0) {
                                    recordDetailRef.current?.fileList.forEach((item: any) => {
                                        // fileList.push(item.url)
                                        fileList.push({
                                            keyName: item.id,
                                            imageUrl: item.url
                                        })
                                        // keyName: item.id,
                                        //     imageUrl: subItem
                                    })
                                }
                                console.log('fileList', fileList);

                                const req = {
                                    ...extendObj,
                                    questionnaireResponsesId: recordDetailRef.current?.formRes.id,
                                    feedbackImgList: fileList,
                                    feedbackContent: res.feedbackContent,
                                    feedbackTime: moment().format('YYYY-MM-DD HH:mm:ss'), // 反馈时间
                                    errorStatus: 2,
                                };

                                const data = await handleUpdateExtend(req)
                                if (data.Result_Code === 100) {
                                    message.success('提交成功')
                                    setShowDetail(false)
                                    setShowAbnormal(false)
                                    actionRef.current?.reload()
                                    setCurrentRow(undefined)
                                } else {
                                    message.error(data.Result_Desc)
                                }
                            })
                        }

                    }}>提交</Button>
                </div> : false
                }
            >
                <RecordDetail onRef={recordDetailRef} parentRow={currentRow} show={showDetail} showError={showAbnormal} />
            </Drawer >
        </div >
    )
}

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