<template>
    <div class="p-3">
        <div class="bg-fff flex1 ov-hd d-flex flex-cln">
            <div class="d-flex a-c pd-16 border-bottom">
                <div class="f-s-20 c-333 f-w-7 mr-10">
                    <template v-if="form?.res === '0'">抽取专家审核</template>
                    <template v-if="['1', '2'].includes(form?.res)">抽取专家详情</template>
                </div>
                <el-button @click="router.go(-1)" type="primary" text>
                    <el-icon>
                        <Back />
                    </el-icon>
                    返回上一级
                </el-button>
            </div>
            <div class="flex1 over-auto">
                <div v-if="form" class="pd-16">
                    <div class="info-title f-w-5 mb-10">事项发起信息</div>
                    <el-descriptions :column="4">
                        <el-descriptions-item label="发起方:">{{ form?.starter || '-' }}</el-descriptions-item>
                        <el-descriptions-item label="事项名称:">{{ form?.title || '-' }}</el-descriptions-item>
                        <el-descriptions-item label="时间:">{{ form?.startTime || '-' }} ~ {{ form?.endTime || '-' }}</el-descriptions-item>
                        <el-descriptions-item label="参与方式:">{{ selectDictLabel(dm_join_type, form?.joinType) || '-' }}</el-descriptions-item>
                        <el-descriptions-item v-if="!+form?.joinType" label="线下地点:">{{ form?.detailedAddress || form?.address || '-' }}</el-descriptions-item>
                        <el-descriptions-item label="联系人:">{{ form?.contact || '-' }}</el-descriptions-item>
                        <el-descriptions-item label="联系电话:">{{ form?.tel || '-' }}</el-descriptions-item>
                        <el-descriptions-item label="提交人:">{{ form?.createByName || '-' }}</el-descriptions-item>
                        <el-descriptions-item label="提交时间:">{{ form?.createTime || '-' }}</el-descriptions-item>
                        <el-descriptions-item label="备注:">{{ form?.remark || '-' }}</el-descriptions-item>
                    </el-descriptions>
                    <el-descriptions :column="1">
                        <el-descriptions-item label="事项详情:">{{ form?.content || '-' }}</el-descriptions-item>
                    </el-descriptions>
                    <el-divider />
                    <div class="info-title f-w-5 mb-10">抽取专家要求</div>
                    <el-descriptions :column="4">
                        <el-descriptions-item label="领域人员是否可重复:">{{ selectDictLabel(yes_no, form?.repeatType) || '-' }}</el-descriptions-item>
                    </el-descriptions>
                    <div>
                        <el-tag v-for="(item, index) in form?.personInfo" :key="index" class="mr-10">{{ selectDictLabel(dm_person_type, item?.personType) }}（{{ item?.personCount }}）</el-tag>
                    </div>
                    <el-divider />
                    <template v-if="form?.approvalLogVos.length">
                        <div class="info-title f-w-5 mb-10">审核记录</div>
                        <!-- // 表格 -->
                        <vxe-table :data="form?.approvalLogVos" border min-height="0" style="width: 100%">
                            <vxe-column title="审核结果">
                                <template #default="{ row }">
                                    <div v-if="+row?.res === 1" class="c-primary">通过</div>
                                    <div v-if="+row?.res === 2" class="c-danger">不通过</div>
                                    <div v-if="+row?.res === 2" class="f-s-12 c-danger">原因：{{ row?.msg }}</div>
                                </template>
                            </vxe-column>
                            <vxe-column field="createTime" title="审核时间" />
                            <vxe-column field="auditorName" title="审核人" />
                        </vxe-table>
                    </template>
                    <template v-if="form?.res === '1'">
                        <el-divider />
                        <div class="info-title f-w-5 mb-10">
                            <span>抽取专家公示信息</span>
                            <span class="c-999 f-s-12">（公示时间：{{ form?.auditTime }}）</span>
                        </div>
                        <vxe-table :data="list" border keep-source :span-method="rowspanMethod" min-height="0" style="width: 100%">
                            <vxe-column title="专家组" field="personType">
                                <template #default="{ row }">
                                    {{ selectDictLabel(dm_person_type, row.personType) || '-' }}
                                </template>
                            </vxe-column>
                            <vxe-column title="人数" field="personType">
                                <template #default="{ row }">{{ row?.allCount|| '-' }}人</template>
                            </vxe-column>
                            <!-- // 是否指定 -->
                            <vxe-column title="是否指定人员">
                                <template #default="{ row }">
                                    {{ selectDictLabel(yes_no, row?.isAppoint) || '-' }}
                                </template>
                            </vxe-column>
                            <vxe-column field="name" title="姓名" />
                            <vxe-column title="联系电话" field="phone" :formatter="colNoData" />
                            <vxe-column title="性别">
                                <template #default="{ row }">
                                    {{ selectDictLabel(sys_sex_type, row?.sex) }}
                                </template>
                            </vxe-column>
                            <vxe-column title="单位" field="workUnit" :formatter="colNoData" />
                            <vxe-column title="所在地区" field="adcodeName" :formatter="colNoData" />
                            <vxe-column title="职称/职务" field="post" :formatter="colNoData" />
                            <vxe-column title="专业品种" field="variety" :formatter="colNoData" />
                        </vxe-table>
                    </template>
                </div>
            </div>
            <div v-if="!+form?.res" class="d-flex a-c j-c pd-16">
                <el-button @click="router.go(-1)">取消</el-button>
                <el-button type="danger" @click="noPass">不通过</el-button>
                <el-button type="primary" @click="showCheckPass = true">通过</el-button>
            </div>
        </div>
    </div>
    <ChooseExpertCheck v-if="showCheckPass" v-model:show="showCheckPass" :info="form" :dict="dict" @success="successChange"></ChooseExpertCheck>
