<template>
    <w-page-common
        btnText="提交"
        @submit="handleSubmit"
        :needPadding="false"
        :btnDisabled="btnDisabled"
    >
        <view class="bg-[#fffbe8] text-error px-3 py-1 text-base">
            若维修过程中发现物料不足，可点击下方的继续添加按钮
        </view>
        <view class="mx-3">
            <TCard title="基本信息" :cardStyle="{ marginTop: '15px' }">
                <view class="c-form-item-wrapper pb-3">
                    <view class="item black">
                        <view>客户名称</view>
                        <view>
                            {{ detail?.clientName }}
                        </view>
                    </view>
                    <view class="item black">
                        <view>模块型号</view>
                        <view>
                            {{ detail?.moduleNumber }}
                        </view>
                    </view>
                    <view class="item black">
                        <view>模块代码</view>
                        <view>
                            {{ detail?.moduleCode }}
                        </view>
                    </view>
                    <view class="item black">
                        <view>功率</view>
                        <view>{{ parseModulePower(detail.modulePower) }}</view>
                    </view>
                </view>
            </TCard>
            <TCard :cardStyle="{ marginTop: '15px' }">
                <w-spareParts-info
                    :sparePartList="detail?.orderPartCodeList"
                    titleClass="text-xl text-[#000] font-bold"
                >
                    <template #right>
                        <text class="text-gray2">
                            共{{ detail?.orderPartCodeList?.length || 0 }}项
                        </text>
                    </template>
                </w-spareParts-info>
            </TCard>
            <TCard
                title="维修使用配件清单"
                :cardStyle="{ paddingBottom: '10px', marginTop: '15px' }"
            >
                <template #right>
                    <view
                        class="text-primary pr-3"
                        @click="choose"
                        :style="{ opacity: btnDisabled ? 0.5 : 1 }"
                    >
                        继续添加
                    </view>
                </template>
                <view v-for="(item, index) in detail.sparePartList" :key="index" class="mt-3 px-3">
                    <view class="spare-item">
                        <view class="flex justify-between mb-1">
                            <text class="text-lightblack">{{ item.sparePartsName }}</text>
                            <text class="text-error">
                                <text class="mr-1">*</text>
                                <text>{{ item.count }}</text>
                            </text>
                        </view>
                        <view class="text-gray2">型号规格：{{ item.specificationsModel }}</view>
                    </view>
                </view>
                <block v-if="formData.sparePartParams.length > 0">
                    <view
                        v-for="(item, index) in formData.sparePartParams"
                        :key="index"
                        class="spare-item mx-3"
                    >
                        <view class="flex justify-between mb-1">
                            <text class="text-lightblack">{{ item.sparePartsName }}</text>
                            <text class="text-primary text-base" @click="removeSpareParts(index)">
                                移除
                            </text>
                        </view>
                        <view class="flex justify-between items-center">
                            <text class="text-gray2">型号规格：{{ item.specificationsModel }}</text>
                            <u-number-box
                                :min="1"
                                :max="item.quantity"
                                integer
                                bgColor="transparent"
                                v-model="item.count"
                            ></u-number-box>
                        </view>
                    </view>
                </block>
            </TCard>
            <TCard :cardStyle="{ marginTop: '15px' }">
                <TTextareaField
                    v-model="formData.remark"
                    placeholder="请输入备注信息，最多255字"
                    :disabled="btnDisabled"
                ></TTextareaField>
            </TCard>
        </view>
    </w-page-common>
</template>

<script setup lang="ts">
import { ref, reactive, unref, onMounted } from 'vue'
import { apiRepairDetail, apiMaterial } from '@/api/repair'
import { onLoad } from '@dcloudio/uni-app'
import { toast, navigateTo } from '@/utils/util'
import { RepairStepEnum } from '@/enums/businessEnums'
import { useModulePower } from '@/hooks/useLockFn'

const detail = ref<any>({})
const moduleCode = ref()

interface Form {
    sparePartParams: MaterialItem[]
    remark: string
}

const formData = ref<Form>({
    remark: '',
    sparePartParams: []
})
const btnDisabled = ref(false)
const { parseModulePower } = useModulePower()

// 选择配件
const choose = () => {
    if (btnDisabled.value) return
    const selectedItem = encodeURIComponent(JSON.stringify(formData.value.sparePartParams))
    uni.navigateTo({
        url: `/bundle/pages/spareParts/spareParts-list?selectedItem=${selectedItem}&clientId=${
            unref(detail).clientId
        }&warehouseType=1&orderType=1`
    })
}

const removeSpareParts = (ind: number) => {
    formData.value.sparePartParams.splice(ind, 1)
}

const handleSubmit = async () => {
    const form = unref(formData)
    if (form.sparePartParams.length === 0) return toast('请添加至少一个配件')
    const params: any = {
        id: unref(detail).id,
        repairOrderStepRemark: form.remark
    }
    params.sparePartParams = form.sparePartParams.map((item: MaterialItem) => {
        return {
            id: item?.sparePartsId ?? item.id,
            count: item?.count // 出库数量
        }
    })
    await apiMaterial(params)
    toast('申请成功，等待管理员审核')

    uni.navigateBack({ delta: 1 })
}

const getDetail = async () => {
    try {
        uni.showLoading({
            title: '加载中...'
        })
        const params = {
            moduleCode: unref(moduleCode)
        }
        const res: RepairItem = await apiRepairDetail(params)
        // 上传维修前图片到填写维修信息前可以发起领料申请
        if (
            res.repairNextStep > RepairStepEnum.SPAREPARTS &&
            res.repairNextStep < RepairStepEnum.FILLIN
        ) {
            detail.value = res
        } else {
            btnDisabled.value = true
            return toast('该维修单当前状态不支持补料')
        }
        console.log('detail', detail)

        uni.hideLoading()
    } catch (error) {}
}
onLoad(options => {
    moduleCode.value = options.code as string
    getDetail()

    uni.$on('sparepartsList', function (data) {
        formData.value.sparePartParams = data
    })
})
</script>
<style scoped lang="scss">
.spare-item {
    background-color: $gray-1;
    @apply rounded p-3 mb-2;
}
</style>
