<!--流程模型管理界面-->
<template>
    <div class="default-main">
        <TableHeader showCustomColumn>
            <template v-slot:select>
                <!--                <el-form-item label='用户'>-->
                <!--                    <el-select v-model='tableStore.table.params.userId' filterable clearable>-->
                <!--                        <el-option-->
                <!--                            v-for='item in userListData'-->
                <!--                            :key='item.id'-->
                <!--                            :label='item.userName'-->
                <!--                            :value='item.id'-->
                <!--                        />-->
                <!--                    </el-select>-->
                <!--                </el-form-item>-->
            </template>
            <template v-slot:operation>
                <el-button type="primary" @click="add" class="ml10" :icon="Plus">新增模型</el-button>
            </template>
        </TableHeader>
        <!--表格-->
        <Table ref="tableRef" isGroup></Table>
        <model-popup ref="modelPopup" />
        <!-- 弹窗：表单详情 -->
        <el-dialog title="表单详情" v-model="formDetailVisible" width="800">
            <form-create :rule="formDetailPreview.rule" :option="formDetailPreview.option" />
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import TableStore from '@/utils/tableStore'
import Table from '@/components/table/index.vue'
import TableHeader from '@/components/table/header/index.vue'
import { onMounted, provide, ref } from 'vue'
import { useRouter } from 'vue-router'
import ModelPopup from '@/views/system/bpm/model/modelPopup.vue'
import { deleteModel, deployModel } from '@/api/bpm-boot/model'
import { getById } from '@/api/bpm-boot/form'
import { setConfAndFields2 } from '@/utils/formCreate'
import { getSignSimpleList } from '@/api/bpm-boot/sign'

defineOptions({
    name: 'governSchemeHistory'
})

const { push } = useRouter()
const modelPopup = ref()

const tableStore = new TableStore({
    url: '/bpm-boot/bpm/model/list',
    method: 'POST',
    column: [
        {
            title: '序号',
            width: 80,
            formatter: (row: any) => {
                return (tableStore.table.params.pageNum - 1) * tableStore.table.params.pageSize + row.rowIndex + 1
            }
        },
        { title: '模型标识', field: 'key', width: 160 },
        { title: '模型名称', field: 'name', width: 160 },
        { title: '流程分类', field: 'categoryName', width: 150 },
        {
            title: '表单信息',
            field: 'formName',
            width: 170,
            formatter: (obj: any) => {
                const formType = obj.row.formType
                if (formType == 20) {
                    return getFormNameByViewPath(obj.row.formCustomViewPath)
                } else {
                    return obj.row.formName
                }
            }
        },
        {
            title: '创建时间',
            field: 'createTime',
            width: 150
        },
        {
            title: '最新部署的流程定义',
            children: [
                {
                    title: '模型版本',
                    width: '150',
                    field: 'processDefinition.version',
                    type: 'html',
                    formatter: (obj: any) => {
                        if (obj.row.processDefinition) {
                            const val = obj.row.processDefinition.version
                            return `<a href='javascript:void(0);'  style='color: #409EFF;text-decoration: none'>v${val}</a>`
                        } else {
                            return '未部署'
                        }
                    }
                },
                {
                    title: '激活状态',
                    width: '150',
                    field: 'processDefinition.suspensionState',
                    // render: 'switch',
                    // activeValue: '1',
                    // inactiveValue: '0',
                    // onChangeField: (row: any, value) => {
                    //     console.log(row, 444123, value)
                    //     value == 0 ? (value = 1) : (value = 0)
                    // }
                    render: 'tag',
                    custom: {
                        2: 'danger',
                        1: 'success'
                    },
                    replaceValue: {
                        2: '关闭',
                        1: '开启'
                    }
                },
                { title: '部署时间', width: '150', field: 'processDefinition.deploymentTime' }
            ]
        },
        {
            title: '操作',
            fixed: 'right',
            align: 'center',
            minWidth: '200',
            render: 'buttons',

            buttons: [
                {
                    name: 'productSetting',
                    title: '设计流程',
                    type: 'primary',
                    icon: 'el-icon-EditPen',
                    render: 'basicButton',
                    click: row => {
                        handleDesign(row.id)
                    }
                },
                {
                    name: 'productSetting',
                    title: '部署流程',
                    type: 'primary',
                    icon: 'el-icon-EditPen',
                    render: 'basicButton',
                    click: row => {
                        handleDeployConfirm(row.id)
                    }
                },
                {
                    name: 'productSetting',
                    title: '表单预览',
                    type: 'primary',
                    icon: 'el-icon-EditPen',
                    render: 'basicButton',
                    click: row => {
                        handleFormDetail(row.formId)
                    }
                },
                {
                    name: 'update',
                    title: '删除',
                    type: 'danger',
                    icon: 'el-icon-Delete',
                    render: 'confirmButton',
                    popconfirm: {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        confirmButtonType: 'danger',
                        title: '确定删除吗？'
                    },
                    click: row => {
                        deleteModel(row.id).then(res => {
                            ElMessage.success('删除成功')
                            tableStore.index()
                        })
                    }
                }
            ]
        }
    ],
    beforeSearchFun: () => {
        if (tableStore.table.params.addr) {
            tableStore.table.params.addrStrOption = tableStore.table.params.addr.map(tempArray => tempArray.join('/'))
        }
        for (let key in tableStore.table.params) {
            if (tableStore.table.params[key] === '') {
                delete tableStore.table.params[key]
            }
        }
    }
})
const flowInfo = ref()

onMounted(async () => {
    //加载流程标识
    await getSignSimpleList().then(res => {
        flowInfo.value = res.data
    })

    // 加载数据
    tableStore.index()
})
tableStore.table.params.userId = ''

provide('tableStore', tableStore)

//获取流程标识的名称
const getFormNameByViewPath = (viewPath: string) => {
    const nameItem = flowInfo.value.filter(item => item.viewPath == viewPath)
    if (nameItem.length > 0) {
        return nameItem[0].name
    } else {
        return ''
    }
}

//新增用户信息
const add = () => {
    modelPopup.value.open('新增流程模型')
}

/** 设计流程 */
const handleDesign = (rowId: string) => {
    push({
        name: 'BpmModelEditor',
        query: {
            modelId: rowId
        }
    })
}

/** 发布流程 */
const handleDeployConfirm = (rowId: string) => {
    try {
        // 删除的二次确认
        ElMessageBox.confirm('是否部署该流程?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            draggable: true,
            type: 'warning'
        })
            .then(() => {
                handleDeploy(rowId)
            })
            .catch(() => {})
    } catch {}
}

const handleDeploy = async (rowId: string) => {
    // 发起部署
    await deployModel(rowId)
    ElMessage.success('部署成功')
    tableStore.index()
}

/** 流程表单的详情按钮操作 */
const formDetailVisible = ref(false)
const formDetailPreview = ref({
    rule: [],
    option: {}
})

const handleFormDetail = async (formId: string) => {
    // 设置表单
    await getById(formId).then(res => {
        const data = res.data
        setConfAndFields2(formDetailPreview, data.conf, data.fields)
        // 弹窗打开
        formDetailVisible.value = true
    })
}
</script>
