<template>
    <div class="content-view">
        <div class="table-head-tool">
            <Button type="primary" @click="showAddWarp">新增聊天记录</Button>
            <Form ref="formInline" :model="gridOption.param.seachOption" inline :label-width="80">
                <FormItem :label-width="20" class="flex">
                    <Select v-model="gridOption.param.seachOption.key" style="width: 120px"
                        :placeholder="seachTypePlaceholder">
                        <Option v-for="item in seachTypes" :value="item.key" :key="item.key">{{ item.value }}</Option>
                    </Select>
                    <Input class="ml10" v-model="gridOption.param.seachOption.value" style="width: 200px" search
                        placeholder="请输入关键字" @on-search="query(1)" />
                </FormItem>
                <FormItem label="平台">
                    <Select v-model="gridOption.param.seachOption.platform" style="width: 120px" clearable @on-change="query(1)">
                        <Option value="boss">Boss直聘</Option>
                        <Option value="liepin">猎聘</Option>
                    </Select>
                </FormItem>
                <FormItem label="消息类型">
                    <Select v-model="gridOption.param.seachOption.messageType" style="width: 120px" clearable @on-change="query(1)">
                        <Option value="sent">发送</Option>
                        <Option value="received">接收</Option>
                        <Option value="system">系统</Option>
                    </Select>
                </FormItem>
                <FormItem>
                    <Button type="primary" @click="query(1)">查询</Button>
                    <Button type="default" @click="resetQuery" class="ml10">重置</Button>
                    <Button type="default" @click="exportCsv">导出</Button>
                </FormItem>
            </Form>
        </div>
        <div class="table-body">
            <tables :columns="listColumns" :value="gridOption.data" :pageOption="gridOption.param.pageOption"
                @changePage="query"></tables>
        </div>
        <editModal ref="editModal" :columns="editColumns" :rules="gridOption.rules"></editModal>
    </div>
</template>

<script>
import chatRecordsServer from '@/api/operation/chat_records_server.js'

