<template>
    <z-paging ref="paging" v-model="list" bgColor="#f7f7f7" @query="query" hide-no-more-inside hide-empty-view>
        <template #top>
            <ut-navbar title="加工任务详情" :fixed="false"> </ut-navbar>
        </template>
        <view class="pd-24">
            <view class="bg-#fff pd-24 pt-16 b-radius p-rtv" @click="gotoDetail">
                <!-- 任务类型标签 -->
                <view v-if="+taskDetail?.processType == 1 && +taskDetail?.processMedType == 1" class="bg-#91C747 c-#fff f-w-5 pd-10 pt-4 pb-4 f-s-20" style="border-radius: 16rpx 0 16rpx 0; width: max-content; position: absolute; top: 0rpx; left: 0rpx">种子初加工</view>
                <view v-if="+taskDetail?.processType == 1 && +taskDetail?.processMedType == 2" class="bg-#C7A962 c-#fff f-w-5 pd-10 pt-4 pb-4 f-s-20" style="border-radius: 16rpx 0 16rpx 0; width: max-content; position: absolute; top: 0rpx; left: 0rpx">药材初加工</view>
                <view v-if="+taskDetail?.processType == 2" class="bg-#37A954 c-#fff f-w-5 pd-10 pt-4 pb-4 f-s-20" style="border-radius: 16rpx 0 16rpx 0; width: max-content; position: absolute; top: 0rpx; left: 0rpx">趁鲜切制</view>
                <!-- 日期范围 -->
                <view v-if="taskDetail?.processingDate || taskDetail?.processingDateEnd" class="d-flex a-c j-ed">
                    <view class="c-#999 f-s-24">{{ taskDetail?.processingDate }} 至 {{ taskDetail?.processingDateEnd }}</view>
                </view>
                <!-- 药材名称 -->
                <view class="d-flex a-c mb-10">
                    <view class="f-s-34 f-w-5 c-#333 mr-10">{{ taskDetail?.variety || taskDetail?.medicineName }}</view>
                    <view v-if="+taskDetail?.processMedType == 1" class="f-s-24 c-#666">{{ selectDictLabel(pt_stock_type, taskDetail?.processMedType) }}</view>
                </view>
                <!-- 加工批号 -->
                <view class="d-flex f-s-28 pd2-4-0">
                    <view class="c-#666">加工批号：</view>
                    <view class="c-#333 f-w-5 flex1">{{ taskDetail?.processCode }}</view>
                </view>
                <!-- 执行标准 -->
                <view class="d-flex f-s-28 pd2-4-0">
                    <view class="c-#666">执行标准：</view>
                    <view class="c-#333 f-w-5 flex1">
                        <span>{{ selectDictLabel(pt_standard_type, taskDetail?.standardType) }}</span>
                        <span v-if="taskDetail?.standardDetailName" class="c-#666">({{ taskDetail?.standardDetailName }})</span>
                    </view>
                </view>
                <!-- 加工工艺 -->
                <view class="d-flex f-s-28 pd2-4-0">
                    <view class="c-#666">加工工艺：</view>
                    <view class="c-#333 f-w-5 flex1 d-flex a-c" style="justify-content: flex-start">
                        <template v-for="(item, index) in (taskDetail?.ptech || '').split(',')" :key="index">
                            <span v-if="+index > 0 && item" class="c-#999 ml-10 mr-10">→</span>
                            <span v-if="item">{{ item }}</span>
                        </template>
                        <span v-if="!taskDetail?.ptech" class="c-#999">-</span>
                    </view>
                </view>
                <view class="d-flex j-sb">
                    <!-- 加工负责人 -->
                    <view class="d-flex f-s-28 pd2-4-0">
                        <view class="c-#666">加工负责人：</view>
                        <view class="c-#333 f-w-5 flex1">{{ taskDetail?.contactName || '-' }}</view>
                    </view>
                    <!-- 去修改按钮 -->
                    <view class="d-flex a-c j-ed pd2-4-0">
                        <view class="c-primary f-s-28 d-flex a-c" @click.stop="goEdit">
                            <span>去修改</span>
                            <up-icon name="arrow-right" size="24rpx" class="ml-5"></up-icon>
                        </view>
                    </view>
                </view>
            </view>
            <!-- Tab 切换 -->
            <view class="d-flex a-c bg-#f7f7f7 mb-16">
                <up-tabs :list="tabs" @change="onTabChange" :current="activeTab" lineWidth="60"></up-tabs>
            </view>
            <!-- 原料信息列表 -->
            <view v-if="+activeTab == 0">
                <view v-if="list.length === 0 && +activeTab == 0" class="d-flex flex-cln a-c pd-40">
                    <ut-empty color="#ccc" size="28rpx" image=" https://ta.zycpzs.cn/oss-file/smart-trace/szyy/images-plt/plant/noEmpty.png">暂无加工原料信息</ut-empty>
                    <up-button type="primary" @click="goAssociate">去关联原料信息</up-button>
                </view>
                <view v-else class="d-flex a-c mb-16">
                    <view class="c-#999 f-s-28">使用的加工原料批次</view>
                    <view class="flex1"></view>
                    <up-button type="error" style="width: 160rpx; height: 60rpx" @click="withdraw">撤回用料</up-button>
                </view>
                <view v-for="(item, index) in list" :key="index" class="bg-#fff b-radius pd-24">
                    <!-- 类型标签 -->
                    <view class="d-flex j-sb a-c li-item-head mb-16">
                        <view class="li-left-tag" :class="{ [`bg-instore-${item?.storageInfo?.instoreType}`]: true }">{{ selectDictLabel(pt_fresh_instore_type, item?.storageInfo?.instoreType) }}</view>
                        <view class="f-s-22 c-#666 pt-10">{{ item?.updateTime || item?.createTime }}</view>
                    </view>
                    <view class="d-flex a-c j-sb mb-10">
                        <!-- 物料名称 -->
                        <view class="d-flex" style="align-items: flex-end">
                            <view class="f-s-32 f-w-5 c-#333 mr-10">{{ item?.materialName }}</view>
                            <view class="f-s-24 c-#999">{{ item?.storageInfo?.partName }}</view>
                        </view>
                        <!-- 状态 -->
                        <view class="d-flex a-c" v-if="item?.storageInfo?.examinReport">
                            <view class="c-#37A954 f-s-24 bg-#EDF7F0 pd-8 radius-8">已检验</view>
                        </view>
                    </view>
                    <!-- 溯源入库 -->
                    <template v-if="+item?.storageInfo?.instoreType == 1">
                        <!-- 采收批号 -->
                        <view class="d-flex pd2-4-0 f-s-28">
                            <view class="c-#666">入库批号：</view>
                            <view class="c-#333 f-w-5 flex1">{{ item?.storageInfo?.batchCode }}</view>
                        </view>
                        <view class="d-flex pd2-4-0 f-s-28">
                            <view class="c-#666">供应商：</view>
                            <view class="c-#333 f-w-5 flex1">{{ item?.storageInfo?.supplier || '-' }}</view>
                        </view>
                    </template>
                    <!-- 非溯源入库 -->
                    <template v-if="+item?.storageInfo?.instoreType == 2">
                        <!-- 采收批号 -->
                        <view class="d-flex pd2-4-0 f-s-28">
                            <view class="c-#666">入库批号：</view>
                            <view class="c-#333 f-w-5 flex1">{{ item?.storageInfo?.batchCode }}</view>
                        </view>
                        <view class="d-flex pd2-4-0 f-s-28">
                            <view class="c-#666">供应商：</view>
                            <view class="c-#333 f-w-5 flex1">{{ item?.storageInfo?.supplier || '-' }}</view>
                        </view>
                        <view class="d-flex pd2-4-0 f-s-28">
                            <view class="c-#666">存放库房：</view>
                            <view class="c-#333 f-w-5 flex1">
                                {{ getStorageRoomNames(item?.storageInfo?.warehouses) || '-' }}
                            </view>
                        </view>
                    </template>
                    <!-- 采收入库 -->
                    <template v-if="+item?.storageInfo?.instoreType == 3">
                        <!-- 采收批号 -->
                        <view class="d-flex pd2-4-0 f-s-28">
                            <view class="c-#666">采收批号：</view>
                            <view class="c-#333 f-w-5 flex1">{{ item?.storageInfo?.batchCode }}</view>
                        </view>
                        <view class="d-flex pd2-4-0 f-s-28">
                            <view class="c-#666">采收基地：</view>
                            <view class="c-#333 f-w-5 flex1">{{ item?.storageInfo?.baseName || '-' }}</view>
                        </view>
                    </template>
                    <!-- 本次使用量 -->
                    <view class="d-flex pd2-4-0 f-s-28">
                        <view class="c-#666">本次使用量：</view>
                        <view class="c-#333 f-w-5 flex1">{{ item?.quantity || 0 }}{{ item?.unit }}</view>
                    </view>
                </view>
            </view>
            <!-- 产出信息列表 -->
            <view v-else>
                <view v-if="outputList?.length === 0" class="d-flex flex-cln a-c pd-40">
                    <ut-empty color="#ccc" size="28rpx" image="https://ta.zycpzs.cn/oss-file/smart-trace/szyy/images-plt/plant/noEmpty.png">暂无产出信息</ut-empty>
                    <up-button type="primary" @click="handleShowOutputModel">去添加产出信息</up-button>
                </view>
                <view v-else class="d-flex a-c mb-16">
                    <view class="c-#999 f-s-28">产出物：</view>
                    <view class="c-#999 f-s-28">{{ outputList.length }}个</view>
                    <view class="flex1"></view>
                    <up-button v-if="+taskDetail?.processType == 1 && +taskDetail?.processMedType == 1" color="#18BECA" style="width: 210rpx; height: 60rpx; margin-right: 20rpx" @click="goToBatchInstore">单个/批量入库</up-button>
                    <up-button type="primary" style="width: 160rpx; height: 60rpx" @click="handleShowOutputModel">添加产出</up-button>
                </view>
                <up-swipe-action>
                    <up-swipe-action-item v-for="(item, index) in outputList" :key="index" :name="item?.id" :options="swipeOptions" class="mb-16" @click="handleSwipeClick">
                        <ProcessingOutputItem :item="item" :index="index" :selectable="false" @click="handleOutputItemClick" />
                    </up-swipe-action-item>
                </up-swipe-action>
            </view>
        </view>
    </z-paging>

    <!-- 添加/修改产出信息弹框 -->
    <OutputInfo v-if="showOutputModel" v-model:show="showOutputModel" :type="taskDetail?.processType" :processId="taskId" :isEdit="isEditOutput" :editData="editOutputData" @confirm="handleOutputConfirm" />
