<template>
    <div class="content-view">
        <!-- 任务列表主页面 -->
        <div v-show="!showCommandsView" class="task-list-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.taskType" style="width: 120px" clearable @on-change="query(1)">
                            <Option value="search">搜索岗位</Option>
                            <Option value="apply">投递简历</Option>
                            <Option value="chat">聊天回复</Option>
                            <Option value="follow">跟进</Option>
                        </Select>
                    </FormItem>
                    <FormItem label="任务状态">
                        <Select v-model="gridOption.param.seachOption.status" style="width: 120px" clearable @on-change="query(1)">
                            <Option value="pending">待执行</Option>
                            <Option value="running">执行中</Option>
                            <Option value="success">成功</Option>
                            <Option value="failed">失败</Option>
                            <Option value="cancelled">已取消</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>
        </div>

        <!-- 指令列表详情页面 -->
        <CommandsList 
            v-show="showCommandsView" 
            :visible="showCommandsView"
            :title="commandsModal.title"
            :loading="commandsModal.loading"
            :data="commandsModal.data"
            @back="backToTaskList" />


        <editModal ref="editModal" :columns="editColumns" :rules="gridOption.rules"></editModal>
    </div>
</template>

<script>
import taskStatusServer from '@/api/operation/task_status_server.js'
import CommandsList from './components/CommandsList.vue'

