<template>
    <div class="inventoryManagement">
        <!-- <TitleComponent title="出入库单管理" subtitle="管理光伏和风电设备备品备件的出入库记录" /> -->
        <el-row :gutter="20">
            <el-col :span="16" class="list" style="flex-grow: 1;display: flex;">
                <el-card style="border-radius: 10px;height: 100%;display: flex;flex-direction: column;flex: 1;">
                    <div style="height: 100%;flex: 1;">
                        <div class="top">
                            <div class="title">单据列表</div>
                            <div class="button-actions">
                                <button :class="{ active: type === 'ruku' }" @click="changeType('ruku')">入库单</button>
                                <button :class="{ active: type === 'chuku' }" @click="changeType('chuku')">出库单</button>
                            </div>
                        </div>
                        <div class="content" style="height: 100%;flex: 1;">
                            <!-- 第一排：四个输入项 -->
                            <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                                :leave-active-class="proxy?.animate.searchAnimate.leave">
                                <div v-show="showSearch" class="mb-[10px]">
                                    <el-card shadow="hover">
                                        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                                            <el-form-item label="单据编号" prop="danjvNumber">
                                                <el-input v-model="queryParams.danjvNumber" placeholder="请输入单据编号"
                                                    clearable @keyup.enter="handleQuery" />
                                            </el-form-item>
                                            <!-- <el-form-item label="设备类型" prop="shebeiType">
                                                <el-select v-model="queryParams.shebeiType" placeholder="请选择设备类型"
                                                    clearable>
                                                    <el-option v-for="dict in wz_device_type" :key="dict.value"
                                                        :label="dict.label" :value="dict.value" />
                                                </el-select>
                                            </el-form-item> -->
                                            <!-- <el-form-item label="审核状态" prop="auditStatus">
                                                <el-select v-model="queryParams.auditStatus" placeholder="请选择审核状态"
                                                    clearable>
                                                    <el-option v-for="dict in shenheStatus" :key="dict.value"
                                                        :label="dict.label" :value="dict.value" />
                                                </el-select>
                                            </el-form-item> -->
                                            <el-form-item label="开始日期" prop="startDate">
                                                <el-date-picker v-model="queryParams.startDate" type="date"
                                                    placeholder="请选择开始日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                                                    style="width: 100%" />
                                            </el-form-item>
                                            <el-form-item label="结束日期" prop="endDate">
                                                <el-date-picker v-model="queryParams.endDate" type="date"
                                                    placeholder="请选择结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                                                    style="width: 100%" />
                                            </el-form-item>
                                            <el-form-item>
                                                <el-button type="primary" icon="Search"
                                                    @click="handleQuery">搜索</el-button>
                                                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                                            </el-form-item>
                                        </el-form>
                                    </el-card>
                                </div>
                            </transition>
                            <div style="margin-top: 10px; display: flex; justify-content: flex-end;">
                                <el-button type="primary" @click="handleAdd">+{{ type === 'chuku' ? '添加出库单'
                                    : '添加入库单' }}</el-button>
                            </div>
                            <el-table v-loading="loading" border :data="churukudanList"
                                style="width: 100%;margin-top: 15px;">
                                <el-table-column label="单据编号" align="center" prop="danjvNumber" />
                                <el-table-column label="产品名称" align="center" prop="chanpinName"></el-table-column>
                                <el-table-column label="经手人" align="center" prop="jingshourenName" width="80px" />
                                <el-table-column label="操作时间" align="center" prop="updateTime" />
                                <el-table-column label="总数量" align="center" prop="zonNumber" width="80px" />
                                <!-- <el-table-column label="审核状态" align="center" prop="shenheStatus">
                                    <template #default="scope">
                                        <el-tag :type="getTagType(shenheStatus, scope.row.shenheStatus)" as="span">
                                            {{ getTagLabel(shenheStatus, scope.row.shenheStatus) }}
                                        </el-tag>
                                    </template>
                                </el-table-column> -->
                                <el-table-column label="单据类型" align="center" prop="danjvType">
                                    <template #default="scope">
                                        <el-tag :type="getTagType(danjvType, scope.row.danjvType)">
                                            {{ getTagLabel(danjvType, scope.row.danjvType) }}
                                        </el-tag>
                                    </template>
                                </el-table-column>
                                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                                    <template #default="scope">
                                        <!-- <el-button link type="primary" @click="handleUpdate(scope.row)"
                                            v-hasPermi="['personnel:churukudan:edit']">修改</el-button> -->
                                        <el-button link type="primary" @click="handleDetail(scope.row)"
                                            v-hasPermi="['personnel:churukudan:query']">详情</el-button>
                                        <el-button link type="primary" @click="handleDelete(scope.row)"
                                            v-hasPermi="['personnel:churukudan:remove']">删除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                            <div class="tool">
                                <div class="pagination-section">
                                    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                                        v-model:limit="queryParams.pageSize" @pagination="getList" />
                                </div>
                            </div>
                        </div>
                    </div>

                </el-card>
            </el-col>
            <el-col :span="8">
                <el-card style="border-radius: 10px;">
                    <div class="item-box">
                        <div class="title">系统信息</div>
                        <div class="content">
                            <SystemInfo />
                        </div>
                    </div>
                    <div class="item-box">
                        <div class="title">数据分析</div>
                        <div class="content">
                            <DataAnalysis :lineData="lineData" :barData="barData" />
                        </div>
                    </div>
                </el-card>
            </el-col>
        </el-row>
        <!-- 添加或修改运维-物资-出入库单管理对话框 -->
        <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
            <el-form ref="churukudanFormRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="单据类型" prop="danjvType">
                    <el-select v-model="form.danjvType" placeholder="请选择单据类型">
                        <el-option v-for="dict in danjvType" :key="dict.value" :label="dict.label"
                            :value="dict.value"></el-option>
                    </el-select>
                </el-form-item>
                <!-- <el-form-item label="设备类型" prop="shebeiType">
                    <el-select v-model="form.shebeiType" placeholder="请选择设备类型">
                        <el-option v-for="dict in wz_device_type" :key="dict.value" :label="dict.label"
                            :value="dict.value"></el-option>
                    </el-select>
                </el-form-item> -->
                <el-form-item label="产品名称" prop="chanpinName">
                    <el-select v-model="form.chanpinName" placeholder="请选择产品名称">
                        <el-option v-for="dict in chanpinSelect" :key="dict.value" :label="dict.label"
                            :value="dict.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="经手人id" prop="jingshourenId">
                    <el-input v-model="form.jingshourenId" placeholder="请输入经手人id" />
                </el-form-item>
                <el-form-item label="经手人" prop="jingshourenName">
                    <el-input v-model="form.jingshourenName" placeholder="请输入经手人" />
                </el-form-item>
                <el-form-item label="联系电话" prop="contactNumber">
                    <el-input v-model="form.contactNumber" placeholder="请输入联系电话" />
                </el-form-item>
                <el-form-item label="总数量" prop="zonNumber">
                    <el-input v-model="form.zonNumber" placeholder="请输入总数量" type="number" min="0"/>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 详情对话框 -->
        <el-dialog title="出入库单详情" v-model="detailVisible" width="500px" append-to-body>
            <el-descriptions :column="1" border>
                <el-descriptions-item label="单据类型">{{ getTagLabel(danjvType, detailData.danjvType)
                }}</el-descriptions-item>
                <el-descriptions-item label="单据编号">{{ detailData.danjvNumber }}</el-descriptions-item>
                <el-descriptions-item label="设备类型">{{ getTagLabel(wz_device_type, detailData.shebeiType)
                }}</el-descriptions-item>
                <el-descriptions-item label="经手人">{{ detailData.jingshourenName }}</el-descriptions-item>
                <el-descriptions-item label="联系电话">{{ detailData.contactNumber }}</el-descriptions-item>
                <el-descriptions-item label="总数量">{{ detailData.zonNumber }}</el-descriptions-item>
                <el-descriptions-item label="审核状态">
                    <dict-tag :options="shenheStatus" :value="detailData.shenheStatus"></dict-tag>
                </el-descriptions-item>
            </el-descriptions>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="detailVisible = false">关闭</el-button>
                </div>
            </template>
        </el-dialog>

    </div>
