<template>
    <w-page-common btnText="提交" @submit="handleSubmit" :btnDisabled="btnDisabled">
        <!-- 手动填 -->
        <TCard v-if="!deviceCode">
            <TInputField
                v-model="showInfo.equipmentNo"
                label="设备编号"
                placeholder="请输入设备编号"
                @blur="codeChange"
            />
            <TInputField
                v-model="showInfo.equipmentName"
                label="设备名称"
                placeholder="请输入设备编号"
                :readonly="true"
            />
            <TInputField
                v-model="showInfo.model"
                label="设备型号"
                placeholder="请输入设备编号"
                :readonly="true"
            />
            <TInputField
                v-model="showInfo.manufacturers"
                label="设备厂家"
                placeholder="请输入设备编号"
                :readonly="true"
            />
            <TInputField
                v-model="showInfo.specification"
                label="设备规格"
                placeholder="请输入设备编号"
                :readonly="true"
            />
            <TInputField
                v-model="showInfo.detailedAddress"
                label="详细地址"
                placeholder="请输入设备编号"
                :readonly="true"
            />
        </TCard>
        <!-- 扫码带回来的设备编号，根据编号查出其他信息 -->
        <TCard v-else title="基本信息">
            <view
                v-for="(item, index) in fieldList"
                :key="index"
                class="flex pl-[14px] leading-[30px]"
            >
                <view class="w-[100px] mr-2">{{ item.name }}</view>
                <view class="flex-1">{{ showInfo[item.prop] }}</view>
            </view>
        </TCard>
        <TCard :cardStyle="{ marginTop: '15px' }">
            <TPicker
                label="故障类型"
                placeholder="请选择故障类型"
                :columns="typeColumns"
                v-model="formData.faultId"
                keyName="name"
                :disabled="btnDisabled"
            />
            <TTextareaField
                label="故障描述"
                v-model="formData.faultDescription"
                placeholder="请输入故障描述"
                :required="true"
                :disabled="btnDisabled"
            ></TTextareaField>
            <view class="px-[32rpx] flex flex-col gap-[20rpx] pb-[12rpx]">
                <view class="picture">故障图片</view>
                <u-upload
                    class="upload-wrapper"
                    :fileList="fileList['picture']"
                    name="picture"
                    :maxCount="9"
                    multiple
                    @beforeRead="beforeRead"
                    @afterRead="afterRead"
                    @delete="deletePic"
                    :width="80"
                    :height="80"
                    :disabled="btnDisabled"
                ></u-upload>
            </view>
        </TCard>
        <TCard :cardStyle="{ marginTop: '15px' }">
            <TTextareaField
                label="备注"
                v-model="formData.remark"
                placeholder="请输入备注信息，选填"
                :disabled="btnDisabled"
            ></TTextareaField>
        </TCard>
    </w-page-common>
</template>

<script setup lang="ts">
import { onMounted, ref, unref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { toast } from '@/utils/util'
import { apiRepair, apiGetDeviceInfoByCode } from '@/api/client'
import { apiFault } from '@/api/app'
import { FaultTypeEnum } from '@/enums/businessEnums'
import { useUserStore } from '@/stores/user'
import { useUploadValidate } from '@/hooks/useUploadValidate'
import { useDictData, getDictName } from '@/hooks/useDictOptions'

const userStore = useUserStore()
const { userInfo } = userStore
const { fileList, beforeRead, afterRead, deletePic } = useUploadValidate()

const formData = ref<any>({
    faultId: '',
    faultDescription: '',
    remark: '',
    equipmentId: ''
})
const showInfo = ref<any>({
    equipmentNo: '',
    equipmentName: '',
    detailedAddress: '',
    manufacturers: '',
    specification: '',
    model: ''
})
const deviceCode = ref('')
const btnDisabled = ref(false)
const typeColumns = ref<any>([])
const fieldList = [
    {
        name: '设备名称',
        prop: 'equipmentName'
    },
    {
        name: '设备编号',
        prop: 'equipmentNo'
    },
    {
        name: '设备型号',
        prop: 'model'
    },
    {
        name: '设备厂家',
        prop: 'manufacturers'
    },
    {
        name: '设备规格',
        prop: 'specification'
    },
    {
        name: '设备地址',
        prop: 'detailedAddress'
    }
]
const { dictData }: { dictData: any } = useDictData(['deviceStatus'])

const handleSubmit = async () => {
    if (formData.value.clientId && formData.value.clientId != userInfo.clientId)
        return toast('不能报修其他客户的设备！')
    const keys = Object.keys(unref(formData))
    keys.map(key => {
        if (!unref(formData)[key] && key != 'remark') {
            toast('请输入必填项！')
            throw new Error('请输入必填项')
        }
    })
    if (fileList.value['picture'].length === 0) return toast('请上传故障图片')
    if (!showInfo.value.equipmentName) toast('系统不存在该设备编号，请检查填写是否正确')
    Object.assign(formData.value, {
        createImg: fileList.value['picture'].map(item => item.url).join(',')
    })
    await apiRepair(unref(formData))
    toast('报修成功')
    setTimeout(() => {
        uni.navigateTo({
            url: '/pages/client/workOrder/index'
        })
    }, 300)
}
const getTypeList = async () => {
    const res = await apiFault({
        faultType: FaultTypeEnum.PROBLEM
    })
    typeColumns.value = [res.lists]
}
// 输入设备编码改变，请求设备信息
const codeChange = () => {
    if (showInfo.value.equipmentNo) getInfoByCode()
}
const getInfoByCode = async () => {
    const res = await apiGetDeviceInfoByCode({ number: unref(showInfo).equipmentNo })
    if (res.clientId != userInfo.clientId) {
        btnDisabled.value = true
        toast('不能报修其他客户的设备！')
    } else if (res.deviceStatus != 1) {
        btnDisabled.value = true
        toast(`该设备状态为【${getDictName(dictData.deviceStatus, res.deviceStatus)}】，不允许报修`)
    } else {
        formData.value.equipmentId = res.id
        formData.value.clientId = res.clientId
        showInfo.value.equipmentNo = res.number
        showInfo.value.equipmentName = res.name
        showInfo.value.detailedAddress = `${res.province || ''}${res.city || ''}${
            res.district || ''
        }${res.detailedAddress || ''}`
        showInfo.value.manufacturers = res.manufacturers
        showInfo.value.specification = res.specification
        showInfo.value.model = res.model
    }
}

onMounted(() => {
    getTypeList()
})

onLoad(option => {
    showInfo.value.equipmentNo = option.code as string
    deviceCode.value = option.code as string
    if (option.code) getInfoByCode()
})
</script>

<style lang="scss" scoped>
.online {
    @include flex-direction;
    gap: 20rpx;
    width: 100vw;
    height: 100vh;
    padding: 20rpx 24rpx;
    background-color: $gray-1;
    padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
    overflow: auto;
    .btn {
        @apply fixed bottom-0 left-0 bg-white w-full pt-3;
        padding-bottom: env(safe-area-inset-bottom);
    }
}
.picture {
    &::after {
        content: ' *';
        color: $red-1;
    }
}
</style>