</template>

<script setup name="authority-input" lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { debounce } from 'lodash';
import { useRouter } from 'vue-router';
import { expertChooseApprove, expertChooseDetail, expertChooseRelationList } from '@/api/authority';
import { ChooseExpertCheck } from '../models';
import { colNoData } from '@/utils/noData';
import { VxeTablePropTypes } from 'vxe-table';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const dict = proxy?.useDict('dm_person_type', 'dm_join_type', 'yes_no', 'sys_sex_type', 'dm_position_status');
const { dm_person_type, dm_join_type, yes_no, sys_sex_type } = toRefs<any>(dict);
const router = useRouter();
const route = useRoute();
const form = ref<any>(null);
const showCheckPass = ref(false);
// 获取专家详情
const getExpertDetail = async () => {
    if (route.query?.id) {
        const res = await expertChooseDetail(route.query.id);
        if (!res || res.code !== 200) return;
        form.value = res.data;
        if (form.value?.res === '1') {
            // 获取专家抽取关联列表
            getExpertRelationList();
        }
    }
};
const noPass = async () => {
    ElMessageBox.prompt('是否确认将该事项的专家抽取审核为不通过！请填写不通过原因：', '审核不通过', {
        confirmButtonText: '确认不通过',
        cancelButtonText: '取消',
        // 校验必填
        inputValidator: (value) => {
            if (!value) {
                return '请填写不通过原因';
            }
            return true;
        },
        inputPlaceholder: '请填写不通过原因'
    })
        .then(({ value }) => {
            const params = {
                targetId: route.query.id,
                res: '2', // 不通过
                msg: value
            };
            submitApprove(params);
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消审核'
            });
        });
};
// 提交审核
const submitApprove = async (params: any) => {
    proxy.$modal.loading('正在提交审核，请稍候...');
    const res = await expertChooseApprove(params).finally(() => {
        proxy.$modal.closeLoading();
    });
    if (res.code === 200) {
        ElMessage({
            type: 'success',
            message: '操作成功'
        });
        router.go(-1);
    } else {
        ElMessage({
            type: 'error',
            message: res.msg || '操作失败'
        });
    }
};
const successChange = (val: any) => {
    showCheckPass.value = false;
    if (val?.length) {
        const params = {
            targetId: route.query.id,
            res: '1', // 通过
            personInfo: val
        };
        submitApprove(params);
    }
};
const list = ref<any[]>([]);
// 获取专家抽取关联列表
const getExpertRelationList = async () => {
    if (route.query?.id) {
        const res = await expertChooseRelationList({ expertChooseId: route.query.id });
        if (!res || res.code !== 200) return;
        list.value = res.data;
    }
};
// 通用行合并函数（将相同多列数据合并为一行）
const rowspanMethod: any = ({ row, _rowIndex, column, visibleData }) => {
    const fields = ['personType', 'personCount', 'id'];
    const cellValue = row[column.field];
    if (cellValue && fields.includes(column.field)) {
        const prevRow = visibleData[_rowIndex - 1];
        let nextRow = visibleData[_rowIndex + 1];
        if (prevRow && prevRow[column.field] === cellValue) {
            return { rowspan: 0, colspan: 0 };
        } else {
            let countRowspan = 1;
            while (nextRow && nextRow[column.field] === cellValue) {
                nextRow = visibleData[++countRowspan + _rowIndex];
            }
            if (countRowspan > 1) {
                return { rowspan: countRowspan, colspan: 1 };
            }
        }
    }
};

onMounted(() => {
    getExpertDetail();
});
</script>
