<template>
    <lay-container fluid="true" class="organization-box">
        <div style="display: flex">
            <!-- 添加左侧科室列表 -->
            <div v-if="userStore.userInfo.level == 1" :style="{ width: isFold ? `0px` : `200px` }" class="left-tree">
                <div v-show="!isFold">
                    科室列表
                </div>
                <lay-tree v-show="!isFold" style="margin-top: 10px" :data="data" v-model:selectedKey="leftId"
                    :showLine="false" :default-expand-all="false" @node-click="handleClick">
                    <template #title="{ data }">
                        <span :class="leftId == data.id ? 'isChecked' : ''">
                            {{ data.name }}
                        </span>
                    </template>
                </lay-tree>
                <div class="isFold" @click="isFold = !isFold">
                    &nbsp;<lay-icon v-if="!isFold" class="layui-icon-left"></lay-icon>
                    <lay-icon v-else class="layui-icon-right"></lay-icon>
                </div>
            </div>

            <!-- 将原有内容包装在右侧容器中 -->
            <div style="flex: 1; padding: 10px;">
                <lay-row :space="10">
                    <lay-col :md="24">
                        <lay-card>
                            <lay-form style="margin-top: 20px">
                                <lay-row style="min-width: 1200px">
                                    <lay-col :md="5">
                                        <lay-form-item label="发生时间：" :label-width="100">
                                            <lay-date-picker style="width: 100%" v-model="searchForm.fsdate"
                                                placeholder="发生时间" allow-clear></lay-date-picker>
                                        </lay-form-item>
                                    </lay-col>
                                    <lay-col :md="6" v-if="userStore.userInfo.level == 1">
                                        <lay-form-item label="考评对象：" :label-width="100">
                                            <lay-select v-model="searchForm.user_id" placeholder="请选择考评对象"
                                                :show-search="true">
                                                <lay-select-option v-for="user in userList" :key="user.id"
                                                    :value="user.id" :label="user.nickname">
                                                </lay-select-option>
                                            </lay-select>
                                        </lay-form-item>
                                    </lay-col>
                                    <lay-col :md="4">
                                        <lay-form-item label="审核状态：" :label-width="100">
                                            <lay-select style="width: 100%" v-model="searchForm.status"
                                                placeholder="审核状态">
                                                <lay-select-option :value="1" label="待审核"></lay-select-option>
                                                <lay-select-option :value="2" label="已通过"></lay-select-option>
                                                <lay-select-option :value="3" label="已驳回"></lay-select-option>
                                            </lay-select>
                                        </lay-form-item>
                                    </lay-col>
                                    <lay-col :md="4">
                                        <lay-form-item :label-width="0">
                                            <lay-button style="margin-left: 20px" type="primary"
                                                @click="toSearch">查询</lay-button>
                                            <lay-button @click="toReset">重置</lay-button>
                                        </lay-form-item>
                                    </lay-col>
                                </lay-row>
                            </lay-form>
                        </lay-card>
                    </lay-col>
                    <lay-col :md="24">
                        <lay-card>
                            <div style="padding: 10px">
                                <span style="font-size: 18px;vertical-align: center;margin-right: 20px">拒收红包列表</span>
                                <lay-button type="primary" size="sm" @click="openAdd">新增</lay-button>
                                <lay-button type="primary" size="sm">导出Excel</lay-button>
                            </div>
                            <lay-table  @change="handlePageChange" :columns="columns" :dataSource="dataSource" :even="true" height="500px" size="lg"
                                :page="page">
                                <template v-slot:checkbox="{ data }">
                                    <lay-checkbox v-model="data.checked" :value="data.checked"></lay-checkbox>
                                </template>
                                <template v-slot:refundAmount="{ data }">
                                    ¥{{ data.refunding_amount }}
                                </template>
                                <template v-slot:refundType="{ data }">
                                    {{ formatRefundType(data.refunding_type) }}
                                </template>
                                <template v-slot:status="{ data }">
                                    <lay-tag v-if="data.status == 1" type="warm">待审核</lay-tag>
                                    <lay-tag v-if="data.status == 2" type="primary">已通过</lay-tag>
                                    <lay-tag v-if="data.status == 3" type="danger">已驳回</lay-tag>
                                </template>
                                <template v-slot:operation="{ data }">
                                    <lay-popconfirm v-if="data.status == 1 && data.level == 1" content="请确认你的操作，流程将结束"
                                        trigger="click" cancelText="审核拒绝" confirmText="审核通过" @confirm="confirm(data, 2)"
                                        @cancel="confirm(data, 3)">
                                        <lay-button v-if="data.status == 1 && data.level == 1" type="primary" size="sm"
                                            style="margin-left: 8px">审核</lay-button>
                                    </lay-popconfirm>
                                    <lay-button type="normal" size="sm" style="margin-left: 8px"
                                        @click="openDetail(data)">详情</lay-button>
                                </template>
                            </lay-table>
                        </lay-card>
                    </lay-col>
                </lay-row>
            </div>
        </div>
    </lay-container>

    <!-- 新增/编辑弹窗 -->
    <lay-layer v-model="visible" :title="formTitle" :type="4" :area="['950px', '100%']" :shade="true">
        <div style="padding: 20px">
            <lay-form :model="form" mode="inline">
                <lay-form-item label="考评对象" required>
                    <lay-select disabled v-model="form.user_id" placeholder="请选择考评对象" :show-search="true">
                        <lay-select-option v-for="user in userList" :key="user.id" :value="user.id"
                            :label="user.nickname">
                        </lay-select-option>
                    </lay-select>
                </lay-form-item>
                <!-- <lay-form-item label="科室" required>
                    <lay-cascader v-model="form.group_id" :options="ksOptions" placeholder="请选择科室"
                        :checkStrictly="false" search :replaceFields="replaceFields">
                    </lay-cascader>
                </lay-form-item> -->
                <lay-form-item label="发生日期" required>
                    <lay-date-picker v-model="form.fsdate" placeholder="请选择发生日期"></lay-date-picker>
                </lay-form-item>
                <lay-form-item label="证明人" required>
                    <lay-select v-model="form.zm_user_id" placeholder="请选择证明人" :show-search="true">
                        <lay-select-option v-for="user in userList" :key="user.id" :value="user.id"
                            :label="user.nickname">
                        </lay-select-option>
                    </lay-select>
                </lay-form-item>
                <lay-form-item label="病区名称" required>
                    <lay-input style="width: 220px" v-model="form.bq_name" placeholder="请输入病区名称"></lay-input>
                </lay-form-item>
                <lay-form-item label="患者姓名" required>
                    <lay-input style="width: 220px" v-model="form.hz_name" placeholder="请输入患者姓名"></lay-input>
                </lay-form-item>
                <lay-form-item label="退还金额" required>
                    <lay-input-number style="width: 220px" v-model="form.refunding_amount"
                        placeholder="请输入退还金额"></lay-input-number>
                </lay-form-item>
                <lay-form-item label="退还日期" required>
                    <lay-date-picker v-model="form.thdate" placeholder="请选择退还日期"></lay-date-picker>
                </lay-form-item>
                <lay-form-item label="退还方式" required>
                    <lay-select v-model="form.refunding_type" placeholder="请选择退还方式">
                        <lay-select-option :value="1" label="现金"></lay-select-option>
                        <lay-select-option :value="2" label="转账"></lay-select-option>
                    </lay-select>
                </lay-form-item>
                <lay-form-item label="附件" mode="block">
                    <lay-upload ref="uploadRef" :number="1" field="file" :size="1000"
                        :headers="{ token: userStore.token }" url="/api/common/upload" @cutdone="getCutDone"
                        v-model="file1" :auto="true" :cut="false" :cutOptions="cutOptions" @done="getFileDone">
                        <template #preview>
                            <a v-if="form.fj_url" style="color: #009688" :href="form.fj_url" target="_blank">
                                {{ form.fj_url }}
                            </a>
                        </template>
                    </lay-upload>
                </lay-form-item>
                <lay-form-item label="备注" mode="block">
                    <lay-textarea v-model="form.notes" placeholder="请输入备注信息"></lay-textarea>
                </lay-form-item>
            </lay-form>
            <div style="text-align: center; margin-top: 20px;">
                <lay-button type="primary" @click="submitForm">确定</lay-button>
                <lay-button @click="visible = false">取消</lay-button>
            </div>
        </div>
    </lay-layer>

    <!-- 修改详情弹窗内容 -->
    <lay-layer v-model="detailVisible" title="详情查看" :type="4" :area="['950px', '100%']" :shade="true">
        <div style="padding: 20px">
            <lay-descriptions title="基本信息" :column="2" border>
                <lay-descriptions-item label="考评对象">
                    <lay-tag size="small" type="primary">{{ detailForm.nickname }}</lay-tag>
                </lay-descriptions-item>
                <lay-descriptions-item label="科室">
                    <lay-tag size="small" type="normal">{{ detailForm.group_name }}</lay-tag>
                </lay-descriptions-item>
                <lay-descriptions-item label="发生日期">
                    {{ detailForm.fsdate }}
                </lay-descriptions-item>
                <lay-descriptions-item label="证明人">
                    <lay-tag size="small" type="warm">{{ detailForm.zm_nickname }}</lay-tag>
                </lay-descriptions-item>
                <lay-descriptions-item label="病区名称">
                    {{ detailForm.bq_name }}
                </lay-descriptions-item>
                <lay-descriptions-item label="患者姓名">
                    {{ detailForm.hz_name }}
                </lay-descriptions-item>
            </lay-descriptions>

            <lay-descriptions title="退还信息" :column="2" border style="margin-top: 20px">
                <lay-descriptions-item label="退还金额">
                    <lay-tag size="small" type="danger">¥{{ detailForm.refunding_amount }}</lay-tag>
                </lay-descriptions-item>
                <lay-descriptions-item label="退还日期">
                    {{ detailForm.thdate }}
                </lay-descriptions-item>
                <lay-descriptions-item label="退还方式">
                    <lay-tag size="small" type="normal">{{ formatRefundType(detailForm.refunding_type) }}</lay-tag>
                </lay-descriptions-item>
                <lay-descriptions-item label="状态">
                    <lay-tag size="small"
                        :type="detailForm.status == 2 ? 'primary' : detailForm.status == 3 ? 'danger' : 'warm'">
                        {{ formatStatus(detailForm.status) }}
                    </lay-tag>
                </lay-descriptions-item>
                <lay-descriptions-item label="备注" :span="2">
                    {{ detailForm.notes || '暂无备注' }}
                </lay-descriptions-item>
            </lay-descriptions>

            <lay-descriptions v-if="detailForm.fj_url" title="附件信息" :column="1" border style="margin-top: 20px">
                <lay-descriptions-item label="附件">
                    <a style="color: #009688" :href="detailForm.fj_url" target="_blank">附件下载</a>
                </lay-descriptions-item>
            </lay-descriptions>

            <div style="text-align: center; margin-top: 20px;">
                <lay-button @click="detailVisible = false">关闭</lay-button>
            </div>
        </div>
    </lay-layer>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import dayjs from "dayjs";