</template>
<style scoped>
.inventoryManagement {
    background-color: #F2F8FC;
    padding: 20px;
}

.button-actions button {
    background: none;
    border: 1px solid #e0e0e0;
    padding: 5px 12px;
    border-radius: 4px;
    margin-left: 8px;
    cursor: pointer;
    font-size: 12px;
    transition: all 0.2s ease;
}

.button-actions button.active {
    background-color: #186DF5;
    color: white;
    border-color: #186DF5;
}

.top {
    display: flex;
    justify-content: space-between;

    .title {
        font-family: "Alibaba-PuHuiTi-Bold";
        color: rgba(0, 30, 59, 1);
        font-weight: bold;
    }
}

.list .content {
    margin-top: 20px;
}

.menu {
    background-color: #F2F2F2;
    padding: 20px;
}

/* 分页区域样式 */
.pagination-section {
    background-color: #fff;
    border-radius: 8px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.pagination-info {
    font-size: 14px;
    color: #606266;
}

.pagination-controls .el-pagination {
    margin: 0;
}


.pagination-controls .el-pagination button {
    min-width: 32px;
    height: 32px;
    line-height: 32px;
    border-radius: 4px;
}

.pagination-controls .el-pagination .el-pager li {
    min-width: 32px;
    height: 32px;
    line-height: 32px;
    border-radius: 4px;
}

.pagination-controls .el-pagination .el-pager li.active {
    background-color: #409eff;
    color: #fff;
}

.tool {

    margin-top: 10px;
    display: flex;
    justify-content: space-between;
}

.item-box {
    .title {
        font-family: "Alibaba-PuHuiTi-Bold";
        font-size: 18px;
        font-weight: 400;
        letter-spacing: 0px;
        line-height: 24px;
        color: rgba(0, 30, 59, 1);
        margin-top: 10px;
    }
}

/* 详情弹窗样式 */
.detail-container {
    padding: 10px 0;
}

.detail-item {
    display: flex;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f0f0f0;
}

.detail-label {
    font-weight: 500;
    color: #606266;
    width: 120px;
}

.detail-value {
    color: #303133;
    flex: 1;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    padding: 12px 0;
}

:v-deep(.el-card__body) {
    height: 100%;
}
</style>
<script setup lang="ts">
import SystemInfo from './components/SystemInfo.vue';
import DataAnalysis from './components/DataAnalysis.vue';
import { ref, computed } from 'vue';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
import { listChurukudan, getChurukudan, delChurukudan, addChurukudan, updateChurukudan, getChuRuKuCountLine, getChuRuKuDayCountBar, getChanpinLists } from '@/api/wuziguanli/churuku/index';
import { ChurukudanVO, ChurukudanQuery, ChurukudanForm } from '@/api/wuziguanli/churuku/types';
const { wz_device_type } = toRefs<any>(proxy?.useDict('wz_device_type'));

import { getCurrentMonthDates } from '@/utils/getDate';
const currentMonthDates = getCurrentMonthDates();
// 导入用户store
import { useUserStore } from '@/store/modules/user';
// 获取用户store
const userStore = useUserStore();

const churukudanList = ref<ChurukudanVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const total = ref(0);
// 单据类型切换变量 - 默认入库单
const type = ref<string>('ruku');

/** 切换单据类型 */
const changeType = (newType: string) => {
    type.value = newType;
    // 更新查询参数
    queryParams.value.pageNum = 1;
    queryParams.value.danjvType = newType === 'chuku' ? '1' : '2';
    // 重新加载数据
    getList();
}

// 单据类型
const danjvType = ref([
    {
        value: '1',
        label: '出库单',
        type: 'primary'
    },
    {
        value: '2',
        label: '入库单',
        type: 'success'
    }
]);
// 审核类型
const shenheStatus = ref([
    {
        value: 'draft',
        label: '草稿',
        type: 'primary'
    },
    {
        value: 'waiting',
        label: '待审核',
        type: 'warning',
    },
    {
        value: 'finish',
        label: '已完成',
        type: 'success'
    }
])
// 根据字典数组和值获取标签类型
const getTagType = (dictArray: any[], value: any): string => {
    if (!dictArray || !value) return '';
    const item = dictArray.find(item => item.value === value);
    return item?.type || '';
}

// 根据字典数组和值获取标签文本
const getTagLabel = (dictArray: any[], value: any): string => {
    if (!dictArray || !value) return '';
    const item = dictArray.find(item => item.value === value);
    return item?.label || value;
}

const queryFormRef = ref<ElFormInstance>();
const churukudanFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
});

