<template>
    <!-- 会签配置 -->
    <div class="app-container">
        <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
        >
            <el-form-item label="节点名称" prop="nodeName">
                <el-input v-model="queryParams.nodeName" placeholder="请输入节点名称" clearable />
            </el-form-item>
            <el-form-item label="会签类型" prop="nodeSignType" clearable>
                <el-select v-model="queryParams.nodeSignType">
                    <el-option label="或签" :value="0" />
                    <el-option label="会签" :value="1" />
                </el-select>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                    v-hasPermi="['system:dict:add']"
                >
                    新增
                </el-button>
            </el-col>

            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-close" size="mini" @click="handleClose">关闭</el-button>
            </el-col>
        </el-row>

        <el-table :data="dataList">
            <el-table-column label="流程类型" align="center">
                <template>
                    {{ processName }}
                </template>
            </el-table-column>
            <el-table-column label="流程节点" align="center" prop="nodeName" />
            <el-table-column label="流程顺序" align="center" prop="nodeSort" />
            <el-table-column label="会签类型" align="center">
                <template slot-scope="{ row }">
                    <el-tag size="mini" type="primary" v-if="row.nodeSignType === 0">或签</el-tag>
                    <el-tag size="mini" type="warning" v-if="row.nodeSignType === 1">会签</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="角色/人员(审核)" align="center" :show-overflow-tooltip="true">
                <template slot-scope="{ row }">
                    <span class="user-roles">
                        {{ row.nodeSignConfig === 1 ? '用户' : '角色' }}
                    </span>
                </template>
            </el-table-column>

            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleUpdate(scope.row)"
                        v-hasPermi="['system:dict:edit']"
                    >
                        修改
                    </el-button>
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                        v-hasPermi="['system:dict:remove']"
                    >
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或修改参数配置对话框 -->
        <el-dialog :title="`${title}流程节点`" :visible.sync="open" width="50%" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                <el-form-item label="流程类型">
                    <el-input v-model="processName" :disabled="true" />
                </el-form-item>
                <el-form-item label="流程节点" prop="nodeName">
                    <el-input v-model="form.nodeName" placeholder="请输入流程节点" />
                </el-form-item>
                <el-form-item label="流程顺序" prop="nodeSort">
                    <el-input-number
                        :min="1"
                        :max="10"
                        :precision="0"
                        v-model="form.nodeSort"
                        controls-position="right"
                    />
                </el-form-item>
                <el-form-item label="会签类型" prop="nodeSignType">
                    <el-radio-group v-model="form.nodeSignType">
                        <el-radio :label="0">或签</el-radio>
                        <el-radio :label="1">会签</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="审核角色 / 用户" prop="nodeSignConfig">
                    <el-radio-group v-model="form.nodeSignConfig" @input="onChangeNodeSignConfig">
                        <el-radio :label="0">角色</el-radio>
                        <el-radio :label="1">用户</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="角色" prop="configValuesList" v-if="form.nodeSignConfig === 0">
                    <el-select
                        v-model="form.configValuesList"
                        style="width: 100%"
                        filterable
                        multiple
                        @change="onRolesChange"
                        @remove-tag="onRemoveTag"
                    >
                        <el-option
                            :key="item.roleId"
                            :value="item.roleId + ''"
                            :label="item.roleName"
                            v-for="item in roleList"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="人员" prop="configValuesList" v-if="form.nodeSignConfig === 1">
                    <el-select v-model="form.configValuesList" style="width: 100%" filterable multiple>
                        <el-option
                            :key="item.userId"
                            :value="item.userId + ''"
                            :label="item.nickName"
                            v-for="item in userList"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listData, getData, delData, addData, updateData } from '@/api/system/dict/data'
import { optionselect as getDictOptionselect, getType } from '@/api/system/dict/type'

import { listRole, allocatedUserList } from '@/api/system/role'
import { listUser } from '@/api/system/user'

import {
    getConfigNodeListApi,
    addConfigNodeApi,
    editConfigNodeApi,
    deleteConfigNodeApi
} from '@/api/countersign/countersign'