</template>

<script setup lang="ts">
import { getStorageRoomNames } from '@/utils/common';
import { useClientRequest } from '@/utils/request';
import OutputInfo from './models/outputInfo.vue';
import ProcessingOutputItem from './models/processing-output-item.vue';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { pt_stock_type, pt_standard_type, pt_fresh_instore_type, pt_final_form_type } = toRefs<any>(proxy?.useDict('pt_stock_type', 'pt_standard_type', 'pt_fresh_instore_type', 'pt_final_form_type'));

const paging = ref();
const list = ref<any[]>([]);
const taskId = ref('');
const taskDetail = ref<any>({});
const outputList = ref<any[]>([]);

const activeTab = ref(0);
const tabs = [
    {
        name: '原料信息',
        value: 0,
    },
    {
        name: '产出信息',
        value: 1,
    },
];
// 加载任务详情
const loadTaskDetail = async () => {
    try {
        const res = await useClientRequest.get(`/plt-api/app/processe/getInfoById/${taskId.value}`);
        if (res && res.data) {
            taskDetail.value = res.data;
        }
    } catch (error) {
        console.error('加载任务详情失败:', error);
    }
};

// z-paging 查询原料列表
const query = async (pageNum: number, pageSize: number) => {
    try {
        const res = await useClientRequest.get('/plt-api/app/processInputMaterial/pageList', {
            pageNum,
            pageSize,
            processId: taskId.value,
        });
        if (res) {
            const { rows } = res;
            paging.value.complete(rows);
        }
        getOutputList();
    } catch (error) {
        console.error('加载原料列表失败:', error);
        paging.value.complete([]);
    }
};
const goAssociate = () => {
    uni.$once(`updatesupervise-${taskDetail?.value?.id}`, function (data) {
        paging.value?.reload();
    });

    uni.$u.route({
        type: 'navigateTo',
        url: '/tools/species-info-process/index',
        params: { id: taskDetail?.value?.id, processMedType: taskDetail?.value?.processMedType },
    });
};
// Tab 切换
const onTabChange = (tabItem: any) => {
    activeTab.value = tabItem?.value;
    if (+activeTab.value === 1) {
        // 切换到产出信息，加载产出信息列表
        getOutputList();
    } else {
        // 切换回原料信息，重新加载
        paging.value?.reload();
    }
};

