<template>
    <view class="common-page" style="padding: 0;">
        <view class="form-page">
            <u-form ref="formRef" :model="form" :rules="rules" labelPosition="left" label-width="85px">
                <u-form-item label="快递单号：" prop="waybillCode" required>
                    <template v-if="isReadonly && form.waybillCode">
                        <text class="readonly-text">{{ form.waybillCode }}</text>
                    </template>
                    <u-input v-else v-model="form.waybillCode" placeholder="请输入快递单号" clearable></u-input>
                </u-form-item>
                <u-form-item label="订单编号：" prop="orderId" required>
                    <template v-if="isReadonly && form.orderId">
                        <text class="clickable-text" @click="goToOrderDetail">{{ form.orderId }}</text>
                    </template>
                    <u-input v-else v-model="form.orderId" placeholder="请输入订单编号" clearable></u-input>
                </u-form-item>
                <u-form-item label="任务类型：" prop="taskType" required>
                    <u-input v-model="taskTypeText" readonly suffixIcon="arrow-down" placeholder="请选择"
                        @click="showTaskTypePicker = true"></u-input>
                </u-form-item>
                <u-form-item label="任务详情：" prop="taskDetail" required>
                    <u-textarea v-model="form.taskDetail" placeholder="请输入" :height="120"
                        :autoHeight="true"></u-textarea>
                </u-form-item>
                <u-form-item label="上传图片：" prop="imgInfo" required>
                    <cy-upload :filename="form.imgInfo" @update:filename="form.imgInfo = $event" />
                </u-form-item>
            </u-form>
        </view>

        <u-picker :show="showTaskTypePicker" :columns="[taskTypeOptions]" title="选择任务类型" @confirm="onPickTaskType"
            @cancel="showTaskTypePicker = false" @close="showTaskTypePicker = false"></u-picker>

        <view class="fixed-bottom">
            <u-button type="warning" size="large" @click="onCancel">取消</u-button>
            <u-button type="primary" size="large" :loading="submitting" @click="onSubmit">提交</u-button>
        </view>
    </view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import CyUpload from '@/components/cy-upload/index.vue'

const formRef = ref(null)
const submitting = ref(false)

const form = ref({
    waybillCode: '',
    orderId: '',
    taskType: '',
    taskDetail: '',
    imgInfo: []
})

const rules = {
    waybillCode: [{ required: true, message: '请输入快递单号' }],
    orderId: [{ required: true, message: '请输入订单编号' }],
    taskType: [{ required: true, message: '请选择任务类型' }],
    taskDetail: [{ required: true, message: '请输入任务详情' }],
}

const taskTypeOptions = ref([])

const showTaskTypePicker = ref(false)
const taskTypeText = ref('')

// 获取任务类型字典
const getTaskTypeOptions = async () => {
    try {
        const res = await uni.$u.http.get('/system/dict/data/type/task_type')
        if (res.code === 200 && res.data) {
            taskTypeOptions.value = res.data.map(item => ({
                text: item.dictLabel,
                value: parseInt(item.dictValue)
            }))
        }
    } catch (e) {
        console.error('获取任务类型失败', e)
    }
}

const onPickTaskType = (e) => {
    console.log(e)
    const cell = e.value?.[0]
    form.value.taskType = cell?.value || ''
    taskTypeText.value = cell?.text || ''
    showTaskTypePicker.value = false
}

const onCancel = () => {
    uni.navigateBack()
}

const goToOrderDetail = () => {
    if (!form.value.orderId) return
    uni.navigateTo({
        url: `/pages/index/detail/index?id=${form.value.orderId}`
    })
}

const workOrderId = ref('')
const isEdit = ref(false)
const isReadonly = ref(false)
const expressTypeFromScan = ref(0)

const onLoadDetail = async (id) => {
    try {
        const res = await uni.$u.http.get('/app/workOrder/getWorkOrderDetail', {
            params: { workOrderId: id }
        })
        if (res.code === 200 && res.data) {
            const data = res.data
            form.value.waybillCode = data.waybillCode || ''
            form.value.orderId = data.orderId || ''
            form.value.taskDetail = data.deatil || data.taskDetail || ''
            form.value.imgInfo = data.imgInfo?.imgUrlList?.length ? data.imgInfo.imgUrlList : []

            // 加载任务类型字典
            await getTaskTypeOptions()

            // 回显任务类型
            if (data.taskType) {
                form.value.taskType = data.taskType
                const matchedType = taskTypeOptions.value.find(item => item.value === data.taskType)
                if (matchedType) {
                    taskTypeText.value = matchedType.text
                }
            }
        }
    } catch (e) {
        console.error(e)
    }
}

const onSubmit = async () => {
    if (submitting.value) return
    try {
        await formRef.value?.validate?.()
    } catch (e) {
        return
    }
    submitting.value = true
    const payload = {
        taskType: form.value.taskType,
        inspectionStatus: 0, // 默认未验货
        deatil: form.value.taskDetail,
        waybillCode: form.value.waybillCode,
        orderId: form.value.orderId,
        type: 2, // 工单类型：2-收书
        imgInfo: form.value.imgInfo,
        handleUsers: []
    }

    if (isEdit.value) {
        payload.id = workOrderId.value
        payload.updateType = 1
    }

    const apiUrl = isEdit.value ? '/app/workOrder/update' : '/app/workOrder/createWorkOrder'

    try {
        const res = await uni.$u.http.post(apiUrl, payload)
        if (res?.code === 200) {
            uni.$u.toast('提交成功')
            uni.navigateBack()
        } else {
            uni.$u.toast(res?.msg || '提交失败')
        }
    } catch (err) {
        uni.$u.toast('网络错误，已本地保存')
    } finally {
        submitting.value = false
    }
}

onLoad((options) => {
    form.value.waybillCode = options?.waybillCode || ''
    form.value.orderId = options?.orderId || ''
    if (options?.expressType) {
        expressTypeFromScan.value = parseInt(options.expressType)
    }

    if (options?.readonly == 1) {
        isReadonly.value = true
    }

    if (options?.mode === 'edit' && options?.workOrderId) {
        isEdit.value = true
        isReadonly.value = true
        workOrderId.value = options.workOrderId
        uni.setNavigationBarTitle({ title: '编辑工单' })
        onLoadDetail(options.workOrderId)
    } else {
        uni.setNavigationBarTitle({ title: '提交工单' })
    }

    // 加载任务类型字典
    getTaskTypeOptions()
})
</script>

<style lang="scss" scoped>
.form-page {
    padding: 24rpx 24rpx 140rpx;
    background: #ffffff;
}

.divider {
    height: 16rpx;
    background: #f4f5f5;
    margin: 20rpx 0;
}

.readonly-text {
    font-size: 28rpx;
    color: #333;
    line-height: 60rpx;
}

.clickable-text {
    font-size: 28rpx;
    color: #2979ff;
    line-height: 60rpx;
}
</style>
