<!--
 * @Author: micky
 * @Date: 2024-08-13 19:19:02
 * @LastEditors: micky
 * @LastEditTime: 2024-11-22 17:02:08
 * @FilePath: \chargingpile-uniapp\src\bundle\pages\overhaul\offer-price.vue
-->
<template>
    <w-page-common btnText="" :btnDisabled="btnDisabled">
        <TCard title="" :cardStyle="{ padding: '22rpx 0' }">
            <view class="c-form-item-wrapper">
                <view class="item">
                    <view>工单编号</view>
                    <view>{{ detail.orderNo }}</view>
                </view>
                <view class="item">
                    <view>报修人</view>
                    <view>{{ detail.creatorName }}</view>
                </view>
                <view class="item">
                    <view>报修时间</view>
                    <view>{{ detail.createTime }}</view>
                </view>
                <w-client-device-info :formData="detail" />
            </view>
        </TCard>
        <TCard :cardStyle="{ marginTop: '15px' }">
            <view class="c-input-field-item with-border px-3">
                <view class="label">选择仓库</view>
                <w-dict-select
                    v-model="formData.warehouseType"
                    :options="optionsMap.stashTypeOptions"
                    @change="formData.sparePartParams = []"
                ></w-dict-select>
            </view>
            <view class="c-input-field-item with-border px-3">
                <view class="label required">选择配件</view>
                <view class="flex items-center" @click="choose">
                    <u-icon name="plus-circle" color="#7C7E82" size="48rpx"></u-icon>
                </view>
            </view>
            <block v-if="formData.sparePartParams.length > 0">
                <view
                    v-for="(item, index) in formData.sparePartParams"
                    :key="index"
                    class="py-3 px-3"
                >
                    <view class="flex justify-between">
                        <text>{{ item.sparePartsName }}</text>
                        <view class="flex items-center">
                            <text class="text-error mr-2">￥{{ item.unitPrice }}</text>
                            <u-icon
                                name="trash"
                                :size="17"
                                color="#0E66FB"
                                @click="removeSpareParts(index)"
                            ></u-icon>
                        </view>
                    </view>
                    <view class="flex justify-between mt-2 items-center">
                        <text class="text-sm 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', paddingTop: '12px' }">
            <view class="c-form-item-wrapper">
                <TTextareaField
                    label="故障描述"
                    v-model="formData.faultDescription"
                    placeholder="请输入故障描述"
                    :remarkStyle="{ padding: 0 }"
                    :required="true"
                ></TTextareaField>

                <view class="whole-row-label required">故障图片</view>
                <u-upload
                    class="upload-wrapper"
                    :fileList="fileList['fault']"
                    name="fault"
                    :maxCount="9"
                    multiple
                    @beforeRead="beforeRead"
                    @afterRead="afterRead"
                    @delete="deletePic"
                    :width="80"
                    :height="80"
                ></u-upload>
            </view>
        </TCard>
        <template #btn>
            <view class="page-common-footer px-3">
                <view class="mr-3">
                    总额：
                    <text class="text-error">￥{{ totalPrice }}</text>
                </view>
                <u-button
                    text="发送报价"
                    color="#2759FF"
                    shape="circle"
                    @click="handleSubmit"
                    class="flex-1"
                    size="middle"
                ></u-button>
            </view>
        </template>
    </w-page-common>
</template>

<script setup lang="ts">
import { ref, unref, computed } from 'vue'
import { useUploadValidate } from '@/hooks/useUploadValidate'
import { optionsMap } from '@/config/options'
import { onLoad } from '@dcloudio/uni-app'
import { toast, navigateTo, uploadFile } from '@/utils/util'
import { apiOverhaulDetail } from '@/api/overhaul'
import { apiOfferPrice } from '@/api/overhaul'

// 提交接口的表单参数
const formData = ref<any>({
    warehouseType: optionsMap.stashTypeOptions[0].value || 0,
    faultDescription: '',
    sparePartParams: [],
    faultImg: ''
})
// 工单详情
const detail = ref<any>({})
const orderId = ref('')
const imageList = ref<string[]>([])

const { fileList, beforeRead, afterRead, deletePic, handleUploadFile, btnDisabled } =
    useUploadValidate()
const totalPrice = computed(() => {
    if (formData.value.sparePartParams.length > 0) {
        return formData.value.sparePartParams.reduce((pre, cur) => {
            return pre + cur.count * cur.unitPrice
        }, 0)
    }
    return 0
})
// 选择配件
const choose = () => {
    const selectedItem = encodeURIComponent(JSON.stringify(formData.value.sparePartParams))
    uni.navigateTo({
        url: `/bundle/pages/spareParts/spareParts-list?selectedItem=${selectedItem}&clientId=${
            unref(detail).clientId
        }&warehouseType=${unref(formData).warehouseType}&orderType=0`
    })
}
const removeSpareParts = (ind: number) => {
    formData.value.sparePartParams.splice(ind, 1)
}

const handleSubmit = () => {
    const form = unref(formData)
    if (form.sparePartParams.length === 0) return toast('请选择配件')
    else if (!form.faultDescription) return toast('请输入故障描述')
    else if (unref(fileList)?.fault?.length === 0) {
        return toast('请选择故障图片')
    }
    handleUploadFile(async files => {
        const data = {
            id: unref(orderId),
            ...unref(formData),
            sparePartParams: unref(formData).sparePartParams.map((item: MaterialItem) => {
                return {
                    id: item.id,
                    count: item.count
                }
            }),
            faultImg: unref(files)?.fault?.toString()
        }
        await apiOfferPrice(data)
        toast('操作成功')
        btnDisabled.value = false
        uni.navigateBack({ delta: 1 })
    })
}

const getDetail = async () => {
    const res = await apiOverhaulDetail({ id: unref(orderId) })
    detail.value = res
    // 回显上次报价的数据
    formData.value.faultDescription = res.faultDescription
    formData.value.faultImg = res.faultImg
    formData.value.warehouseType = res.warehouseType || 0
    formData.value.sparePartParams =
        res.sparePartList.map(item => {
            return {
                ...item,
                id: item.sparePartsId,
                count: item.count
            }
        }) || []
    if (res.faultImg) {
        fileList.value['fault'] = res.faultImg?.split(',')?.map(img => {
            return {
                url: img
            }
        })
    }
}

onLoad(options => {
    uni.$on('sparepartsList', function (data) {
        formData.value.sparePartParams = data
    })
    orderId.value = options.id as string
    getDetail()
})
</script>
<style scoped lang="scss">
// .upload-wrapper {
//     :deep(.u-upload__wrap) {
//         display: grid;
//         grid-template-columns: repeat(4, 1fr);
//         gap: 20rpx;
//     }
// }
</style>