import { getDoctorName, getRejectRedEnvelopes, rejectRedEnvelopesCreate, rejectRedEnvelopesUpdate, userGroupData } from '@/api/module/home';
import { layer } from '@layui/layui-vue';
import { useUserStore } from '@/store/user';
const userStore = useUserStore()
// 搜索表单
const searchForm = ref({
    fsdate: '',
    user_id: '',
    status: ''
})

// 修改分页参数的定义方式
const page = reactive({
    current: 1,
    limit: 10,
    total: 1
})
const cutOptions = {
    copperOption: {
        center: false,
        aspectRatio: 1,
    }
}
const cutUrl = ref("");
const uploadRef = ref(null)
const file1 = ref([]);
const getCutDone = (res) => {
    console.log("getCutDone", res);
    cutUrl.value = res.msg;
};
const getFileDone = (res) => {
    var date = JSON.parse(res.data);
    console.log("getFileDone", date);
    form.value.fj_url = date.data.fullurl;
    //uploadRef.value.submit()
};
// 添加级联选择器所需的数据结构
const ksOptions = ref([])
const replaceFields = {
    label: 'name',
    value: 'id',
    children: 'children'
}
// 修改获取用户列表方法为懒加载方法
const getGroupList = () => {
    userGroupData({}).then((res) => {
        if (res.code === 1) {
            ksOptions.value = res.data;
        } else {
            layer.msg(res.msg, { icon: 2 })
        }
    })
}
const userList = ref([]);
const getUserList = () => {
    getDoctorName({}).then((res) => {
        if (res.code === 1) {
            userList.value = res.data;
        }
    })
}
// 表格数据
const dataSource = ref([])

