import { getAcReduceListApi, getSysSeatListApi } from 'mocp/api/system'
import { formData, formRef, relatedSeatSet } from './add.compositions'
import { addUpdateSupportApi } from 'mocp/api/support-application'

//切换机号
export const changeAc = async () => {
    const res = await getAcReduceListApi({ ac: formData.machineNumber }, { loading: true })
    if (res.code == 200) {
        formData.model = res.data[0]?.zstortgc
        formData.aviation = res.data[0]?.zop3
    } else {
        uni.$mocpMessage.error(res.message)
    }
}
//选择相关席位
export const onBeforeOpen = async () => {
    if (!formData.machineNumber) {
        uni.$mocpMessage.error('请选择机号')
        return false
    }
    if (!formData.terminal) {
        uni.$mocpMessage.error('请选择航站')
        return false
    }
    try {
        await uni.showLoading({
            mask: true,
            title: '检索席位中'
        })
        const terminalCode = formData.terminal.match(/[A-Z]+/gi)[0]
        const resp = await Promise.all([
            getSysSeatListApi({
                pid: 0,
                seatType: 1,
                pageSize: 1000,
                terminalCode
            }),
            getSysSeatListApi({
                pid: 0,
                seatType: 1,
                pageSize: 1000,
                acType: formData.model
            })
        ])
        if (resp.every((a) => a.code.toString() === '200')) {
            relatedSeatSet.value = resp[0].data.list.concat(resp[1].data.list)
            return true
        } else {
            throw new Error('请求席位失败！')
        }
    } catch (res) {
        uni.$mocpMessage.error(res.message)
    } finally {
        uni.hideLoading()
    }
}
//提交表单
export const handleSubmit = async (sponsorSeat) => {
    await formRef.value?.validate()
    const res = await addUpdateSupportApi({ ...formData, sponsorSeat }, { loading: true })
    if (res.code == 200) {
        uni.$mocpJump.navigateBack()
        uni.$mocpMessage.success(res.message)
        uni.$emit('supportApplicationReload')
    } else {
        uni.$mocpMessage.error(res.message)
    }
}