// 详情弹窗显示状态
const detailVisible = ref(false);

// 详情数据
const detailData = ref<ChurukudanVO>({} as ChurukudanVO);

const initFormData: ChurukudanForm = {
    id: undefined,
    projectId: undefined,
    danjvNumber: undefined,
    shebeiType: undefined,
    jingshourenId: undefined,
    jingshourenName: undefined,
    contactNumber: undefined,
    zonNumber: undefined,
    shenheStatus: undefined,
    danjvType: undefined,
    updateTime: undefined,
    auditStatus: undefined,
    chanpinName: undefined,
    chanpinId: undefined,
}
const data = reactive<PageData<ChurukudanForm, ChurukudanQuery>>({
    form: { ...initFormData },
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: undefined,
        danjvNumber: undefined,
        shebeiType: undefined,
        shenheStatus: undefined,
        startDate: undefined,
        endDate: undefined,
        auditStatus: undefined,
        chanpinName: undefined,
        chanpinId: undefined,
        danjvType: '2', // 默认显示入库单
        params: {
        }
    },
    rules: {
        // shebeiType: [
        //     { required: true, message: "设备类型不能为空", trigger: "change" }
        // ],
        chanpinName: [
            { required: true, message: "产品名称不能为空", trigger: "change" }
        ],
        jingshourenId: [
            { required: true, message: "经手人id不能为空", trigger: "blur" }
        ],
        jingshourenName: [
            { required: true, message: "经手人不能为空", trigger: "blur" }
        ],
        zonNumber: [
            { required: true, message: "总数量不能为空", trigger: "blur" }
        ],
        danjvType: [
            { required: true, message: "单据状态不能为空", trigger: "change" }
        ],
        // 手机号码格式校验
        contactNumber: [
            { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码格式", trigger: "blur" }
        ]
    }
});