// 添加左侧树相关的变量
const data = ref([])
const leftId = ref('')
const isFold = ref(false)

// 修改获取列表数据的方法，添加科室id参数
const getList = () => {
    const params = {
        page: page.current,
        size: page.limit,
        group_id: leftId.value, // 添加科室id参数
        ...searchForm.value
    }
    getRejectRedEnvelopes(params).then((res) => {
        if (res.code === 1) {
            dataSource.value = res.data.data;
            page.total = res.data.count;
        } else {
            layer.msg(res.msg, { icon: 2 })
        }
    })
}

// 格式化退还方式
const formatRefundType = (type) => {
    return type == 1 ? '现金' : '转账'
}

// 修改表格列配置
const columns = [
    {
        title: '序号',
        width: '90px',
        key: 'id',
        align: 'center'
    },
    {
        title: '发生日期',
        width: '120px',
        key: 'fsdate',
        align: 'center'
    },
    {
        title: '考评对象',
        width: '120px',
        key: 'nickname',
        align: 'center'
    },
    {
        title: '科室',
        width: '120px',
        key: 'group_name',
        align: 'center'
    },
    {
        title: '病区',
        width: '120px',
        key: 'bq_name',
        align: 'center'
    },
    {
        title: '患者姓名',
        width: '120px',
        key: 'hz_name',
        align: 'center'
    },
    {
        title: '退还金额',
        width: '120px',
        key: 'refunding_amount',
        align: 'center',
        customSlot: 'refundAmount'
    },
    {
        title: '退还日期',
        width: '120px',
        key: 'thdate',
        align: 'center'
    },
    {
        title: '退还方式',
        width: '120px',
        key: 'refunding_type',
        align: 'center',
        customSlot: 'refundType'
    },
    {
        title: '状态',
        width: '130px',
        key: 'status',
        align: 'center',
        customSlot: 'status'
    },
    {
        title: '操作',
        width: '150px',
        key: 'operation',
        align: 'center',
        fixed: 'right',
        customSlot: 'operation'
    }
]

