<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.is_enabled" style="width: 120px" clearable
                        @on-change="query(1)">
                        <Option :value="1">启用</Option>
                        <Option :value="0">禁用</Option>
                    </Select>
                </FormItem>
                <FormItem>
                    <Button type="primary" @click="query(1)">查询</Button>
                    <Button type="default" @click="resetQuery" class="ml10">重置</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" @on-save="handleSaveSuccess">
        </editModal>
    </div>
</template>

<script>
import jobTypesServer from '@/api/work/job_types_server.js'

export default {
    data() {
        let rules = {}
        rules["name"] = [{ required: true, message: '请填写职位类型名称', trigger: 'blur' }]

        return {
            seachTypes: [
                { key: 'name', value: '职位类型名称' },
                { key: 'description', value: '描述' }
            ],
            gridOption: {
                param: {
                    seachOption: {
                        key: 'name',
                        value: '',
                        is_enabled: null
                    },
                    pageOption: {
                        page: 1,
                        pageSize: 20
                    }
                },
                data: [],
                rules: rules
            },
            listColumns: [
                { title: 'ID', key: 'id', minWidth: 80 },
                { title: '职位类型名称', key: 'name', minWidth: 150 },
                { title: '描述', key: 'description', minWidth: 200 },
                {
                    title: '状态',
                    key: 'is_enabled',
                    minWidth: 100,
                    render: (h, params) => {
                        const status = params.row.is_enabled === 1
                        return h('Tag', { props: { color: status ? 'success' : 'default' } }, status ? '启用' : '禁用')
                    }
                },
                {
                    title: '常见技能关键词', key: 'commonSkills', minWidth: 200,
                },
                {
                    title: '排除关键词', key: 'excludeKeywords', minWidth: 200
                },
                { title: '排序', key: 'sort_order', minWidth: 80 },
                {
                    title: '操作',
                    key: 'action',
                    width: 200,
                    align: 'center',
                    render: (h, params) => {
                        return h('div', [
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: () => {
                                        this.edit(params.row)
                                    }
                                }
                            }, '编辑'),
                            h('Button', {
                                props: {
                                    type: 'error',
                                    size: 'small'
                                },
                                on: {
                                    click: () => {
                                        this.del(params.row)
                                    }
                                }
                            }, '删除')
                        ])
                    }
                }
            ],
            editColumns: [
                {
                    title: '职位类型名称',
                    key: 'name',
                    type: 'input',
                    required: true
                },
                {
                    title: '描述',
                    key: 'description',
                    com: 'TextArea',
                    required: false
                },
                {
                    title: '常见技能关键词',
                    key: 'commonSkills',
                    com: 'TextArea',

                    required: false,
                    placeholder: '请输入JSON数组格式，例如：["Vue", "React", "Node.js"]',
                    tooltip: '技能关键词列表，JSON数组格式'
                },
                {
                    title: '排除关键词',
                    key: 'excludeKeywords',
                    com: 'TextArea',
                    required: false,
                    placeholder: '请输入JSON数组格式，例如：["外包", "销售", "客服"]',
                    tooltip: '排除关键词列表，JSON数组格式'
                },
                {
                    title: '是否启用',
                    key: 'is_enabled',
                    type: 'select',
                    required: true,
                    options: [
                        { value: 1, label: '启用' },
                        { value: 0, label: '禁用' }
                    ]
                },
                {
                    title: '排序顺序',
                    key: 'sort_order',
                    type: 'number',
                    required: false,
                    defaultValue: 0
                }
            ]
        }
    },
    computed: {
        seachTypePlaceholder() {
            const item = this.seachTypes.find(item => item.key === this.gridOption.param.seachOption.key)
            return item ? `请输入${item.value}` : '请选择'
        }
    },
    mounted() {
        this.query(1)
    },
    methods: {
        query(page) {
            if (page) {
                this.gridOption.param.pageOption.page = page
            }
            const param = {
                pageOption: this.gridOption.param.pageOption,
                seachOption: {}
            }
            if (this.gridOption.param.seachOption.key && this.gridOption.param.seachOption.value) {
                param.seachOption[this.gridOption.param.seachOption.key] = this.gridOption.param.seachOption.value
            }
            if (this.gridOption.param.seachOption.is_enabled !== null) {
                param.seachOption.is_enabled = this.gridOption.param.seachOption.is_enabled
            }
            jobTypesServer.page(param).then(res => {
                if (res.code === 0) {
                    const data = res.data
                    this.gridOption.data = data.rows
                    this.gridOption.param.pageOption.total = data.count || data.total || 0
                } else {
                    this.$Message.error(res.message || '查询失败')
                }
            }).catch(err => {
                this.$Message.error('查询失败：' + (err.message || '未知错误'))
            })
        },
        resetQuery() {
            this.gridOption.param.seachOption = {
                key: 'name',
                value: '',
                is_enabled: null
            }
            this.query(1)
        },
        showAddWarp() {
            this.$refs.editModal.show({
                name: '',
                description: '',
                commonSkills: '[]',
                excludeKeywords: '[]',
                is_enabled: 1,
                sort_order: 0
            })
        },
        edit(row) {
            // 解析 JSON 字段
            let commonSkills = row.commonSkills || '[]'
            let excludeKeywords = row.excludeKeywords || '[]'

            // 如果是字符串，尝试解析并格式化
            if (typeof commonSkills === 'string') {
                try {
                    const parsed = JSON.parse(commonSkills)
                    commonSkills = JSON.stringify(parsed, null, 2)
                } catch (e) {
                    // 保持原样
                }
            } else {
                commonSkills = JSON.stringify(commonSkills, null, 2)
            }

            if (typeof excludeKeywords === 'string') {
                try {
                    const parsed = JSON.parse(excludeKeywords)
                    excludeKeywords = JSON.stringify(parsed, null, 2)
                } catch (e) {
                    // 保持原样
                }
            } else {
                excludeKeywords = JSON.stringify(excludeKeywords, null, 2)
            }

            this.$refs.editModal.editShow({
                id: row.id,
                name: row.name,
                description: row.description || '',
                commonSkills: commonSkills,
                excludeKeywords: excludeKeywords,
                is_enabled: row.is_enabled,
                sort_order: row.sort_order || 0
            })
        },
        del(row) {
            this.$Modal.confirm({
                title: '确认删除',
                content: `确定要删除职位类型"${row.name}"吗？`,
                onOk: () => {
                    jobTypesServer.del(row).then(res => {
                        if (res.code === 0) {
                            this.$Message.success('删除成功')
                            this.query(this.gridOption.param.pageOption.page)
                        } else {
                            this.$Message.error(res.message || '删除失败')
                        }
                    }).catch(err => {
                        this.$Message.error('删除失败：' + (err.message || '未知错误'))
                    })
                }
            })
        },
        handleSaveSuccess(data) {
            // 处理 JSON 字段
            const formData = { ...data }

            // 处理 commonSkills
            if (formData.commonSkills) {
                try {
                    const parsed = typeof formData.commonSkills === 'string'
                        ? JSON.parse(formData.commonSkills)
                        : formData.commonSkills
                    formData.commonSkills = Array.isArray(parsed) ? parsed : []
                } catch (e) {
                    this.$Message.warning('常见技能关键词格式错误，将使用空数组')
                    formData.commonSkills = []
                }
            }

            // 处理 excludeKeywords
            if (formData.excludeKeywords) {
                try {
                    const parsed = typeof formData.excludeKeywords === 'string'
                        ? JSON.parse(formData.excludeKeywords)
                        : formData.excludeKeywords
                    formData.excludeKeywords = Array.isArray(parsed) ? parsed : []
                } catch (e) {
                    this.$Message.warning('排除关键词格式错误，将使用空数组')
                    formData.excludeKeywords = []
                }
            }

            const apiMethod = formData.id ? jobTypesServer.update : jobTypesServer.add
            apiMethod(formData).then(res => {
                if (res.code === 0) {
                    this.$Message.success(formData.id ? '更新成功' : '添加成功')
                    this.$refs.editModal.hide()
                    this.query(this.gridOption.param.pageOption.page)
                } else {
                    this.$Message.error(res.message || (formData.id ? '更新失败' : '添加失败'))
                }
            }).catch(err => {
                this.$Message.error((formData.id ? '更新失败' : '添加失败') + '：' + (err.message || '未知错误'))
            })
        }
    }
}
</script>

<style scoped>
.content-view {
    padding: 16px;
}
</style>
