<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">
                <!-- 任务类型标签 -->
                <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 mx-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="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">
                <ut-tabs v-model="activeTab" :tabs="tabs" @change="onTabChange"></ut-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-for="(item, index) in outputList" :key="index" class="bg-#fff b-radius pd-24 mb-16">
                    <!-- 序号 -->
                    <view class="d-flex a-c mb-12">
                        <view class="bg-#2289E0 c-#fff f-s-20 f-w-5 pd-10 pt-4 pb-4 radius-8 mr-10">{{ String(index + 1).padStart(2, '0') }}</view>
                        <view class="f-s-32 f-w-5 c-#333">{{ item?.specnLevel || '统货' }}</view>
                    </view>
                    <!-- 规格 -->
                    <view class="d-flex mb-12 f-s-28">
                        <view class="c-#666">规格：</view>
                        <view class="c-#333 f-w-5 flex1">{{ item?.specn || '-' }}</view>
                    </view>
                    <!-- 产能 -->
                    <view class="d-flex mb-12 f-s-28">
                        <view class="c-#666">产能：</view>
                        <view class="c-#333 f-w-5 flex1">{{ item?.capacity || 0 }}{{ item?.unit }}</view>
                    </view>
                    <!-- 状态 -->
                    <view class="d-flex a-c j-end mt-16">
                        <view v-if="item?.examinReport?.length > 0" class="c-#37A954 f-s-24 bg-#EDF7F0 pd-8 radius-8">已检</view>
                        <view v-else class="c-#F74C30 f-s-24 bg-#FEF3E8 pd-8 radius-8">未检</view>
                    </view>
                </view>
            </view>
        </view>
    </z-paging>

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

<script setup lang="ts">
import { getStorageRoomNames } from '@/utils/common';
import { useClientRequest } from '@/utils/request';
import OutputInfo from './models/outputInfo.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 = [
    {
        label: '原料信息',
        value: '0',
    },
    {
        label: '产出信息',
        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);
        }
    } 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 = () => {
    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;
        }
    } 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 },
    });
};

onLoad((options: any) => {
    taskId.value = options?.id || '';
    if (taskId.value) {
        loadTaskDetail();
    }
});
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/${taskDetail.value?.id}`);
        if (delRes && delRes.code === 200) {
            uni.showToast({ title: '删除成功', icon: 'none' });
            paging.value?.reload();
        }
    }
};

// 显示添加产出信息弹框
const showOutputModel = ref(false);
const handleShowOutputModel = () => {
    showOutputModel.value = true;
};

// 处理添加成功
const handleOutputConfirm = () => {
    getOutputList();
};
</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>
