<template>
    <!-- 会签配置管理 列表页面 -->
    <div class="app-container">

        <el-table v-loading="loading" :data="configList" ref="multipleTable">
            <el-table-column
                width="80"
                label="序号"
                type="index"
                align="center"
                :index="indexContinuation(queryParams.pageNum, queryParams.pageSize)"
            />

            <!-- 点击跳转到二级页面配置审核流程 -->
            <el-table-column label="结算类型" align="center" prop="processName" show-overflow-tooltip>
                <template slot-scope="scope">
                <el-tag 
                    :type="scope.row.processName == '安全工器具' ? 'warning' : ''" 
                    effect="plain">
                    {{ scope.row.processName }}
                </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="配置人员" align="center" prop="userNameStr" width="500" >
                <template slot-scope="scope">
                    <span>{{ sortUserNames(scope.row.userNameStr) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="250">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="primary"
                        icon="el-icon-edit"
                        @click="handleUpdate(scope.row)"
                    >
                        人员配置
                    </el-button>
                    <!-- <el-button
                        size="mini"
                        type="danger"
                        icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                    >
                        删除
                    </el-button> -->
                </template>
            </el-table-column>
        </el-table>

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

        <!-- 新增或修改弹窗 -->
        <el-dialog :title="title" :visible.sync="showConfig" width="40%" append-to-body @close="onDialogClose">
            <el-form ref="form" :model="form"  label-width="120px">
                <el-row :gutter="24">
                    <el-col :span="20">
                        <el-form-item label="配置人员" prop="typeName">
                            <el-select
                                v-model="form.userIds"
                                filterable multiple
                                placeholder="请选择人员"
                                style="width: 100%"
                            >
                                <el-option
                                v-for="keeper in userOptions"
                                :key="keeper.userId+''"
                                :label="keeper.nickName"
                                :value="keeper.userId+''"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { getCostConfigListApi,getCostConfigUserListApi, editCostConfigApi,deleteCostConfigApi, deleteConfigApi } from '@/api/countersign/countersign'
import { getKeeperIds } from '@/api/ma/typeConfigKeeper'
export default {
    name: 'CostConfig',
    data() {
        return {
            // 遮罩层
            loading: false,
            // 显示搜索条件
            showSearch: true,
            showConfig: false,
            // 总条数
            total: 0,
            // 会签配置表格数据
            configList: [],
            userOptions:[],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                keyWord: undefined
            },
            // 表单参数
            form: {
                id: '',
                userIds: [],
                itemName: '',
            },
        }
    },
    created() {
        this.getList()
    },

    methods: {
        sortUserNames(userNameStr) {
            if (!userNameStr) return '';
            
            // 分割、排序、再合并
            return userNameStr.split(',')
                .map(name => name.trim())
                .filter(name => name)
                .sort((a, b) => a.localeCompare(b)) // 明确指定比较规则
                .join(', ');
        },

        // 取消按钮
        cancel() {
            this.showConfig = false
        },

        // 搜索
        handleQuery() {
            this.getList()
        },

        // 弹框关闭时触发
        onDialogClose() {
            this.$refs.form.resetFields()
        },

        // 表单重置
        reset() {
            this.form = {
                typeName: '',
                taskType: ''
            }
            this.resetForm('form')
        },
        // 重置
        resetQuery() {
            this.resetForm('queryForm')
            this.queryParams.keyWord = null
            this.queryParams.pageNum = 1
            this.queryParams.pageSize = 10
            this.handleQuery()
        },

        // 编辑
        async handleUpdate(row) {
            this.form.id = row.id
            this.userOptions = []
            let roleIds = ''
            await getKeeperIds(row.itemName).then((response) => {
                 roleIds = response.rows[response.rows.length - 1].itemValue
            })
            await getCostConfigUserListApi({userNameStr:roleIds}).then((response) => {
                    this.userOptions = response.rows.sort((a, b) =>
                    a.nickName.localeCompare(b.nickName, 'zh-CN')
                    )
            })
            if (row.itemValue) {
            const userIds = row.itemValue.split(',')
            // 根据 keeperIds 从 KeeperOptions 中获取对应的 keeper 对象
            const users = userIds.map((id) =>
                this.userOptions.find((user) => user.userId + '' == id)
            ).filter(Boolean) // 过滤掉可能不存在的 keeper

            // 根据 keeperName 中文排序
            users.sort((a, b) =>
                a.nickName.localeCompare(b.nickName, 'zh-CN')
            )

            // 提取排序后的 keeperId
            this.form.userIds = users.map((user) => user.userId + '')
            } else {
            this.form.userIds = [] // 如果不存在，设置为空数组
            }
            this.title = '人员配置'
            this.showConfig = true
        },

        // 查询列表
        async getList() {
            this.loading = true
            const res = await getCostConfigListApi()
            this.configList = res.rows
            this.total = res.total
            this.loading = false
        },

        // 删除
        handleDelete(row) {
            const id = row.id
            this.$modal
                .confirm('是否确认删除数据项？')
                .then(function () {
                    return deleteCostConfigApi({ id })
                })
                .then(() => {
                    this.$modal.msgSuccess('删除成功')
                    this.getList()
                })
                .catch(() => {})
        },

        // 提交
        submitForm() {
            console.log("xxxxxxxxxxxxxx",this.form)
            editCostConfigApi(this.form).then(res => {
                this.$modal.msgSuccess('修改成功')
                this.showConfig = false
                this.getList()
            })
        }
    }
}
</script>
