<template>
    <My-shade />
    <view class="content">
        <view class="title">
            服务信息
        </view>
        <up-form :model="form" labelWidth="70" ref="uFormRef">
            <up-form-item 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 v-if="rules.class2[0].required" label="故障类型" :required="rules.class2[0].required"
                prop="class2">
                <up-radio-group v-model="form.class2">
                    <up-radio :customStyle="{ marginLeft: '12px' }" v-for="(item) in class2" :key="item.value"
                        :label="item.value" :name="item.value">
                    </up-radio>
                </up-radio-group>
            </up-form-item>

            <view class="title">
                产品信息
            </view>

            <up-form-item label="序列号" :required="rules.sku[0].required" prop="sku">
                <up-input v-model="form.sku" placeholder="序列号" clearable @blur="skuConfirm">
                    <template #suffix>
                        <view style="display: flex;align-items: center;">
                            <view class="my-but" hover-class="navigator-hover" @click="toSelectProduct2">
                                选择产品
                            </view>
                            <up-icon name="scan" color="#2979ff" size="28" @click="openScan" />
                        </view>
                    </template>
                </up-input>
            </up-form-item>

            <up-form-item label="产品名称" prop="itemname" :required="rules.itemname[0].required">
                <up-input v-model="form.itemname" disabled placeholder="请输入序列号或选择产品">
                    <template #suffix>
                        <view style="display: flex;align-items: center;">
                            <view class="my-but" hover-class="navigator-hover" @click="toSelectProduct">
                                选择产品
                            </view>
                        </view>
                    </template>
                </up-input>
            </up-form-item>

            <up-form-item label="产品编号" prop="itemno">
                <up-input v-model="form.itemno" disabled placeholder="请输入序列号或选择产品" />
            </up-form-item>

            <up-form-item label="产品型号" prop="model">
                <up-input v-model="form.model" disabled placeholder="请输入序列号或选择产品" />
            </up-form-item>
            <up-form-item label="保修卡号" prop="cardno">
                <up-input v-model="form.cardno" disabled placeholder="请输入序列号或选择产品" />
            </up-form-item>

            <view class="title">
                联系人信息
            </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="省市县" :required="rules.province[0].required" prop="province">
                <My_region @select="changeRegion"> {{ form.province ? [form.province, form.city, form.county].join("-")
                    : '选择省市县' }}
                </My_region>
            </up-form-item>

            <up-form-item label="详细地址" prop="address" :required="rules.address[0].required">
                <up-textarea maxlength="499" v-model="form.address" placeholder="详细地址" autoHeight height="20" />
            </up-form-item>

            <up-form-item label="" prop="remarks">
                <up-textarea v-model="form.remarks" placeholder="如有特殊需求，您可在此处留言" count></up-textarea>
            </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>

    <up-popup :show="products.length" @close="closePopup" :customStyle="{
        width: '80vw',
    }" mode="right">
        <scroll-view :safeAreaInsetBottom="false" scroll-y style="width: 100%;height: 100vh;">
            <view class="product" v-for="item in products" :key="item.itemid" hover-class="navigator-hover"
                @click="changeItem(item)">
                <view class="itemname">
                    {{ item.itemname }}
                </view>
                <view class="row">
                    序列号: {{ item.sku || '--' }}
                </view>
                <view class="row">
                    产品编号: {{ item.itemno || '--' }}
                </view>
                <view class="row">
                    产品型号: {{ item.model || '--' }}
                </view>
                <view class="row">
                    经销商: {{ item.enterprisename || '--' }}
                </view>
                <view class="row">
                    用户信息: {{ item.name || '--' }} {{ item.phonenumber || '--' }}
                </view>
            </view>
            <view style="height: 30px;" />
        </scroll-view>
    </up-popup>
</template>

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

const userMsg = uni.getStorageSync('userMsg');
const uFormRef = ref(null);
const form = reactive({
    sa_serviceorderid: 0,
    sa_orderid: 0,
    sys_enterpriseid: 0,
    servicetype: '', // 服务类型
    class1: '', // 产品品类
    class2: '', // 故障类型
    sku: '', // 序列号
    itemid: '', // 产品ID
    itemname: '', // 产品名称
    itemno: '', // 产品编号
    model: '', // 产品型号
    cardno: '', // 保修卡号

    scenecontact: userMsg.name, // 联系人
    scenecontactphonenumber: userMsg.phonenumber, // 联系人电话

    province: '', // 省
    city: '', // 市
    county: '', // 县

    address: '', // 详细地址
    remarks: ''
});

