<!--
 * @Author: micky
 * @Date: 2024-09-08 19:23:35
 * @LastEditors: micky
 * @LastEditTime: 2024-10-25 18:32:42
 * @FilePath: \chargingpile-uniapp\src\bundle\pages\repair\step\step-pfc.vue
-->
<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="px-[24rpx] pt-[20rpx]">
            <TCard>
                <view class="c-input-field-item with-border px-[32rpx] !h-[unset]">
                    <view>
                        <view class="mt-1">条形码</view>
                        <view class="text-sm text-gray2 my-1">扫描模块上的条形码</view>
                    </view>
                    <u-icon name="scan" :size="28" @click="scanAndCheck(7)"></u-icon>
                </view>
                <TInputField
                    v-model="moduleCode"
                    label="模块代码"
                    placeholder="请扫码"
                    :readonly="true"
                    :required="false"
                />
                <TInputField
                    v-model="detailForm.moduleNumber"
                    label="模块型号"
                    placeholder="请扫码"
                    :readonly="true"
                    :required="false"
                />
                <TInputField
                    v-model="detailForm.modulePower"
                    label="功率"
                    :readonly="true"
                    :required="false"
                    placeholder="请扫码"
                />
            </TCard>
            <TCard :cardStyle="{ marginTop: '15px' }">
                <w-spareParts-info
                    :sparePartList="sparePartList"
                    showIcon
                    iconName="icon-selected"
                    iconColor="#0e66fb"
                >
                    <template #right>
                        <view
                            class="text-primary text-base flex items-center"
                            @click="scanAndCheck(8)"
                        >
                            <view class="ml-1">扫码核实</view>
                        </view>
                    </template>
                </w-spareParts-info>
            </TCard>
            <TCard :cardStyle="{ marginTop: '15px' }">
                <TFeedBack v-model:remark="remark" v-model:imageList="fileList" />
            </TCard>
        </view>
    </w-page-common>
</template>

<script setup lang="ts">
import { ref, unref, watch } from 'vue'
import { toast } from '@/utils/util'
import { DCPFC } from '@/enums/cacheEnums'
import cache from '@/utils/cache'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import { apiCommonStep, apiRepairDetail } from '@/api/repair'
import { useUploadValidate } from '@/hooks/useUploadValidate'
import { useDictData } from '@/hooks/useDictOptions'
import { YesOrNoEnum } from '@/enums/businessEnums'

interface SparePartsItem {
    id: number
    partCode: string
    selected: boolean
}
const pages = getCurrentPages() // 当前页面
const detailForm = ref<Partial<RepairItem>>({})
const { dictData }: { dictData: any } = useDictData(['modulePower'])
const moduleCode = ref('')
const orderId = ref('')
const sparePartList = ref<SparePartsItem[]>([])
let code: any = ''
let type: any = ''

const { handleUploadFile, btnDisabled } = useUploadValidate()

// 扫描配件
const scanAndCheck = (type: number) => {
    setCache()
    const exist = pages.find(item => item.route == 'bundle/pages/repair/step/step-pfc')
    const isupdate = isUpdate.value == YesOrNoEnum.NO + '' ? 'true' : false
    if (exist) {
        uni.redirectTo({
            url: `/bundle/pages/scan/scan?type=${type}&id=${
                unref(detailForm).id
            }&isUpdate=${isupdate}`
        })
    } else {
        uni.navigateTo({
            url: `/bundle/pages/scan/scan?type=${type}&id=${
                unref(detailForm).id
            }&isUpdate=${isupdate}`
        })
    }
}

const setCache = () => {
    cache.set(DCPFC, {
        list: unref(sparePartList),
        moduleCode: unref(moduleCode)
    })
}

const remark = ref('')
const isUpdate = ref('')
const fileList: any = ref({
    repairImage: []
})

const handleSubmit = () => {
    if (!unref(moduleCode)) return toast('请扫描模块代码核实')
    if (unref(sparePartList).some(item => item.selected == false))
        return toast('请扫描核实全部部件')
    if (unref(fileList)?.repairImage?.length === 0) return toast('请上传图片')
    handleUploadFile(async (files: Record<string, string>) => {
        const params = {
            id: unref(orderId),
            repairOrderStepRemark: unref(remark),
            repairOrderStepImg: unref(files).repairImage?.toString(),
            repairStep:
                isUpdate.value == YesOrNoEnum.NO + '' ? 9 : unref(detailForm).repairNextStep,
            changeStepOrNot: isUpdate.value
        }
        await apiCommonStep(params).finally(() => {
            btnDisabled.value = false
        })
        toast('操作成功')
        setTimeout(() => {
            uni.navigateBack()
            // appStore.clearSelectedList()
        }, 300)
    }, unref(fileList))
}
// const appStore = useAppStore()
// const { selectedList } = storeToRefs(appStore)

const getDetail = async () => {
    const res = await apiRepairDetail({ id: unref(orderId) })
    res.modulePower =
        dictData.modulePower.find((item: DictItem) => item.value == res.modulePower)?.name ?? '--'
    detailForm.value = res
    sparePartList.value = res.orderPartCodeList.map((item: DictItem) => {
        return {
            ...item,
            selected: false
        }
    })
    const obj = res.repairOrderStepDataList.find(item => item.repairStep == 9)
    if (obj?.img) {
        fileList.value['repairImage'] = obj.img?.split(',')?.map(img => {
            return {
                url: img
            }
        })
    }

    const cacheData = cache.get(DCPFC) || {}
    if (cacheData?.list?.length > 0) sparePartList.value = cacheData.list
    cacheData.moduleCode && (moduleCode.value = cacheData.moduleCode)
    // 核实模块码
    if (type == 7) {
        if (code == detailForm.value.moduleCode) moduleCode.value = code
        else
            toast(
                `扫描的模块代码和当前工单模块代码【${detailForm.value.moduleCode}】不匹配，请重新扫码`
            )
    } else {
        //核实部件码
        const ind = sparePartList.value.findIndex(item => item.partCode == code)
        if (ind == -1 && code) toast(`当前工单没有关联【${code}】部件，请重新扫码`)
        else if (ind >= 0) sparePartList.value[ind].selected = true
        console.log('cacheData', cacheData)
    }
}

onLoad(options => {
    orderId.value = options.id as string
    code = options.code
    type = options.type

    if (options.isUpdate == 'true') isUpdate.value = YesOrNoEnum.NO
    else isUpdate.value = YesOrNoEnum.YES
    getDetail()
})
</script>
<style scoped lang="scss"></style>