export default {
    data() {
        let rules = {}
        rules["sn_code"] = [{ required: true, message: '请填写设备SN码', trigger: 'blur' }]
        rules["platform"] = [{ required: true, message: '请选择平台', trigger: 'change' }]
        rules["messageContent"] = [{ required: true, message: '请填写消息内容', trigger: 'blur' }]

        return {
            replyContent: '',
            seachTypes: [
                { key: 'companyName', value: '公司名称' },
                { key: 'contactName', value: '联系人' },
                { key: 'sn_code', value: '设备SN码' }
            ],
            gridOption: {
                param: {
                    seachOption: {
                        key: 'companyName',
                        value: '',
                        platform: null,
                        messageType: null
                    },
                    pageOption: {
                        page: 1,
                        pageSize: 20
                    }
                },
                data: [],
                rules: rules
            },
            listColumns: [
                { title: 'ID', key: 'id', minWidth: 80 },
                { title: '设备SN码', key: 'sn_code', minWidth: 120 },
                { 
                    title: '平台', 
                    key: 'platform', 
                    minWidth: 100,
                    render: (h, params) => {
                        const platformMap = {
                            'boss': { text: 'Boss直聘', color: 'blue' },
                            'liepin': { text: '猎聘', color: 'green' }
                        }
                        const platform = platformMap[params.row.platform] || { text: params.row.platform, color: 'default' }
                        return h('Tag', { props: { color: platform.color } }, platform.text)
                    }
                },
                { title: '岗位名称', key: 'jobTitle', minWidth: 150 },
                { title: '公司名称', key: 'companyName', minWidth: 150 },
                { title: '联系人', key: 'contactName', minWidth: 120 },
                { 
                    title: '消息类型', 
                    key: 'messageType', 
                    minWidth: 100,
                    render: (h, params) => {
                        const typeMap = {
                            'sent': { text: '发送', color: 'blue' },
                            'received': { text: '接收', color: 'success' },
                            'system': { text: '系统', color: 'default' }
                        }
                        const type = typeMap[params.row.messageType] || { text: params.row.messageType, color: 'default' }
                        return h('Tag', { props: { color: type.color } }, type.text)
                    }
                },
                { title: '消息内容', key: 'messageContent', minWidth: 250 },
                { title: '发送时间', key: 'sendTime', minWidth: 150 },
                {
                    title: '操作',
                    key: 'action',
                    width: 300,
                    type: 'template',
                    render: (h, params) => {
                        let btns = [
                            {
                                title: '查看详情',
                                type: 'info',
                                click: () => {
                                    this.showChatDetail(params.row)
                                },
                            },
                            {
                                title: '回复',
                                type: 'success',
                                click: () => {
                                    this.replyMessage(params.row)
                                },
                            },
                            {
                                title: '编辑',
                                type: 'primary',
                                click: () => {
                                    this.showEditWarp(params.row)
                                },
                            },
                            {
                                title: '删除',
                                type: 'error',
                                click: () => {
                                    this.delConfirm(params.row)
                                },
                            },
                        ]
                        return window.framework.uiTool.getBtn(h, btns)
                    },
                }
            ],
            editColumns: [
                { title: '设备SN码', key: 'sn_code', type: 'text', required: true },
                { title: '平台', key: 'platform', type: 'select', required: true, options: [
                    { value: 'boss', label: 'Boss直聘' },
                    { value: 'liepin', label: '猎聘' }
                ]},
                { title: '投递记录ID', key: 'applyId', type: 'text' },
                { title: '岗位名称', key: 'jobTitle', type: 'text' },
                { title: '公司名称', key: 'companyName', type: 'text' },
                { title: '联系人', key: 'contactName', type: 'text' },
                { title: '消息类型', key: 'messageType', type: 'select', options: [
                    { value: 'sent', label: '发送' },
                    { value: 'received', label: '接收' },
                    { value: 'system', label: '系统' }
                ]},
                { title: '消息内容', key: 'messageContent', type: 'textarea', required: true },
                { title: '是否已读', key: 'isRead', type: 'switch' }
            ]
        }
    },
    mounted() {
        this.query(1)
    },
    methods: {
        query(page) {
            this.gridOption.param.pageOption.page = page
            chatRecordsServer.page(this.gridOption.param).then(res => {
                this.gridOption.data = res.data.rows
                this.gridOption.param.pageOption.total = res.data.count
            })
        },
        showAddWarp() {
            this.$refs.editModal.showModal()
        },
        showEditWarp(row) {
            this.$refs.editModal.showModal(row)
        },
        delConfirm(row) {
            window.framework.uiTool.delConfirm(async () => {
                await chatRecordsServer.del(row)
                this.$Message.success('删除成功！')
                this.query(1)
            })
        },
        exportCsv() {
            chatRecordsServer.exportCsv(this.gridOption.param).then(res => {
                window.framework.funTool.downloadFile(res, '聊天记录.csv')
            })
        },
        resetQuery() {
            this.gridOption.param.seachOption = {
                key: 'companyName',
                value: '',
                platform: null,
                messageType: null
            }
            this.query(1)
        },
        showChatDetail(row) {
            this.$Modal.info({
                title: '聊天记录详情',
                width: 800,
                render: (h) => {
                    return h('div', { style: { maxHeight: '500px', overflowY: 'auto' } }, [
                        h('h3', { style: { marginBottom: '15px', color: '#2d8cf0' } }, '基本信息'),
                        h('p', [h('strong', '设备SN码: '), row.sn_code || '未知']),
                        h('p', [h('strong', '平台: '), row.platform === 'boss' ? 'Boss直聘' : row.platform === 'liepin' ? '猎聘' : row.platform]),
                        h('p', [h('strong', '岗位名称: '), row.jobTitle || '未知']),
                        h('p', [h('strong', '公司名称: '), row.companyName || '未知']),
                        h('p', [h('strong', '联系人: '), row.contactName || '未知']),

                        h('h3', { style: { marginTop: '20px', marginBottom: '15px', color: '#2d8cf0' } }, '消息信息'),
                        h('p', [h('strong', '消息类型: '), this.getMessageTypeText(row.messageType)]),
                        h('p', [h('strong', '发送时间: '), row.sendTime || '未知']),
                        h('p', [h('strong', '是否已读: '), row.isRead ? '是' : '否']),

                        h('div', { style: { marginTop: '20px' } }, [
                            h('strong', '消息内容:'),
                            h('div', {
                                style: {
                                    whiteSpace: 'pre-wrap',
                                    marginTop: '10px',
                                    padding: '15px',
                                    backgroundColor: '#f5f5f5',
                                    borderRadius: '4px',
                                    border: '1px solid #e8e8e8'
                                }
                            }, row.messageContent)
                        ])
                    ])
                }
            })
        },
        replyMessage(row) {
            this.$Modal.confirm({
                title: '回复消息',
                render: (h) => {
                    return h('div', [
                        h('p', { style: { marginBottom: '10px' } }, [
                            h('strong', '回复给: '),
                            `${row.companyName} - ${row.contactName || 'HR'}`
                        ]),
                        h('p', { style: { marginBottom: '10px' } }, [
                            h('strong', '原消息: '),
                            row.messageContent
                        ]),
                        h('Input', {
                            props: {
                                type: 'textarea',
                                rows: 4,
                                placeholder: '请输入回复内容'
                            },
                            on: {
                                input: (val) => {
                                    this.replyContent = val
                                }
                            }
                        })
                    ])
                },
                onOk: async () => {
                    if (!this.replyContent) {
                        this.$Message.warning('请输入回复内容')
                        return
                    }

                    try {
                        const loading = this.$Message.loading({
                            content: '正在发送消息...',
                            duration: 0
                        })

                        const sn_code = row.sn_code || localStorage.getItem('current_sn_code') || 'GHJU'

                        await chatRecordsServer.sendMessage({
                            sn_code: sn_code,
                            jobId: row.jobId,
                            content: this.replyContent,
                            chatType: 'reply',
                            platform: row.platform
                        })

                        loading()
                        this.$Message.success('消息发送成功！')
                        this.replyContent = ''
                        this.query(this.gridOption.param.pageOption.page)
                    } catch (error) {
                        this.$Message.error('消息发送失败：' + (error.message || '未知错误'))
                    }
                }
            })
        },
        getMessageTypeText(type) {
            const typeMap = {
                'sent': '发送',
                'received': '接收',
                'system': '系统'
            }
            return typeMap[type] || type
        }
    },
    computed: {
        seachTypePlaceholder() {
            const selected = this.seachTypes.find(item => item.key === this.gridOption.param.seachOption.key)
            return selected ? selected.value : '请选择搜索类型'
        }
    }
}
</script>

<style scoped>
.ml10 {
    margin-left: 10px;
}

.flex {
    display: flex;
    align-items: center;
}
</style>

