<template>
    <view class="content">
        <up-form :model="form" labelWidth="70" ref="uFormRef">
            <view class="title" style="margin-top: 0;">
                服务信息
            </view>

            <up-form-item v-if="detail.status == '待开始'" label="服务类型" :required="rules.servicetype[0].required"
                prop="servicetype">
                <up-radio-group v-model="form.servicetype" @change="servicetypeChange">
                    <up-radio :customStyle="{ marginLeft: '12px' }" v-for="(item) in servertypes" :key="item"
                        :label="item" :name="item">
                    </up-radio>
                </up-radio-group>
            </up-form-item>

            <up-form-item label="产品品类" :required="rules.class1[0].required" prop="class1">
                <up-radio-group v-model="form.class1">
                    <up-radio :customStyle="{ marginLeft: '12px' }" v-for="(item) in class1" :key="item.value"
                        :label="item.value" :name="item.value">
                    </up-radio>
                </up-radio-group>
            </up-form-item>

            <up-form-item label="服务地址" :required="rules.province[0].required" prop="province">
                <picker class="picker" mode="region" :value="[form.province, form.city, form.county]"
                    @change="changeRegion">
                    {{ [form.province, form.city, form.county].join("-") || '选择省市县' }}
                </picker>
            </up-form-item>

            <view style="margin-top: -30rpx;">
                <up-form-item label="" prop="address">
                    <up-textarea maxlength="499" v-model="form.address" placeholder="详细地址" autoHeight height="20" />
                </up-form-item>
            </view>

            <up-form-item label="客户姓名" :required="rules.scenecontact[0].required" prop="scenecontact">
                <up-input v-model="form.scenecontact" placeholder="客户姓名" clearable />
            </up-form-item>

            <up-form-item label="客户手机号" :required="rules.scenecontactphonenumber[0].required"
                prop="scenecontactphonenumber">
                <up-input type="number" v-model="form.scenecontactphonenumber" placeholder="客户手机号" clearable />
            </up-form-item>

            <up-form-item label="服务距离(单程)" prop="servicemileage">
                <up-input v-model="form.servicemileage" placeholder="服务距离(单程)" clearable>
                    <template #suffix>
                        Km
                    </template>
                </up-input>
            </up-form-item>

            <view class="title">
                产品信息
            </view>
            <up-form-item label="序列号" :required="rules.sku[0].required" prop="sku">
                <up-input v-model="sku" placeholder="序列号" clearable @blur="skuConfirm">
                    <template #suffix>
                        <up-icon name="scan" color="#2979ff" size="28" @click="openScan" />
                    </template>
                </up-input>
            </up-form-item>
            <up-form-item label="产品名称" prop="itemname">
                <up-input v-model="form.itemname" disabled placeholder="选择产品">
                </up-input>
            </up-form-item>
            <up-form-item label="产品型号" prop="model">
                <up-input v-model="form.model" disabled placeholder="型号" />
            </up-form-item>
            <up-form-item v-if="form.servicetype != '安装'" label="保修卡号" prop="cardno">
                <up-input v-model="form.cardno" disabled placeholder="保修卡号" />
            </up-form-item>
        </up-form>
        <view style="padding-bottom: 50px;width: 350rpx;margin: 40rpx auto 0;" @click="save">
            <My-button text="保存" :loading="loading" />
        </view>
    </view>
</template>

<script setup>
import { ref, reactive, getCurrentInstance } from 'vue';
const { $Http } = getCurrentInstance().proxy;
import { onLoad } from '@dcloudio/uni-app';

const uFormRef = ref(null);
const sku = ref('');
const form = reactive({
    class1: '', // 产品品类
    class2: '', // 故障类型
    servicetype: '', // 服务类型
    address: "", // 详细地址
    province: '', // 省份
    city: '', // 城市
    county: '', // 区县
    scenecontact: '', // 客户名称
    scenecontactphonenumber: '', // 客户电话
    sku: '', // 序列号
    'customername': "", // 客户名称
    'customerphonenumber': "", // 客户电话
    'itemid': "", //    产品ID
    'itemname': "", // 产品名称
    'itemno': "", // 产品编号
    'model': "", // 型号
    'unitname': "", // 计量单位
    'spec': "", // 规格
    enterprisename: "", //  经销商
    cardno: "",// 保修卡号
    servicemileage: ""
});
const rules = reactive({
    class1: [{ required: true, message: '请选择产品品类', trigger: 'change' }],
    class2: [{ required: false, message: "请选择故障类型", trigger: 'change' }],
    servicetype: [{ required: true, message: '请选择服务类型', trigger: 'change' }],
    province: [{ required: true, message: '请选择省市县', trigger: 'change' }],
    address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
    scenecontact: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
    sku: [{ required: false, message: '请输入序列号', trigger: 'change' }],
    scenecontactphonenumber: [{ required: true, message: '请输入客户电话', trigger: 'blur', pattern: /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/, message: '请输入正确的手机号码' }],
});