// 弹窗控制
const visible = ref(false)
const formTitle = ref('新增拒收红包')

// 修改表单数据定义
const form = ref({
    user_id: '',
    group_id: [] as (string | number)[],
    fsdate: '',
    zm_user_id: '',
    hz_name: '',
    bq_name: '',
    refunding_amount: 0,
    thdate: '',
    refunding_type: '',
    fj_url: '',
    notes: ''
})

// 添加编辑状态标识
const isEdit = ref(false)
const editId = ref('')

// 搜索方法
const toSearch = () => {
    page.current = 1
    getList()
}

// 重置方法
const toReset = () => {
    searchForm.value = {
        fsdate: '',
        user_id: '',
        status: ''
    }
    page.current = 1
    getList()
}
// 打开新增弹窗
const openAdd = () => {
    console.log(userStore.userInfo);
    formTitle.value = '新增拒收红包'
    isEdit.value = false
    editId.value = ''
    form.value = {
        user_id: userStore.userInfo.id,
        group_id: '',
        fsdate: '',
        zm_user_id: '',
        hz_name: '',
        bq_name: '',
        refunding_amount: 0,
        thdate: '',
        refunding_type: '',
        fj_url: '',
        notes: ''
    }
    visible.value = true
}

// 修改提交表单方法
const submitForm = () => {
    if (!form.value.user_id) {
        layer.msg('请选择考评对象', { icon: 2 })
        return
    }
    if (!form.value.fsdate) {
        layer.msg('请选择发生日期', { icon: 2 })
        return
    }
    if (!form.value.zm_user_id) {
        layer.msg('请选择证明人', { icon: 2 })
        return
    }
    if (!form.value.hz_name) {
        layer.msg('请输入患者姓名', { icon: 2 })
        return
    }
    if (!form.value.refunding_amount) {
        layer.msg('请输入退还金额', { icon: 2 })
        return
    }
    if (!form.value.thdate) {
        layer.msg('请选择退还日期', { icon: 2 })
        return
    }
    if (!form.value.refunding_type) {
        layer.msg('请选择退还方式', { icon: 2 })
        return
    }

    const params = {
        ...form.value,
        // 获取级联选择器最后一个选中值
        group_id: userStore.userInfo.group_id
    }

    const submitRequest = rejectRedEnvelopesCreate(params);

    submitRequest.then(res => {
        if (res.code === 1) {
            layer.msg('新增成功', { icon: 1 })
            visible.value = false
            getList()
        } else {
            layer.msg(res.msg, { icon: 2 })
        }
    })
}
const confirm = (data: any, type: number) => {
    const submitRequest = rejectRedEnvelopesUpdate({ status: type, id: data.id });
    submitRequest.then(res => {
        if (res.code === 1) {
            layer.msg('审核成功', { icon: 1 })
            getList()
        }
    })
}
// 添加分页变化处理方法
const handlePageChange = (current: number) => {
    page.current = current
    getList()
}

