<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.isOutsourcing" style="width: 120px" clearable @on-change="query(1)">
                        <Option :value="true">是</Option>
                        <Option :value="false">否</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 jobPostingsServer from '@/api/work/job_postings_server.js'

export default {
    data() {
        let rules = {}
        rules["jobTitle"] = [{ required: true, message: '请填写岗位名称', trigger: 'blur' }]
        rules["companyName"] = [{ required: true, message: '请填写公司名称', trigger: 'blur' }]
        rules["platform"] = [{ required: true, message: '请选择平台', trigger: 'change' }]

        return {
            seachTypes: [
                { key: 'jobTitle', value: '岗位名称' },
                { key: 'companyName', value: '公司名称' },
                { key: 'jobId', value: '岗位ID' }
            ],
            gridOption: {
                param: {
                    seachOption: {
                        key: 'jobTitle',
                        value: '',
                        platform: null,
                        isOutsourcing: null
                    },
                    pageOption: {
                        page: 1,
                        pageSize: 20
                    }
                },
                data: [],
                rules: rules
            },
            listColumns: [
                { title: '岗位ID', key: 'jobId', minWidth: 180 },
                { 
                    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: 180 },
                { title: '公司名称', key: 'companyName', minWidth: 180 },
                { title: '薪资', key: 'salary', minWidth: 120 },
                { title: '地点', key: 'location', minWidth: 120 },
                { title: '经验要求', key: 'experience', minWidth: 100 },
                { title: '学历要求', key: 'education', minWidth: 100 },
                { 
                    title: 'AI匹配度', 
                    key: 'aiMatchScore', 
                    minWidth: 100,
                    render: (h, params) => {
                        const score = params.row.aiMatchScore || 0
                        const color = score >= 80 ? 'success' : score >= 60 ? 'warning' : 'error'
                        return h('Tag', { props: { color: color } }, `${score}%`)
                    }
                },
                {
                    title: '是否外包',
                    key: 'isOutsourcing',
                    minWidth: 100,
                    render: (h, params) => {
                        return h('Tag', {
                            props: { color: params.row.isOutsourcing ? 'warning' : 'success' }
                        }, params.row.isOutsourcing ? '是' : '否')
                    }
                },
                {
                    title: '投递状态',
                    key: 'applyStatus',
                    minWidth: 100,
                    render: (h, params) => {
                        const statusMap = {
                            'pending': { text: '待投递', color: 'default' },
                            'applied': { text: '已投递', color: 'success' },
                            'rejected': { text: '被拒绝', color: 'error' },
                            'accepted': { text: '已接受', color: 'blue' }
                        }
                        const status = statusMap[params.row.applyStatus] || statusMap['pending']
                        return h('Tag', { props: { color: status.color } }, status.text)
                    }
                },
                { title: '发布时间', key: 'publishTime', minWidth: 150 },
                {
                    title: '操作',
                    key: 'action',
                    width: 300,
                    type: 'template',
                    render: (h, params) => {
                        const isApplied = params.row.applyStatus === 'applied'
                        let btns = [
                            {
                                title: '查看详情',
                                type: 'info',
                                click: () => {
                                    this.showJobDetail(params.row)
                                },
                            },
                            {
                                title: isApplied ? '已投递' : '打招呼',
                                type: isApplied ? 'default' : 'success',
                                disabled: isApplied,
                                click: () => {
                                    if (!isApplied) {
                                        this.jobGreet(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: '岗位ID', key: 'jobId', type: 'text', required: false },
                { title: '平台', key: 'platform', type: 'select', required: true, options: [
                    { value: 'boss', label: 'Boss直聘' },
                    { value: 'liepin', label: '猎聘' }
                ]},
                { title: '岗位名称', key: 'jobTitle', type: 'text', required: true },
                { title: '公司名称', key: 'companyName', type: 'text', required: true },
                { title: '薪资', key: 'salary', type: 'text' },
                { title: '地点', key: 'location', type: 'text' },
                { title: '经验要求', key: 'experience', type: 'text' },
                { title: '学历要求', key: 'education', type: 'text' },
                { title: '岗位描述', key: 'jobDescription', type: 'textarea' },
                { title: '岗位链接', key: 'jobUrl', type: 'text' },
                { title: 'AI匹配度', key: 'aiMatchScore', type: 'number' },
                { title: '技能匹配度', key: 'aiSkillMatch', type: 'number' },
                { title: '经验匹配度', key: 'aiExperienceMatch', type: 'number' },
                { title: '薪资合理性', key: 'aiSalaryReasonable', type: 'number' },
                { title: '公司质量评分', key: 'aiCompanyQuality', type: 'number' },
                { title: 'AI分析结果', key: 'aiAnalysisResult', type: 'textarea' },
                { title: '是否外包', key: 'isOutsourcing', type: 'switch' }
            ]
        }
    },
    mounted() {
        this.query(1)
    },
    methods: {
        query(page) {
            this.gridOption.param.pageOption.page = page
            jobPostingsServer.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 jobPostingsServer.del(row)
                this.$Message.success('删除成功！')
                this.query(1)
            })
        },
        exportCsv() {
            jobPostingsServer.exportCsv(this.gridOption.param).then(res => {
                window.framework.funTool.downloadFile(res, '岗位信息.csv')
            })
        },
        resetQuery() {
            this.gridOption.param.seachOption = {
                key: 'jobTitle',
                value: '',
                platform: null,
                isOutsourcing: null
            }
            this.query(1)
        },
        showJobDetail(row) {
            this.$Modal.info({
                title: '岗位详情',
                width: 800,
                render: (h) => {
                    return h('div', { style: { maxHeight: '500px', overflowY: 'auto' } }, [
                        h('p', [h('strong', '岗位ID: '), row.jobId]),
                        h('p', [h('strong', '平台: '), row.platform === 'boss' ? 'Boss直聘' : row.platform]),
                        h('p', [h('strong', '岗位名称: '), row.jobTitle]),
                        h('p', [h('strong', '公司名称: '), row.companyName]),
                        h('p', [h('strong', '薪资: '), row.salary || '未知']),
                        h('p', [h('strong', '地点: '), row.location || '未知']),
                        h('p', [h('strong', '经验要求: '), row.experience || '未知']),
                        h('p', [h('strong', '学历要求: '), row.education || '未知']),
                        h('p', [h('strong', 'AI匹配度: '), `${row.aiMatchScore || 0}%`]),
                        h('p', [h('strong', '是否外包: '), row.isOutsourcing ? '是' : '否']),
                        h('p', [h('strong', '发布时间: '), row.publishTime || '未知']),
                        row.jobDescription ? h('div', [
                            h('strong', '岗位描述:'),
                            h('p', { style: { whiteSpace: 'pre-wrap', marginTop: '10px' } }, row.jobDescription)
                        ]) : null,
                        row.jobUrl ? h('p', [
                            h('strong', '岗位链接: '),
                            h('a', { attrs: { href: row.jobUrl, target: '_blank' } }, row.jobUrl)
                        ]) : null
                    ])
                }
            })
        },
        jobGreet(row) {
            this.$Modal.confirm({
                title: '确认打招呼',
                content: `确定要向 ${row.companyName} 的 ${row.jobTitle} 岗位打招呼吗？`,
                onOk: async () => {
                    try {
                        const loading = this.$Message.loading({
                            content: '正在发送打招呼...',
                            duration: 0
                        })

                        // 获取设备SN码（这里需要从配置或用户选择中获取）
                        const sn_code = localStorage.getItem('current_sn_code') || 'GHJU'

                        await jobPostingsServer.jobGreet({
                            sn_code: sn_code,
                            encryptJobId: row.jobId,
                            brandName: row.companyName,
                            platform: row.platform || 'boss'
                        })

                        loading()
                        this.$Message.success('打招呼成功！')

                        // 刷新列表
                        this.query(this.gridOption.param.pageOption.page)
                    } catch (error) {
                        this.$Message.error('打招呼失败：' + (error.message || '未知错误'))
                    }
                }
            })
        }
    },
    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>