// 获取产出信息列表
const getOutputList = async () => {
    try {
        const res: any = await useClientRequest.get('/plt-api/app/processOutPut/pageList', {
            processId: taskId.value,
        });
        if (res && res.rows) {
            outputList.value = res.rows;
        }
        return res;
    } catch (error) {
        console.error('加载产出信息失败:', error);
        outputList.value = [];
    }
};

// 去修改
const goEdit = () => {
    uni.$u.route({
        type: 'navigateTo',
        url: '/plant/processing/processing-create/index',
        params: { id: taskId.value, edit: 1 },
    });
};

// 跳转到详情页
const gotoDetail = () => {
    uni.$u.route({
        type: 'navigateTo',
        url: '/plant/processing/processing-detail/index',
        params: { id: taskId.value },
    });
};

// 监听修改成功事件，重新加载任务详情
const handleUpdateTaskDetail = () => {
    loadTaskDetail(); // 重新加载任务详情
    if (+activeTab.value === 0) {
        paging.value?.reload(); // 刷新原料列表
    } else {
        getOutputList(); // 刷新产出列表
    }
};

onLoad((options: any) => {
    taskId.value = options?.id || '';
    // 监听修改成功事件
    uni.$on('updateprocesstasklist', handleUpdateTaskDetail);
    if (taskId.value) {
        loadTaskDetail();
    }
    if (options?.output) {
        activeTab.value = 1;
        getOutputList();
    }
});