// 添加每页条数变化处理方法
const handleLimitChange = (limit: number) => {
    page.current = 1
    page.limit = limit
    getList()
}

// 添加状态格式化方法
const formatStatus = (status: number) => {
    switch (status) {
        case 1:
            return '待审核'
        case 2:
            return '已通过'
        case 3:
            return '已驳回'
        default:
            return '未知'
    }
}

// 详情弹窗控制
const detailVisible = ref(false)
const detailForm = ref({
    nickname: '',
    group_name: '',
    fsdate: '',
    zm_user_name: '',
    bq_name: '',
    hz_name: '',
    refunding_amount: '',
    thdate: '',
    refunding_type: '',
    status: '',
    fj_url: '',
    notes: ''
})

// 打开详情弹窗
const openDetail = (data: any) => {
    detailForm.value = { ...data }
    detailVisible.value = true
}

// 添加获取左侧科室列表的方法
const getLeftList = () => {
    userGroupData({}).then((res) => {
        if (res.code === 1) {
            data.value = res.data;
            if (userStore.userInfo.level == 1) {
                leftId.value = res.data[0].id;
            } else {
                leftId.value = userStore.userInfo.group_id;
            }
            getList(); // 获取右侧列表数据
        } else {
            layer.msg(res.msg, { icon: 2 })
        }
    })
}

// 修改点击科室树节点的处理方法
function handleClick(node: any) {
    leftId.value = node.id
    getList();
}

onMounted(() => {
    getLeftList(); // 替换原有的 getList()
    getUserList();
    getGroupList();
})
</script>

<style>
.layui-table-header .layui-table-cell {
    background-color: #ECF8FA !important;
}

.search-form-wrapper {
    width: 100%;
    overflow-x: auto;
}

.search-form-wrapper::-webkit-scrollbar {
    height: 8px;
}

.search-form-wrapper::-webkit-scrollbar-thumb {
    background-color: #e0e0e0;
    border-radius: 4px;
}

.search-form-wrapper::-webkit-scrollbar-track {
    background-color: #f5f5f5;
}
</style>

<style scoped>
/* 添加左侧树的样式 */
.organization-box {
    width: calc(100vw - 240px);
    height: calc(100vh - 110px);
    margin-top: 10px;
    box-sizing: border-box;
    background-color: #fff;
    overflow: hidden;
}

.left-tree {
    display: inline-block;
    padding: 20px 15px 0 5px;
    height: 1200px;
    border-right: 1px solid #e6e6e6;
    box-sizing: border-box;
    position: relative;
}

.isFold {
    position: absolute;
    top: 36%;
    right: -10px;
    width: 26px;
    height: 26px;
    line-height: 26px;
    border-radius: 13px;
    background-color: #fff;
    border: 1px solid #e6e6e6;
    cursor: pointer;
}

.isChecked {
    display: inline-block;
    background-color: #e8f1ff;
    color: red;
}
</style>
