<!--
 * @Author: micky
 * @Date: 2024-08-15 10:58:26
 * @LastEditors: micky
 * @LastEditTime: 2024-10-19 16:25:21
 * @FilePath: \chargingpile-uniapp\src\bundle\pages\charge\add-repair-order.vue
-->
<template>
    <w-page-common btnText="确认创建工单" @submit="handleSubmit">
        <view class="flex flex-col h-full">
            <TCard>
                <TSelectField
                    label="客户名称"
                    placeholder="请选择客户"
                    @on-click="handleToggle"
                    v-model="showInfo.clientName"
                    inputAlign="right"
                />
            </TCard>
            <TCard :cardStyle="{ marginTop: '15px' }" class="flex-1 overflow-auto">
                <view class="c-input-field-item border-b border-[#f1f1f1] px-[32rpx]">
                    <view>扫描模块码</view>
                    <u-icon name="scan" :size="28" @click="toScan"></u-icon>
                </view>
                <module-item ref="moduleItemRef" v-model="formData.repairOrderList"></module-item>
            </TCard>
        </view>

        <ClientPopup v-model="show" @handle-selected-value="handleSelectedValue" />
        <ConfirmModal ref="confirmModalRef" />
    </w-page-common>
</template>

<script setup lang="ts">
import { nextTick, ref, shallowRef, unref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { toast } from '@/utils/util'
import { apiCreateOrder } from '@/api/repair'
import { useToggle } from '@/hooks/useLockFn'
import ClientPopup from './components/client-popup.vue'
import ModuleItem from './components/module-item.vue'
import ConfirmModal from './components/confirm-modal.vue'

const confirmModalRef = ref()
const showInfo = shallowRef({
    clientName: ''
})
const formData = ref<any>({
    clientId: '',
    repairOrderList: []
})
const moduleItemRef = ref()
const { show, handleToggle } = useToggle()
const handleSubmit = async () => {
    const form = unref(formData)
    if (!form.clientId) return toast('请选择客户')
    if (form.repairOrderList.length === 0) return toast('请扫描录入模块信息')

    const data = await apiCreateOrder({
        ...unref(formData)
    })

    if (data) {
        // 初步确定是否有返修模块
        confirmModalRef.value.openModal(data)
    } else {
        toast('创建成功')
        setTimeout(() => {
            uni.navigateBack()
        }, 300)
    }
}

// 选中客户
const handleSelectedValue = client => {
    showInfo.value.clientName = client.clientName
    formData.value.clientId = client.id
}

const toScan = () => {
    const params = encodeURIComponent(JSON.stringify(formData.value.repairOrderList))
    uni.navigateTo({
        url: `/bundle/pages/charge/scan-module?params=${params}`
    })
}

onLoad(() => {
    uni.$on('moduleList', async function (data) {
        await nextTick()
        moduleItemRef.value.setItem(data)
    })
})
</script>
<style scoped lang="scss">
.return-address {
    height: auto !important;
    padding: 24rpx 32rpx;
}
</style>