const { queryParams, form, rules } = toRefs(data);
// 查询产品名称列表
const chanpinList = ref<any[]>([]);
const chanpinSelect = ref<any[]>([]);
// 查询产品名称列表
const getChanpinList = async () => {
    try {
        const res = await getChanpinLists({ projectId: userStore.selectedProject.id });
        chanpinList.value = res.data || [];
        chanpinSelect.value = chanpinList.value.map(item => ({
            label:item.caigouPlanName +'-'+item.chanpinName,
            value: item.id
        }));
        console.log('chanpinSelect.value', chanpinSelect.value);
        
    } catch (error) {
        console.error('获取产品名称列表失败:', error);
        proxy?.$modal.msgError("获取产品名称列表失败，请稍后重试");
        chanpinList.value = [];
    }
}

/** 查询运维-物资-出入库单管理列表 */
const getList = async () => {
    loading.value = true;
    try {
        const res = await listChurukudan(queryParams.value);
        churukudanList.value = res.rows || [];
        total.value = res.total || 0;
    } catch (error) {
        console.error('获取出入库单列表失败:', error);
        proxy?.$modal.msgError("获取数据失败，请稍后重试");
        churukudanList.value = [];
        total.value = 0;
    } finally {
        loading.value = false;
    }
}

/** 取消按钮 */
const cancel = () => {
    reset();
    dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
    form.value = { ...initFormData };
    churukudanFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
    // 检查日期范围筛选条件
    if ((queryParams.value.startDate && !queryParams.value.endDate) ||
        (!queryParams.value.startDate && queryParams.value.endDate)) {
        proxy?.$modal.msgWarning("时间范围筛选必须同时选择开始日期和结束日期");
        return;
    }
    queryParams.value.pageNum = 1;
    getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
}


/** 新增按钮操作 */
const handleAdd = () => {
    reset();
    if (userStore.selectedProject && userStore.selectedProject.id) {
        form.value.projectId = userStore.selectedProject.id;
    }
    // 根据当前选择的类型自动设置单据类型
    form.value.danjvType = type.value === 'chuku' ? '1' : '2';
    dialog.visible = true;
    dialog.title = type.value === 'chuku' ? "添加出库单" : "添加入库单";
}

/** 修改按钮操作 */
// const handleUpdate = async (row?: ChurukudanVO) => {
//     reset();
//     const _id = row?.id || ids.value[0];
//     if (!_id) {
//         proxy?.$modal.msgWarning("请选择要修改的数据");
//         return;
//     }
//     try {
//         const res = await getChurukudan(_id);
//         Object.assign(form.value, res.data);
//         dialog.visible = true;
//         dialog.title = "修改运维-物资-出入库单管理";
//     } catch (error) {
//         console.error('获取出入库单详情失败:', error);
//         proxy?.$modal.msgError("获取数据失败，请稍后重试");
//     }
// }