// 离开页面时卸载事件监听
onUnload(() => {
    uni.$off('updateprocesstasklist');
});
const withdraw = async () => {
    // 删除
    const res = await uni.showModal({
        title: '撤回提示',
        content: '撤回后不可恢复，请谨慎操作！',
        confirmColor: '#F74C30',
    });
    console.log(res);
    if (res.confirm) {
        const delRes = await useClientRequest.get(`/plt-api/app/processInputMaterial/callbackInput/${list.value?.[0]?.id}`);
        if (delRes && delRes.code === 200) {
            uni.showToast({ title: '删除成功', icon: 'none' });
            uni.$emit(`updatesupervise-${taskId.value}`, []);
            paging.value?.reload();
        }
    }
};

// 显示添加产出信息弹框
const showOutputModel = ref(false);
const isEditOutput = ref(false); // 是否编辑模式
const editOutputData = ref<any>({}); // 编辑的数据

const handleShowOutputModel = () => {
    isEditOutput.value = false;
    editOutputData.value = {};
    showOutputModel.value = true;
};

// 处理添加/修改成功
const handleOutputConfirm = async () => {
    const res: any = await getOutputList();
    console.log(res, 'res˝');

    uni.$emit(`updateoutList-${taskId.value}`, res?.rows || []);
};

// 处理产出项点击
const handleOutputItemClick = (item: any) => {
    console.log('点击产出项:', item);
};

// 滑动操作选项
const swipeOptions = reactive([
    {
        text: '修改',
        style: {
            backgroundColor: '#18BECA',
            width: '100rpx',
            fontSize: '28rpx',
        },
    },
    {
        text: '删除',
        style: {
            backgroundColor: '#F74C30',
            width: '100rpx',
            fontSize: '28rpx',
        },
    },
]);

// 处理滑动按钮点击
const handleSwipeClick = async (event: any) => {
    const { name, index } = event;
    const item = outputList.value[index];

    if (index === 0) {
        // 点击修改
        handleEditOutput(item);
    } else if (index === 1) {
        // 点击删除
        handleDeleteOutput(name, item);
    }
};

// 处理修改产出
const handleEditOutput = (item: any) => {
    isEditOutput.value = true;
    editOutputData.value = item;
    showOutputModel.value = true;
};

// 处理删除产出
const handleDeleteOutput = async (outPutId: string | number, item: any) => {
    try {
        const res = await uni.showModal({
            title: '删除提示',
            content: '删除后不可恢复，请谨慎操作！',
            confirmColor: '#F74C30',
        });
        if (!res.confirm) return;

        const delRes = await useClientRequest.get(`/plt-api/app/processOutPut/removeOutPut/${outPutId}`);
        if (delRes && delRes.code === 200) {
            uni.showToast({ title: '删除成功', icon: 'none' });
            const data = await getOutputList();
            uni.$emit(`updateoutList-${taskId.value}`, data?.rows || []);
        }
    } catch (error) {
        console.error('删除失败:', error);
    }
};

// 跳转到单个/批量入库页面
const goToBatchInstore = () => {
    uni.$u.route({
        type: 'navigateTo',
        url: '/plant/processing/processing-depstock/index',
        params: {
            processId: taskId.value,
        },
    });
};
</script>

<style scoped lang="scss">
.li-left-tag {
    padding: 6rpx 16rpx;
    color: #fff;
    border-radius: 16rpx 0 16rpx 0;
    font-size: 20rpx;
    font-weight: 500;
}
.li-item-head {
    margin-left: -24rpx;
    margin-top: -24rpx;
}
</style>