export default {
    name: 'Data',
    dicts: ['sys_normal_disable'],
    data() {
        return {
            // 遮罩层
            loading: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 字典表格数据
            dataList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,

            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                typeId: '',
                nodeSignType: '',
                nodeName: ''
            },
            // 表单参数
            form: {
                nodeName: '', // 流程节点
                nodeSort: '', // 流程顺序
                nodeSignType: 1, // 会签类型
                nodeSignConfig: 1, // 审核人员类型
                configValues: '', // 审核人员
                configValuesList: [],
                roleIds: ''
            },
            // 表单校验
            rules: {
                nodeName: [{ required: true, message: '流程节点不能为空', trigger: 'blur' }],
                nodeSort: [{ required: true, message: '流程顺序不能为空', trigger: 'blur' }],
                nodeSignType: [{ required: true, message: '请选择会签类型', trigger: 'blur' }],
                nodeSignConfig: [{ required: true, message: '请选择审核人员类型', trigger: 'blur' }],
                configValuesList: [{ required: true, message: '请选择审核人员或用户', trigger: 'blur' }]
            },
            processName: '',
            roleList: [],
            userList: [],
            userIds: []
        }
    },
    created() {
        this.processName = this.$route.params && this.$route.params.processName
        this.queryParams.typeId = this.$route.params && this.$route.params.id
        this.getList()
        this.getRoleAndUserList()
    },
    methods: {
        // 获取角色列表
        async getRoleAndUserList() {
            const { rows: res } = await listRole({ pageNum: 1, pageSize: 999 })
            const { rows: result } = await listUser({ pageNum: 1, pageSize: 999 })
            this.roleList = res
            this.userList = result
        },
        /** 查询字典数据列表 */
        async getList() {
            this.loading = true
            const res = await getConfigNodeListApi(this.queryParams)
            this.dataList = res.rows
            this.total = res.total
            this.loading = false
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                nodeName: '',
                nodeSort: '',
                nodeSignType: 0,
                nodeSignConfig: 0,
                configValuesList: [],
                roleIds: ''
            }
            this.resetForm('form')
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 返回按钮操作 */
        handleClose() {
            const obj = { path: '/countersign/config' }
            this.$tab.closeOpenPage(obj)
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset()
            this.open = true
            this.title = '添加'
        },

        /** 修改按钮操作 */
        handleUpdate(row) {
            const { nodeName, nodeSort, nodeSignType, nodeSignConfig, configValues, id, roleIds } = row
            Object.assign(this.form, {
                nodeName,
                nodeSort,
                nodeSignType,
                nodeSignConfig,
                configValues,
                id,
                roleIds
            })

            if (nodeSignConfig == 0 && this.form.roleIds) {
                this.form.configValuesList = this.form.roleIds.split(',')
            } else if(this.form.roleIds){
                this.form.configValuesList = this.form.configValues.split(',')
            }

            this.title = '修改'
            this.open = true
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs['form'].validate(async valid => {
                if (valid) {
                    const SUBMIT_FUN = this.title === '添加' ? addConfigNodeApi : editConfigNodeApi
                    const isSortPass = this.dataList.findIndex(e => e.nodeSort === this.form.nodeSort)
                    // 判断当前是角色还是用户

                    let apiPromises = []
                    // 判断当前是角色还是用户
                    if (this.form.nodeSignConfig == 0) {
                        this.userIds = []
                        // 创建一个包含所有 API 调用的 Promise 数组
                        apiPromises = this.form.configValuesList.map(e => {
                            return allocatedUserList({ pageNum: 1, pageSize: 999, roleId: e }).then(res => {
                                res.rows.forEach(j => {
                                    this.userIds.push(j.userId)
                                })
                            })
                        })
                    } else {
                        this.form.configValues = this.form.configValuesList.join(',')
                    }

                    try {
                        // 等待所有 API 调用完成
                        await Promise.all(apiPromises)

                        if (this.form.nodeSignConfig == 0) {
                            this.form.configValues = this.userIds.join(',')
                            this.form.roleIds = this.form.configValuesList.join(',')
                        }

                        // 准备提交的表单数据
                        const addOrEditForm = JSON.parse(JSON.stringify(this.form))
                        this.$delete(addOrEditForm, 'configValuesList') // 去除无关字段

                        if (this.title === '添加') {
                            addOrEditForm.typeId = this.queryParams.typeId
                        }

                        // 执行提交操作
                        const res = await SUBMIT_FUN(addOrEditForm)
                        if (res.code === 200) {
                            this.$modal.msgSuccess(`${this.title}成功`)
                            this.userIds = []
                            this.getList()
                            this.open = false
                        }
                    } catch (err) {
                        console.error('请求错误:', err)
                    }
                }
            })
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            this.$modal
                .confirm('是否确认删除该审核节点？')
                .then(function () {
                    return deleteConfigNodeApi({ id: row.id })
                })
                .then(() => {
                    this.getList()
                    this.$modal.msgSuccess('删除成功')
                })
                .catch(() => {})
        },
        // 审核角色用户切换
        onChangeNodeSignConfig(val) {
            console.log(val, '角色用户切换')

            if (val == 0) {
                this.form.configValuesList = []
            }
        },
        // 角色复选框change事件
        async onRolesChange(val) {
            // if (val.length === 0) {
            //     this.userIds = []
            // } else {
            //     val.forEach(e => {
            //         allocatedUserList({ pageNum: 1, pageSize: 999, roleId: e }).then(res => {
            //             res.rows.forEach(j => {
            //                 this.userIds.push(j.userId)
            //             })
            //         })
            //     })
            // }
        },
        // 角色清除时
        onRemoveTag(val) {}
    }
}
</script>

<style scoped>
.user-roles {
    cursor: pointer;
    color: #409eff;
    font-size: 14px;
}
</style>