// 切换服务类型
function servicetypeChange(type) {
    // rules.class2[0].required = type == '维修';
    rules.sku[0].required = type == '安装';
    uFormRef.value.setRules(rules);
}

const class1 = ref(''),
    servertypes = ref(['维修', '清洗']),
    class2 = ref('');

let sa_workorderid = 0;

onLoad((options) => {
    sa_workorderid = options.id;
    getDetail()

    $Http.getClass('prodclass1').then(res => {
        class1.value = res.data;
        if (res.code !== 1) return uni.showToast({ title: res.msg, icon: 'none' });
    });

    $Http.getClass('faulttype').then(res => {
        class2.value = res.data;
        uFormRef.value.setRules(rules);
        if (res.code !== 1) return uni.showToast({ title: res.msg, icon: 'none' });
    });
});

let detail = reactive({});

// 保存
let loading = ref(false);

function save() {
    if (loading.value) return;
    uFormRef.value.validate().then(async valid => {
        if (valid) {
            let content = Object.assign(detail, {
                "sa_workorderid": sa_workorderid,
                sa_serviceorderid: detail.sa_serviceorderid,
                ...form,
                servicemileage: form.servicemileage || 0,
                phonenumber: form.customerphonenumber || '',
            });
            content.customerphonenumber = content.customerphonenumber || content.phonenumber;
            content.name = content.customername || '';
            content.sa_customersid = content.sa_customersid == '' ? content.sa_customersid : 0;
            loading.value = true;
            if (content.sa_customersid == 0 || content.sa_customersid == '') await $Http.basic({
                "id": 2025121118401503,
                "content": {
                    "nocache": true,
                    sys_enterpriseid: detail.sys_enterpriseid,
                    "pageNumber": 1,
                    "pageSize": 2, "where": { "phonenumber": content.scenecontactphonenumber }
                }
            }).then(res => {
                console.log("查询客户信息", res)
                if (res.code === 1 && res.data.length > 0) {
                    content.sa_customersid = res.data[0].sa_customersid;
                    content.customername = res.data[0].name;
                    content.customerphonenumber = res.data[0].phonenumber;
                }
            });
            $Http.basic({
                "id": "20230208140003",
                content
            }).then(res => {
                loading.value = false;
                console.log("保存工单", res);
                if (res.code != 1) uni.showModal({
                    title: '错误提示',
                    content: res.msg,
                    showCancel: false,
                    confirmText: '我知道了',
                })
                let workorderids = uni.getStorageSync('workorderids') || [];
                workorderids.push(sa_workorderid);
                uni.setStorageSync('workorderids', workorderids);
                if (detail.status == '待开始') {
                    uni.showModal({
                        title: '提示',
                        content: '工单信息已保存，是否立即开始服务？',
                        cancelText: '稍后再说',
                        confirmText: '开始服务',
                        complete: async ({ confirm }) => {
                            if (confirm) {
                                uni.showLoading({ title: '加载中...', mask: true, });
                                let start = await $Http.basic({
                                    id: 20230209144503,
                                    "content": {
                                        "sa_workorderid": sa_workorderid
                                    }
                                })
                                uni.hideLoading();
                                console.log("开始工单", start)
                                $Http.getDetail && $Http.getDetail()
                            }
                            let pages = getCurrentPages();
                            if (pages[pages.length - 2].route == 'pages/workOrder/index') {
                                uni.redirectTo({
                                    url: `/pages/workOrder/detail?id=${sa_workorderid}`
                                });
                            } else {
                                uni.navigateBack({})
                            }
                        },
                    });
                } else {
                    let pages = getCurrentPages();
                    if (pages[pages.length - 2].route == 'pages/workOrder/index') {
                        uni.redirectTo({
                            url: `/pages/workOrder/detail?id=${sa_workorderid}`,
                            success: (success) => {
                                uni.showToast({ title: '工单信息已保存', icon: 'none' });
                            },
                        });
                    } else {
                        uni.navigateBack({
                            success: (success) => {
                                uni.showToast({ title: '工单信息已保存', icon: 'none' });
                            },
                        })
                        $Http.getDetail && $Http.getDetail()
                    }
                }
            }).catch(err => {
                loading.value = false;
                console.error("保存工单失败", err);
                uni.showToast({ title: '保存失败，请稍后重试', icon: 'none' });
            });
        }
    })
}
let disabled = ref(false);
function getDetail() {
    $Http.basic({ "id": "20230208140103", "content": { "nocache": true, sa_workorderid } }).then(res => {
        console.log("工单详情", res)
        if (res.code !== 1) return uni.showToast({ title: res.msg, icon: 'none' });
        detail = reactive(res.data);
        rules.class2[0].required = detail.type == '维修';
        if (detail.type == '安装') {
            servertypes.value = ['安装'];
            rules.sku[0].required = true
        } else {
            $Http.getClass('servertype').then(res1 => {
                servertypes.value = res1.data.map(v => v.value).filter(v => v != '安装')
                if (res1.code !== 1) return uni.showToast({ title: res.msg, icon: 'none' });
            });
        }
        if (res.data.servicetype)
            for (const key in form) {
                if (detail[key] !== undefined) {
                    form[key] = detail[key];
                    if (key == 'sku') {
                        sku.value = detail[key];
                    }
                }
            }
        if (detail.type == '安装') {
            let id = detail.sa_workorderid,
                workorderids = uni.getStorageSync('workorderids') || [];
            let hasId = workorderids.findIndex(item => item == id);
            if (hasId == -1) {
                form.sku = '';
                sku.value = '';
            }
        }
        disabled.value = detail.item ? true : false
    })
}