export default {
    components: {
        CommandsList
    },
    data() {
        let rules = {}
        rules["taskType"] = [{ required: true, message: '请选择任务类型', trigger: 'change' }]
        rules["sn_code"] = [{ required: true, message: '请填写设备SN码', trigger: 'blur' }]

        return {
            seachTypes: [
                { key: 'taskName', value: '任务名称' },
                { key: 'sn_code', value: '设备SN码' },
                { key: 'id', value: '任务ID' }
            ],
            showCommandsView: false, // 是否显示指令列表视图
            gridOption: {
                param: {
                    seachOption: {
                        key: 'taskName',
                        value: '',
                        taskType: null,
                        status: null
                    },
                    pageOption: {
                        page: 1,
                        pageSize: 20
                    }
                },
                data: [],
                rules: rules
            },
            listColumns: [
                { title: '任务ID', key: 'id', minWidth: 180 },
                { title: '设备SN码', key: 'sn_code', minWidth: 120 },
                { 
                    title: '任务类型', 
                    key: 'taskType', 
                    minWidth: 100,
                    render: (h, params) => {
                        const typeMap = {
                            'search': { text: '搜索岗位', color: 'blue' },
                            'apply': { text: '投递简历', color: 'success' },
                            'chat': { text: '聊天回复', color: 'purple' },
                            'follow': { text: '跟进', color: 'orange' }
                        }
                        const type = typeMap[params.row.taskType] || { text: params.row.taskType, color: 'default' }
                        return h('Tag', { props: { color: type.color } }, type.text)
                    }
                },
                { title: '任务名称', key: 'taskName', minWidth: 150 },
                { 
                    title: '任务状态', 
                    key: 'status', 
                    minWidth: 100,
                    render: (h, params) => {
                        const statusMap = {
                            'pending': { text: '待执行', color: 'default' },
                            'running': { text: '执行中', color: 'blue' },
                            'success': { text: '成功', color: 'success' },
                            'failed': { text: '失败', color: 'error' },
                            'cancelled': { text: '已取消', color: 'warning' }
                        }
                        const status = statusMap[params.row.status] || { text: params.row.status, color: 'default' }
                        return h('Tag', { props: { color: status.color } }, status.text)
                    }
                },
                { title: '进度', key: 'progress', minWidth: 100 },
                { title: '开始时间', key: 'startTime', minWidth: 150 },
                { title: '结束时间', key: 'endTime', minWidth: 150 },
                { title: '创建时间', key: 'create_time', minWidth: 150 },
                { 
                    title: '操作', 
                    key: 'action', 
                    width: 360,
                    type: 'template',
                    render: (h, params) => {
                        let btns = [
                            {
                                title: '指令列表',
                                type: 'info',
                                click: () => {
                                    this.showCommands(params.row)
                                },
                            },
                            {
                                title: '编辑',
                                type: 'primary',
                                click: () => {
                                    this.showEditWarp(params.row)
                                },
                            }
                        ]
                        
                        if (params.row.status === 'failed') {
                            btns.push({
                                title: '重试',
                                type: 'success',
                                click: () => {
                                    this.retryTask(params.row)
                                },
                            })
                        }
                        
                        if (params.row.status === 'pending' || params.row.status === 'running') {
                            btns.push({
                                title: '取消',
                                type: 'warning',
                                click: () => {
                                    this.cancelTask(params.row)
                                },
                            })
                        }
                        
                        btns.push({
                            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: 'taskType', type: 'select', required: true, options: [
                    { value: 'search', label: '搜索岗位' },
                    { value: 'apply', label: '投递简历' },
                    { value: 'chat', label: '聊天回复' },
                    { value: 'follow', label: '跟进' }
                ]},
                { title: '任务名称', key: 'taskName', type: 'text' },
                { title: '任务描述', key: 'taskDescription', type: 'textarea' },
                { title: '任务参数', key: 'taskParams', type: 'textarea' },
                { title: '优先级', key: 'priority', type: 'number' },
                { title: '最大重试次数', key: 'maxRetries', type: 'number' },
                { title: '计划执行时间', key: 'scheduledTime', type: 'datetime' }
            ],
            commandsModal: {
                loading: false,
                title: '指令列表',
                data: []
            }
        }
    },
    mounted() {
        this.query(1)
    },
    methods: {
        query(page) {
            this.gridOption.param.pageOption.page = page
            taskStatusServer.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)
        },
        cancelTask(row) {
            this.$Modal.confirm({
                title: '确认取消任务',
                content: `确定要取消任务 "${row.taskName}" 吗？`,
                onOk: async () => {
                    try {
                        await taskStatusServer.cancel(row)
                        this.$Message.success('任务取消成功！')
                        this.query(this.gridOption.param.pageOption.page)
                    } catch (error) {
                        this.$Message.error('任务取消失败')
                    }
                }
            })
        },
        retryTask(row) {
            this.$Modal.confirm({
                title: '确认重试任务',
                content: `确定要重试任务 "${row.taskName}" 吗？`,
                onOk: async () => {
                    try {
                        await taskStatusServer.retry(row)
                        this.$Message.success('任务重试成功！')
                        this.query(this.gridOption.param.pageOption.page)
                    } catch (error) {
                        this.$Message.error('任务重试失败')
                    }
                }
            })
        },
        delConfirm(row) {
            window.framework.uiTool.delConfirm(async () => {
                await taskStatusServer.del(row)
                this.$Message.success('删除成功！')
                this.query(1)
            })
        },
        exportCsv() {
            taskStatusServer.exportCsv(this.gridOption.param).then(res => {
                window.framework.funTool.downloadFile(res, '任务状态.csv')
            })
        },
        resetQuery() {
            this.gridOption.param.seachOption = {
                key: 'taskName',
                value: '',
                taskType: null,
                status: null
            }
            this.query(1)
        },
        async showCommands(row) {
            this.showCommandsView = true
            this.commandsModal.loading = true
            this.commandsModal.title = `指令列表 - 任务ID: ${row.id} (${row.taskName})`
            
            try {
                const res = await taskStatusServer.getCommands(row.id)
                this.commandsModal.data = res.data || []
            } catch (error) {
                this.$Message.error('获取指令列表失败')
                this.commandsModal.data = []
            } finally {
                this.commandsModal.loading = false
            }
        },
        backToTaskList() {
            this.showCommandsView = false
        }
    },
    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;
}

/* 任务列表视图 */
.task-list-view {
    width: 100%;
    height: 100%;
}
</style>

