<template>
    <w-page-common btnText="提交" @submit="handleSubmit" :btnDisabled="btnDisabled">
        <TCard title="基本信息">
            <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', paddingBottom: '10px' }" title="难修原因">
            <template #right>
                <u-icon
                    :name="!toggleReason ? 'arrow-down' : 'arrow-up'"
                    size="32rpx"
                    color="#7C7E82"
                    class="mr-3"
                    @tap="toggleReason = !toggleReason"
                />
            </template>
            <view class="difficult-reason" v-show="!toggleReason">
                <view class="title">维修了什么?</view>
                <view class="item" v-for="(item, index) in reasonField.repaired" :key="item">
                    <view class="serial-number">{{ index + 1 }}</view>
                    <u-input placeholder="请输入" v-model="formData[item]"></u-input>
                </view>
                <view class="title">现在遇到了什么问题?</view>
                <view class="item" v-for="(item, index) in reasonField.question" :key="item">
                    <view class="serial-number">{{ index + 1 }}</view>
                    <u-input placeholder="请输入" v-model="formData[item]"></u-input>
                </view>
            </view>
        </TCard>
        <TCard :cardStyle="{ marginTop: '15px' }">
            <view class="c-input-field-item px-3">
                <text class="label">是否已领用配件</text>
                <u-switch
                    v-model="formData.receiver"
                    :activeValue="YesOrNoEnum.YES"
                    :inactiveValue="YesOrNoEnum.NO"
                    disabled
                ></u-switch>
            </view>
            <template v-if="formData.receiver == YesOrNoEnum.YES">
                <view class="c-input-field-item px-3 border-t border-border">
                    <text class="label">是否已更换配件</text>
                    <u-switch
                        v-model="formData.changeAccessory"
                        :activeValue="YesOrNoEnum.YES"
                        :inactiveValue="YesOrNoEnum.NO"
                        :disabled="detail.receiveOrNot != YesOrNoEnum.YES"
                    ></u-switch>
                </view>
                <replaceParts
                    ref="partsListRef"
                    :sparepartsList="detail.sparePartList"
                    v-model="formData.sparePartUseParams"
                    @changeItem="changeItem"
                    :initialSparesList="initialSparesList"
                />
                <view
                    class="text-primary flex items-center justify-center py-2"
                    v-if="formData.changeAccessory == YesOrNoEnum.YES"
                >
                    <u-icon name="plus" color="#0e66fb" :size="15"></u-icon>
                    <text class="ml-1" @click="addReplaceItem">添加明细</text>
                </view>
            </template>
        </TCard>
        <TCard
            title="未使用配件清单"
            :cardStyle="{ paddingBottom: '10px', marginTop: '15px' }"
            v-if="detail?.sparePartList?.length > 0 && detail.receiveOrNot == YesOrNoEnum.YES"
        >
            <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>
        </TCard>
        <TCard :cardStyle="{ padding: '0 10px 10px', marginTop: '15px' }">
            <view class="c-form-item-wrapper !p-0">
                <view class="whole-row-label required">图片</view>
                <u-upload
                    :fileList="fileList['repairImage']"
                    name="repairImage"
                    :maxCount="9"
                    @beforeRead="beforeRead"
                    @afterRead="afterRead"
                    @delete="deletePic"
                    :width="80"
                    :height="80"
                    multiple
                ></u-upload>
            </view>
        </TCard>
    </w-page-common>
</template>

<script setup lang="ts">
import { ref, unref } from 'vue'
import { apiRepairDetail, apiReturnStashApply } from '@/api/repair'
import { onLoad } from '@dcloudio/uni-app'
import { toast } from '@/utils/util'
import { YesOrNoEnum } from '@/enums/businessEnums'
import replaceParts from './components/replace-parts.vue'
import { useUploadValidate } from '@/hooks/useUploadValidate'
import { useModulePower } from '@/hooks/useLockFn'

const detail = ref<any>({})
const moduleCode = ref()
const initialSparesList = ref<any>([])
const toggleReason = ref(false)