/** 提交按钮 */
const submitForm = () => {
    churukudanFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
            buttonLoading.value = true;
            try {
                form.value.chanpinId = form.value.chanpinName
                if (form.value.id) {
                    await updateChurukudan(form.value);
                    proxy?.$modal.msgSuccess("修改成功");
                } else {
                    await addChurukudan(form.value);
                    proxy?.$modal.msgSuccess("添加成功");
                }
                dialog.visible = false;
                await getList();
            } catch (error) {
                console.error('保存出入库单失败:', error);
                proxy?.$modal.msgError("操作失败，请稍后重试");
            } finally {
                buttonLoading.value = false;
            }
        }
    });
}

/** 详情按钮操作 */
const handleDetail = async (row?: ChurukudanVO) => {
    if (!row?.id) {
        proxy?.$modal.msgWarning("请选择要查看详情的数据");
        return;
    }
    try {
        const res = await getChurukudan(row.id);
        detailData.value = res.data || {} as ChurukudanVO;
        detailVisible.value = true;
    } catch (error) {
        console.error('获取出入库单详情失败:', error);
        proxy?.$modal.msgError("获取详情失败，请稍后重试");
    }
}

/** 删除按钮操作 */
const handleDelete = async (row?: ChurukudanVO) => {
    const _ids = row?.id || ids.value;
    if (!_ids || (_ids instanceof Array && _ids.length === 0)) {
        proxy?.$modal.msgWarning("请选择要删除的数据");
        return;
    }
    try {
        const confirmed = await proxy?.$modal.confirm('是否确认删除运维-物资-出入库单管理编号为"' + _ids + '"的数据项？');
        if (!confirmed) return;
        loading.value = true;
        await delChurukudan(_ids);
        proxy?.$modal.msgSuccess("删除成功");
        await getList();
    } catch (error) {
        console.error('删除出入库单失败:', error);
        proxy?.$modal.msgError("删除失败，请稍后重试");
    } finally {
        loading.value = false;
    }
}

// 折线图数据获取
const lineData = ref<any>();
const fetchChuRuKuCountLineData = async () => {
    if (!queryParams.value.projectId) {
        return;
    }
    let data = {
        projectId: queryParams.value.projectId,
        startDate: currentMonthDates[0].fullDate,
        endDate: currentMonthDates[currentMonthDates.length - 1].fullDate,
    }
    try {
        const res = await getChuRuKuCountLine(data);
        if (res.code === 200) {
            lineData.value = res.data;
        }
        // 这里可以添加数据处理和图表更新的逻辑
    } catch (error) {
        proxy?.$modal.msgError("获取统计数据失败");
    }
}
// 柱状图数据获取
const barData = ref<any>();
const fetchChuRuKuCountBarData = async () => {
    if (!queryParams.value.projectId) {
        return;
    }
    let data = {
        projectId: queryParams.value.projectId,
        startDate: currentMonthDates[0].fullDate,
        endDate: currentMonthDates[currentMonthDates.length - 1].fullDate,
    }
    try {
        const res = await getChuRuKuDayCountBar(data);
        if (res.code === 200) {
            barData.value = res.data;
        }
        // 这里可以添加数据处理和图表更新的逻辑
    } catch (error) {
        proxy?.$modal.msgError("获取统计数据失败");
    }
}
// 监听用户选择的项目变化
watch(() => userStore.selectedProject, (newProject) => {
    if (newProject && newProject.id) {
        queryParams.value.projectId = newProject.id;
        // 只在新增表单时设置projectId，编辑表单保留原有值
        if (!form.value.id) {
            form.value.projectId = newProject.id;
        }
        // 调用getList刷新数据
        getList();
        fetchChuRuKuCountLineData();
        fetchChuRuKuCountBarData();
    }
}, { immediate: true, deep: true });
onMounted(() => {
    getList();
    fetchChuRuKuCountLineData();
    fetchChuRuKuCountBarData();
    // 查询产品名称列表
    getChanpinList();
});

// 组件卸载时清空projectId
onUnmounted(() => {
    queryParams.value.projectId = undefined;
    form.value.projectId = undefined;
});
</script>