import { message, Modal,Table, Space } from "antd";
import { FolderAddOutlined } from '@ant-design/icons';
// import locale from 'antd/es/date-picker/locale/zh_CN';
// import { useParams } from "react-router-dom";
import { useEffect, useState } from "react";
// import { get, put, post, del, downloadUrl } from "../../../util/AjaxUtils.ts";
import {
    get, put, post, del,
    downloadUrl
} from "../../util/AjaxUtils.ts";
import { Button, Form, Input } from 'antd';
import { AxiosResponse } from "axios";

import type { SearchProps } from 'antd/es/input/Search';
// import type { TableColumnsType } from 'antd';

type ContactType = {
    csaNo: string
    gmtCreate: string
    gmtModified: string
    name: string
    phone: string
    projContactId: string
    email: string
    company: string
}
const { Search } = Input;
const { Column } = Table;

export default function ContactPeople() {
    const [messageApi, contextHolder] = message.useMessage();
    const [formContact] = Form.useForm<ContactType>()
    const height = window.innerHeight - 200;
    const [isContantOpen, steIsContantOpen] = useState(false)
    // 联系人弹窗标题
    const [contactTitle, setContactTitle] = useState('')
    // 客服二维码
    const [imgUrl, setImgUrl] = useState('')
    // 联系人搜索关键字
    const [peopleKeyWords, setPeopleKeyWords] = useState('')
    // 联系人表格数据
    const [tableContactData, setTableContactData] = useState<ContactDataType[]>([])
    // 联系人id 关键字
    const [contactId, setContactId] = useState('')
    // 申请人信息搜索 applicantPeopleSearch
    const applicantPeopleSearch: SearchProps['onSearch'] = (value, _e, info) => (
        console.log(info?.source, value),
        // alert(value),
        setPeopleKeyWords(value),
        getSearchProjContactList(value)
    );
    // 获取联系人表格
    const getProjContactList = () => {
        get({
            messageApi,
            url: `/api/proj-contact/list/self`,
            onSuccess({ data }: AxiosResponse) {
                console.log('联系人表格', data);
                // setTableBelongData(data)
                setTableContactData(data)
            }
        })
    }
    // 获取联系人表格 带搜索
    const getSearchProjContactList = (keywords: any) => {
        get({
            messageApi,
            url: `/api/proj-contact/list/self?keywords=${keywords}`,
            onSuccess({ data }: AxiosResponse) {
                // console.log('联系人表格', data);
                // setTableBelongData(data)
                setTableContactData(data)
            }
        })
    }
    // 点击创建联系热人获取随机客服
    const getCas = () => {
        get({
            messageApi,
            url: `/api/csa/get`,
            onSuccess({ data }: AxiosResponse) {
                console.log('随机客服信息二维码', data.casQrCode);
                formContact.setFieldsValue({
                    csaNo: data.csaNo
                });
                if (data.casQrCode) {
                    const imgUrl = downloadUrl(data.casQrCode);
                    console.log('图片地址', imgUrl);
                    setImgUrl(imgUrl)
                }

            }
        })
    }
    // 创建联系人
    const newContact = () => {
        post({
            messageApi,
            url: '/api/proj-contact/save',
            body: {
                csaNo: formContact.getFieldValue('csaNo'),
                name: formContact.getFieldValue('name'),
                phone: formContact.getFieldValue('phone'),
                email: formContact.getFieldValue('email'),
                company: formContact.getFieldValue('company')
            },
            onBefore() {

            },
            onSuccess() {
                messageApi.success('提交成功')
                getProjContactList()
                steIsContantOpen(false)
            },
            onFinally() {
            }
        })
    }
    // 编辑联系人
    const upContact = () => {
        put({
            messageApi,
            url: `/api/proj-contact/update/${contactId}`,
            body: {
                csaNo: formContact.getFieldValue('csaNo'),
                name: formContact.getFieldValue('name'),
                phone: formContact.getFieldValue('phone'),
                email: formContact.getFieldValue('email'),
                company: formContact.getFieldValue('company')
            },
            onBefore() {
            },
            onSuccess() {
                // console.log(data);
                // alert('编辑成功')
                messageApi.open({
                    type: 'success',
                    content: '编辑成功'
                })
                // getProjContactList()
                getSearchProjContactList(peopleKeyWords)
                steIsContantOpen(false)

            },
            onFinally() {
            }
        })
    }
    // 联系人人表单信息 点击确定
    const contactHandleOk = () => {
        // alert('联系热确定')
        formContact.validateFields().then(() => {
            // 如果验证通过，则执行确认操作
            // 这里可以放置你的确认操作逻辑
            if (contactTitle === '编辑联系人') {
                upContact()
            }
            if (contactTitle === '创建联系人') {
                newContact()
            }
            // 关闭 弹窗
            // setIsNewBelongOpen(false)
            // 初始化数据
            formContact.resetFields(); // 重置表单字段为初始值

        }).catch(() => {
            // 如果验证不通过，可以根据需要处理错误信息
            // (errorInfo);
        });
    };
    useEffect(() => {

        getProjContactList()

    }, [])
    return (
        <div style={{ height: `${height - 175}px`, overflow: 'auto' }}>
            {contextHolder}
            <div style={{ padding: '22px 15px 0 15px',background: 'var(--color-light)' }}>
                <div style={{ padding: '14px 19px', background: '#F3F3F3', color: '#A3A3A3', fontSize: '14px' }}>
                    联系人用于接受平台相关业务办理进度的通知信息与各类协议的线下签章等工作。
                </div>
                <div className='belongPeople-center'>
                    <Button onClick={() => {
                        formContact.resetFields()
                        getCas()
                        steIsContantOpen(true)
                        setContactTitle('创建联系人')

                    }} type="primary" icon={<FolderAddOutlined style={{ fontSize: '18px' }} />} style={{ width: "160px", height: '43px', fontSize: '14px' }}>
                        创建联系人
                    </Button>
                    <div className='belongPeople-search'>
                        <Search placeholder="请输入持有者名称搜索对应信息" onSearch={applicantPeopleSearch} style={{ width: '353px', height: '43px' }} />
                    </div>
                </div>

                <div className='belongPeople-bot'>
                    {/* 表格 lyp*/}
                    <Table

                        dataSource={tableContactData}
                        pagination={{
                            defaultPageSize: 5, // 设置默认一页显示 5 条数据
                        }}
                        style={{ textAlign: 'center' }} // 设置表格内容居中显示
                        rowKey="projContactId" // 指定数据项的唯一标识符
                    >
                        <Column title="联系人" dataIndex="name" />
                        <Column title="联系人手机号" dataIndex="phone" />
                        <Column title="平台专属客服" dataIndex="csaNo" />
                        <Column title="所属公司" dataIndex="company"
                            render={(text) => (text !== '' ? text : '一')}
                        />

                        {/* <Column title="实名认证状态" dataIndex="address" key="key" /> */}
                        <Column
                            title="操作"
                            render={(text, record: any) => (
                                <Space size="middle">
                                    <a onClick={() => {
                                        // alert(record.projOwnerId);

                                        console.log('text:', text);
                                        console.log('record:', record);

                                        setContactId(record.projContactId)
                                        setContactTitle('编辑联系人')
                                        steIsContantOpen(true)
                                        // formContact 表单赋值
                                        formContact.setFieldsValue({
                                            csaNo: record.csaNo,
                                            name: record.name,
                                            phone: record.phone,
                                            email: record.email,
                                            company: record.company
                                        })
                                    }}>编辑 </a>
                                    <span style={{ color: '#3472EE' }}>|</span>
                                    <a onClick={() => {
                                        // alert(record.projOwnerId); 
                                        del({
                                            messageApi,
                                            url: `/api/proj-contact/remove/${record.projContactId}`,
                                            onSuccess() {
                                                messageApi.success('删除成功');
                                                getProjContactList()
                                            }
                                        })
                                    }}>删除</a>
                                    <span style={{ color: '#3472EE' }}>|</span>
                                    <a onClick={() => {
                                        setContactTitle('查看联系人')
                                        steIsContantOpen(true)
                                        formContact.setFieldsValue({
                                            csaNo: record.csaNo,
                                            name: record.name,
                                            phone: record.phone,
                                            email: record.email

                                        })
                                    }}>查看</a>

                                </Space>
                            )}
                        />
                    </Table>

                </div>
            </div>
            {/* 选择创建/编辑/查看联系人弹框 lyp*/}
            <Modal
                destroyOnClose
                okText="确认"
                // cancelText="取消"
                cancelText={contactTitle === '查看联系人' ? '返回' : '取消'}
                open={isContantOpen}
                // 点击确认上传事件
                // onOk={() => {
                // }}
                onOk={
                    contactHandleOk
                }
                width={745}
                // 确认按钮样式
                okButtonProps={{ size: 'large', style: { display: contactTitle == '查看联系人' ? 'none' : 'block' } }}
                // 返回按钮样式
                cancelButtonProps={{ size: 'large', style: {} }}

                onCancel={() => {
                    steIsContantOpen(false)
                    getSearchProjContactList(peopleKeyWords)
                }}
            >
                <div className='belongPeople-Modal'>
                    <div className='belongPeople-Mtop'>
                        {contactTitle}
                    </div>
                    <div className='contact-modal-context'>
                        <div>
                            <Form
                                name="contactInfo"
                                form={formContact}
                                layout="vertical"
                                labelCol={{ span: 8 }}
                                wrapperCol={{ span: 24 }}
                                style={{ width: '100%', }}
                                onFinish={() => {
                                    // setIsNewBelongOpen(true);   
                                }}
                                autoComplete="off"
                            >
                                <div className='blongNameInt'>
                                    <div className='blongTitle ' style={{ width: 65, marginRight: '15px' }}>姓名: </div>


                                    <Form.Item<ContactType>
                                        name="name"
                                        rules={[{ required: true, message: '请输入姓名' }]}
                                    >
                                        <Input placeholder="请输入姓名"
                                            style={{ height: '44px', width: '384px', fontSize: '15px', marginTop: '22px' }}

                                            disabled={contactTitle == '查看联系人' ? true : false}
                                        />
                                    </Form.Item>
                                </div>
                                <div className='blongNameInt'>
                                    <div className='blongTitle ' style={{ width: 65, marginRight: '15px' }}>电话: </div>

                                    <Form.Item<ContactType>
                                        name="phone"
                                        rules={[{ required: true, message: '请输入电话号码' }]}
                                    >
                                        <Input placeholder="请输入电话号码"
                                            style={{ height: '44px', width: '384px', fontSize: '15px', marginTop: '22px' }}

                                            disabled={contactTitle == '查看联系人' ? true : false}
                                        />
                                    </Form.Item>
                                </div>
                                <div className='blongNameInt'>
                                    <div className='blongTitle ' style={{ width: 65, marginRight: '15px' }}>所属公司: </div>

                                    <Form.Item<ContactType>
                                        name="company"
                                        rules={[{ required: false, message: '请输入所属公司' }]}
                                    >
                                        <Input placeholder="请输入所属公司"
                                            style={{ height: '44px', width: '384px', fontSize: '15px', marginTop: '22px' }}

                                            disabled={contactTitle == '查看联系人' ? true : false}
                                        />

                                    </Form.Item>
                                </div>
                                <div className='blongNameInt'>
                                    <div className='blongTitle ' style={{ width: 65, marginRight: '15px' }}>邮箱: </div>

                                    <Form.Item<ContactType>
                                        name="email"
                                        rules={[{ required: false, message: '请输入邮箱' },
                                        { type: 'email', message: '请输入有效的邮箱地址' }
                                        ]}
                                    >
                                        <Input placeholder="请输入邮箱"
                                            style={{ height: '44px', width: '384px', fontSize: '15px', marginTop: '22px' }}

                                            disabled={contactTitle == '查看联系人' ? true : false}
                                        />
                                    </Form.Item>
                                </div>
                                <div
                                    style={{ display: 'none' }}
                                >
                                    <Form.Item<ContactType>
                                        name="csaNo"
                                    >
                                        <Input placeholder="客服编码 需隐藏"
                                            style={{ height: '44px', width: '384px', fontSize: '15px', }}

                                            disabled={contactTitle == '查看联系人' ? true : false}
                                        />
                                    </Form.Item>
                                </div>



                            </Form>
                        </div>
                        <div className='cas' style={{
                            display: contactTitle == '创建联系人' ? 'block' : 'none'
                        }}>
                            <div className='cas-title'>
                                请使用微信扫一扫
                            </div>
                            <div className='cas-text'>
                                添加您的专属客服
                            </div>
                            <img src={imgUrl} alt="" width={137} height={138} />
                        </div>
                    </div>
                </div>

            </Modal >
        </div>
    )
}