const formData = ref<any>({
    // reasonForWithdrawal: '',
    receiver: 0,
    changeAccessory: YesOrNoEnum.NO,
    sparePartUseParams: []
})
const reasonField = {
    repaired: ['whatWasRepairedOne', 'whatWasRepairedTwo', 'whatWasRepairedThree'],
    question: ['questionOne', 'questionTwo', 'questionThree']
}
const partsListRef = ref()
const { parseModulePower } = useModulePower()
const { fileList, beforeRead, afterRead, deletePic, handleUploadFile, btnDisabled } =
    useUploadValidate()

const addReplaceItem = () => {
    partsListRef.value.addItem()
}
// 子组件选择配件，删除配件，改变数量触发的方法
// 处理未处理配件清单的数据
const changeItem = (item: any, type: string) => {
    const target = initialSparesList.value.find(spare => spare.sparePartsId == item.sparePartsId)
    const items = formData.value.sparePartUseParams.filter(i => {
        return i.sparePartsId == item.sparePartsId && item.sparePartsId
    })
    const total = items.reduce((prev, cur) => {
        return prev + Number(cur.count)
    }, 0)
    const leave = Math.max(target?.count - total, 0)

    if (isNaN(leave)) return
    if (leave == 0)
        detail.value.sparePartList = detail.value.sparePartList.filter(
            spare => spare.sparePartsId != target.sparePartsId
        )
    else {
        const obj = detail.value.sparePartList.find(
            spare => spare.sparePartsId == item.sparePartsId
        )

        if (!obj) {
            detail.value.sparePartList.push({
                sparePartsName: item.sparePartsName,
                specificationsModel: item.specificationsModel,
                count: leave,
                value: item.sparePartsId,
                sparePartsId: item.sparePartsId
            })
        } else if (type == 'del') {
            obj.count = leave + 1
        } else {
            obj.count = leave
        }
    }
}

const handleSubmit = () => {
    const form = unref(formData)
    for (let i in reasonField) {
        for (let j = 0; j < reasonField[i].length; j++) {
            if (!formData.value[reasonField[i][j]]) {
                return toast('请输入完整的难修原因')
            }
        }
    }

    if (form.changeAccessory == YesOrNoEnum.YES && form.sparePartUseParams.length === 0)
        return toast('请添加替换配件明细')
    const empty = form.sparePartUseParams?.find(item => {
        return !item.repairMotherboard || !item.materialPositionNumber || !item.sparePartsId
    })
    if (empty) return toast('请填写完整的配件信息')
    if (unref(fileList)?.repairImage?.length === 0) return toast('请上传图片')
    handleUploadFile(async files => {
        const data = {
            id: detail.value.id,
            ...unref(formData),
            sparePartUseParams: unref(formData).sparePartUseParams.map(i => {
                const { repairMotherboard, materialPositionNumber, count, sparePartsId } = i
                return {
                    repairMotherboard,
                    materialPositionNumber,
                    sparePartsId,
                    useNumber: count
                }
            }),
            withdrawalImg: unref(files)?.repairImage?.toString()
        }

        await apiReturnStashApply(data).finally(() => {
            btnDisabled.value = false
        })
        toast('操作成功')

        uni.reLaunch({
            url: '/pages/repair/task/index'
        })
    })
}

const getDetail = async () => {
    try {
        uni.showLoading({
            title: '加载中...'
        })
        const params = {
            moduleCode: unref(moduleCode)
        }
        const res: RepairItem = await apiRepairDetail(params)
        uni.hideLoading()
        if (res.returning == YesOrNoEnum.YES) {
            uni.$u.toast('该维修单已申请退仓')
            btnDisabled.value = true
        }
        if (res.scrapOrNot == YesOrNoEnum.YES) {
            uni.$u.toast('该维修单已申请报废')
            btnDisabled.value = true
        } else if (res.repairNextStep < 13 && res.orderStatus != 6) {
            formData.value.receiver = res.sparePartList.length > 0 ? 0 : 1
            detail.value = res
            initialSparesList.value = uni.$u.deepClone(res.sparePartList)
        } else {
            uni.$u.toast('该维修单当前状态不支持退仓')
            btnDisabled.value = true
        }
    } catch (error) {}
}
onLoad(options => {
    moduleCode.value = options.code as string
    getDetail()
})
</script>
<style scoped lang="scss">
.spare-item {
    background-color: $gray-1;
    @apply rounded p-3 mb-2;
}
</style>