function changeRegion(e) {
    form.province = e.detail.value[0];
    form.city = e.detail.value[1];
    form.county = e.detail.value[2];
}

async function skuConfirm() {
    if (sku.value.trim()) {
        if (sku.value.trim() == '') return;
        let s = {
            code: 1,
        }
        try {
            if (detail.agentnum == detail.agentnum_service && detail.sys_enterpriseid) detail.initiator = '经销商';
        } catch (error) {

        }
        if (detail.initiator == '经销商') s = await $Http.basic({
            id: 2025121515015903,
            content: {
                sys_enterpriseid: detail.sys_enterpriseid,
                "sku": sku.value.trim()
            }
        })
        if (s.code !== 1) {
            uni.showModal({
                title: '错误提示',
                content: s.msg,
                showCancel: false,
                confirmText: '我知道了',
            })
            form.sku = '';
            sku.value = '';
            form.itemid = '';
            form.itemname = '';
            form.itemno = '';
            form.model = '';
            form.unitname = '';
            form.spec = '';
            form.cardno = '';
            return
        }
        $Http.basic({
            "id": 20221215101003,
            content: {
                nocache: true,
                "where": {
                    "sku": sku.value.trim()
                }
            }
        }).then(res => {
            console.log("查询sku", res)
            uni.hideLoading();
            if (res.code !== 1) {
                uni.showToast({ title: res.msg, icon: 'none' })
                form.sku = '';
                sku.value = '';
                form.itemid = '';
                form.itemname = '';
                form.itemno = '';
                form.model = '';
                form.unitname = '';
                form.spec = '';
                form.cardno = '';
                return
            };
            if (res.data.length === 0 || res.data[0].sku !== sku.value.trim()) {
                uni.showToast({ title: '未查询到对应的产品信息，请确认序列号是否正确', icon: 'none' });
                form.sku = '';
                sku.value = '';
                form.itemid = '';
                form.itemname = '';
                form.itemno = '';
                form.model = '';
                form.unitname = '';
                form.spec = '';
                form.cardno = '';
                return;
            }
            changeItem(res.data[0]);
        })
    } else {
        form.sku = '';
        sku.value = '';
    }
}

function changeItem(item) {
    let list = ['sku', 'cardno', 'itemid', 'itemname', 'itemno', 'sa_customersid'];
    list.forEach(key => {
        if (key == 'sku') sku.value = item[key] || '';
        form[key] = item[key] || '';
    });
    uFormRef.value.clearValidate('sku');
}

function openScan() {
    uni.scanCode({
        onlyFromCamera: true,
        scanType: ['qrCode', 'barCode'],
        success: (res) => {
            console.log("扫码结果", res);
            if (res.result) {
                form.sku = res.result;
                skuConfirm();
            } else {
                uni.showToast({ title: '扫码失败，请重试', icon: 'none' });
            }
        },
        fail: (err) => {
            console.error("扫码失败", err);
            uni.showToast({ title: '扫码失败，请重试', icon: 'none' });
        }
    });
}

</script>

<style lang="scss" scoped>
.content {
    width: 100vw;
    padding: 20px;
    box-sizing: border-box;
    min-height: 100vh;
    background: #fff;


    .picker {
        width: 100%;
        border: 1px solid #dadbde;
        font-size: 32rpx;
        color: #606266;
        padding: 9px;
        border-radius: 8rpx;
    }

    .title {
        font-size: 34rpx;
        color: #4773EE;
        margin: 20rpx 0;
        font-weight: bold;
    }
}

.product {
    padding: 20rpx;
    background: #fff;
    margin: 10rpx 0;
    border-radius: 8rpx;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

    .itemname {
        font-size: 32rpx;
        color: #333;
        font-weight: bold;
        margin-bottom: 10rpx;
    }

    .row {
        font-size: 28rpx;
        color: #666;
        margin-top: 8rpx;
    }
}
</style>