
import { ConnectState } from "@/models/global";
import { ActionType, FormInstance, ProTable } from "@ant-design/pro-components";
import { connect } from "umi";
import moment from "moment";
import { Button, Drawer, Image, message, Popconfirm, Space } from "antd";
import { useRef, useState } from "react";

const examineRecord: 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 [columnsStateMap, setColumnsStateMap] = useState<any>({
        score: { show: false }
    })



    const columns: any = [
        {
            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: 150,
            ellipsis: true,
            render: (_, record) => {
                return record?.template.serverPartName ? record?.template.serverPartName : "-"
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>站点名称</div>,
            dataIndex: "placeName",
            hideInSearch: true,
            width: 150,
            ellipsis: true,
            render: (_, record) => {
                return 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: res.situation === 1 ? "red" : "" }}>{res.situation === 1 ? '异常' : res.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 extendObj?.uploadResult ? extendObj?.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: "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: "errorStatus",
            hideInSearch: true,
            width: 100,
            ellipsis: true,
            align: 'center',
            render: (_, record) => {
                let res: any = record.extend ? JSON.parse(record.extend) : "-"
                return <span style={{ color: res.errorStatus === 0 ? "red" : res.errorStatus === 1 ? "#1677ff" : "" }}>{
                    res.errorStatus === 0
                        ? "待处理"
                        : res.errorStatus === 1
                            ? "处理中"
                            : res.errorStatus === 2
                                ? "已处理"
                                : "-"
                }</span>
            }
        },
        {
            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 = extendObj.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 <Space>
                    {
                        res.situation === 1 ?
                            <a onClick={
                                () => {
                                    setCurrentRow({
                                        ...record,
                                        ...res
                                    })
                                    setShowAbnormal(true)
                                    setShowDetail(true)
                                }
                            }>异常处理</a> : ""
                    }
                    < a onClick={() => {
                        setCurrentRow({
                            ...record,
                            ...res
                        })
                        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.code === 200) {
            message.success(data.message)
            actionRef.current?.reload()
        }
    }

    return (
        <div style={{ backgroundColor: '#fff', display: 'flex' }}>
            <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
                    }}
                    scroll={{ x: "100%", y: 'calc(100vh - 400px)' }}
                    headerTitle={<span style={{ color: "#1890ff", fontSize: 14, fontWeight: 600 }}>考核记录管理</span>}
                    search={{ span: 6 }}
                    request={async (params) => {

                    }}
                    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>
            }
        </div>
    )
}

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