const rules = reactive({
    servicetype: [{ required: true, message: '请选择服务类型', trigger: 'change' }],
    class1: [{ required: true, message: '请选择产品品类', trigger: 'change' }],
    class2: [{ required: false, message: "请选择故障类型", trigger: 'change' }],
    sku: [{ required: false, message: '请输入序列号', trigger: 'blur' }],
    itemno: [{ required: false, message: '请输入产品编号', trigger: 'blur' }],
    itemname: [{ required: true, message: '请选择产品', trigger: 'blur' }],
    model: [{ required: false, message: '请输入产品型号', trigger: 'blur' }],
    cardno: [{ required: false, message: '请输入保修卡号', trigger: 'blur' }],
    province: [{ required: true, message: '请选择省市县', trigger: 'change' }],
    address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
    scenecontact: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
    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('');

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

    $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 loading = ref(false);

function save() {
    if (querySku.value === false) return uni.showToast({ title: '序列号不正确', icon: 'none' });
    if (loading.value) return;
    if (confirm) uFormRef.value.validate().then(valid => {
        if (valid) wx.showModal({
            content: '请确认预约信息正确以便后续服务，是否确认提交？',
            title: '提示',
            success: ({ confirm }) => {
                let userRecord = uni.getStorageSync('userRecord') || { sa_customersid: "" };
                form.customername = userRecord.name || form.scenecontact;
                form.customerphonenumber = userRecord.phonenumber || form.scenecontactphonenumber;
                form.name = form.customername;
                form.phonenumber = userRecord.phonenumber || form.scenecontactphonenumber;
                form.sa_customersid = userRecord.sa_customersid
                let content = {
                    ...form,
                };
                loading.value = true;
                $Http.basic({
                    "id": "20230206091403",
                    content
                }).then(res => {
                    loading.value = false;
                    console.log("提交申请单", res);
                    if (res.code !== 1) {
                        uni.showToast({ title: res.code !== 1 ? res.msg : "保存成功", icon: 'none', mask: res.code == 1 });
                    } else {
                        uni.showModal({
                            showCancel: false,
                            content: "预约申请已提交，请保持电话畅通，以便后续服务人员联系您！",
                            success: (success) => {
                                uni.navigateBack();
                            },
                        })
                        $Http.basic({
                            id: 20230206101403,
                            content: {
                                sa_serviceorderid: res.data.sa_serviceorderid,
                                backreason: "",
                                issumbit: 1
                            }
                        }).then(res => {
                            console.log("提交工单", res);
                        })
                    }
                }).catch(err => {
                    loading.value = false;
                    console.error("保存工单失败", err);
                    uni.showToast({ title: '保存失败，请稍后重试', icon: 'none' });
                });
            },
        })
    })

}

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

let querySku = ref(true); // SKU是否正确

function skuConfirm() {
    if (form.sku) {
        ['contact', 'serviceenterprisename', 'cardno', 'itemid', 'itemname', 'itemno', 'model', 'phonenumber', 'unitname', 'spec', 'sys_enterpriseid'].forEach(key => {
            form[key] = '';
        });
        if (form.sku == '') return;
        uni.showLoading({
            title: '查询中...',
            mask: true,
        });
        $Http.basic({
            "id": 2025080813465203,
            "content": {
                "pageNumber": 1,
                "pageSize": 1,
                "where": {
                    sku: form.sku,
                }
            }
        }).then(res => {
            console.log(res)
            uni.hideLoading();
            if (res.code !== 1) return uni.showToast({ title: res.msg, icon: 'none' });
            if (res.data.length === 0 || res.data[0].sku !== form.sku) {
                uni.showToast({ title: '未找到对应的产品信息', icon: 'none' });
                querySku.value = false;
                return;
            }
            querySku.value = true;
            res.data[0].contact = res.data[0].name;
            res.data[0].serviceenterprisename = res.data[0].serviceenterprisename || res.data[0].enterprisename;
            ['contact', 'phonenumber', 'serviceenterprisename', 'cardno', 'itemid', 'itemname', 'itemno', 'model', 'unitname', 'spec', 'address', 'province', 'city', 'county'].forEach(key => {
                form[key] = res.data[0][key] || '';
            });
            uni.showToast({ title: '已填充表单', icon: 'none' });
        })
    } else {
        form.sku = '';
    }
}

let products = ref([]); // 产品列表
function closePopup() {
    products.value = [];
}
function changeItem(item) {
    item.contact = item.name;
    item.serviceenterprisename = item.serviceenterprisename || item.enterprisename;
    ['contact', 'serviceenterprisename', 'sku', 'cardno', 'itemid', 'itemname', 'itemno', 'model', 'phonenumber', 'unitname', 'spec', 'sys_enterpriseid'].forEach(key => {
        form[key] = item[key] || '';
    });
    uni.showToast({ title: '已填充表单', icon: 'none' });
    querySku.value = true;
    closePopup();
}

import { BrowserMultiFormatReader } from '@zxing/library';
function openScan() {
    uni.chooseImage({
        count: 1,
        success: imgRes => {
            const imagePath = imgRes.tempFilePaths[0];

            const img = new Image();
            img.src = imagePath;

            img.onload = async () => {
                const codeReader = new BrowserMultiFormatReader();
                try {
                    const result = await codeReader.decodeFromImageElement(img);
                    form.sku = result.text;
                    skuConfirm();
                } catch (err) {
                    uni.showToast({ title: '未识别出二维码或条码', icon: 'none' });
                }
            };
        }
    });
}

//去选择产品
function toSelectProduct() {
    uni.navigateTo({
        url: '/pages/select/product'
    });
    $Http.onSelected = (item) => {
        ['contact', 'serviceenterprisename', 'sku', 'cardno', 'itemid', 'itemname', 'itemno', 'model', 'phonenumber', 'unitname', 'spec'].forEach(key => {
            form[key] = item[key] || '';
        });
        uni.navigateBack()
        delete $Http.onSelected
    }
}

function toSelectProduct2() {
    uni.navigateTo({
        url: '/pages/select/myProduct'
    });
    $Http.onSelected = (item) => {
        ['contact', 'phonenumber', 'sku', 'serviceenterprisename', 'cardno', 'itemid', 'itemname', 'itemno', 'model', 'unitname', 'spec', 'address', 'province', 'city', 'county', 'sys_enterpriseid'].forEach(key => {
            form[key] = item[key] || '';
        });
        uni.navigateBack()
        delete $Http.onSelected
    }
}
</script>

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


    .picker {
        width: 100%;
        // border-bottom: 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;
    }
}

.my-but {
    line-height: 44rpx;
    padding: 0 20rpx;
    background: #2979ff;
    color: #fff;
    border-radius: 8rpx;
    margin-right: 10rpx;
    font-size: 24rpx;
}
</style>