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

            <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> -->

            <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>

            <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>
                        <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="选择产品">
                    <!-- <template #suffix>
                        <up-button v-if="!disabled" type="success" size="mini" text="选择产品" @click="toSelectProduct" />
                    </template> -->
                </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 label="经销商" prop="serviceenterprisename">
                <up-textarea maxlength="499" v-model="form.serviceenterprisename" disabled placeholder="经销商" autoHeight
                    height="20" />
            </up-form-item>
            <up-form-item label="客户名称" prop="customername">
                <up-input v-model="form.customername" disabled placeholder="客户名称" />
            </up-form-item>
            <up-form-item label="客户电话" prop="customerphonenumber">
                <up-input v-model="form.customerphonenumber" placeholder="客户电话">
                    <template #suffix>
                        <up-button type="success" :disabled="!form.customerphonenumber" size="mini" text="查询"
                            @click="phonenumberConfirm" />
                    </template>
                </up-input>
            </up-form-item>
            <up-form-item 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>

    <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 { onLoad } from '@dcloudio/uni-app';

const uFormRef = ref(null);
const form = reactive({
    class1: '', // 产品品类
    class2: '', // 故障类型
    servicetype: '', // 服务类型
    address: "", // 详细地址
    province: '', // 省份
    city: '', // 城市
    county: '', // 区县
    scenecontact: '', // 联系人
    scenecontactphonenumber: '', // 联系人电话
    sku: '', // 序列号
    'customername': "", // 客户名称
    'customerphonenumber': "", // 客户电话
    'itemid': "", //    产品ID
    'itemname': "", // 产品名称
    'itemno': "", // 产品编号
    'model': "", // 型号
    'unitname': "", // 计量单位
    'spec': "", // 规格
    serviceenterprisename: "", //  经销商
    cardno: "" // 保修卡号
});
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: 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 == '维修';
    uFormRef.value.setRules(rules);
}

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

let sa_workorderid = 0;

onLoad((options) => {
    sa_workorderid = options.id;
    getDetail()
    $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 detail = reactive({});

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

function save() {
    if (querySku.value === false) return uni.showToast({ title: '序列号不正确', icon: 'none' });
    if (loading.value) return;
    uFormRef.value.validate().then(valid => {
        if (valid) {
            let content = {
                "sa_workorderid": sa_workorderid,
                sa_serviceorderid: detail.sa_serviceorderid,
                ...form
            };
            content.customerphonenumber = content.customerphonenumber || content.phonenumber;
            content.name = content.customername || '';
            content.sa_customersid = content.sa_customersid || 0;
            loading.value = true;
            $Http.basic({
                "id": "20230208140003",
                content
            }).then(res => {
                loading.value = false;
                console.log("保存工单", res);
                uni.showToast({ title: res.code !== 1 ? res.msg : "保存成功", icon: 'none', mask: res.code == 1 });
                if (res.code == 1) setTimeout(() => {
                    uni.navigateBack();
                }, 500);
            }).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 == '维修'
        for (const key in form) {
            if (detail[key] !== undefined) {
                form[key] = detail[key];
            }
        }
        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];
}

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

function skuConfirm() {
    if (form.sku) {
        ['serviceenterprisename', "customername", 'customerphonenumber', 'sa_customersid', 'cardno', 'itemid', 'itemname', 'itemno', 'model', 'phonenumber', 'unitname', 'spec'].forEach(key => {
            form[key] = '';
        });
        if (form.sku.length < 3) {
            querySku.value = false;
            return uni.showToast({ title: '请输入正确的序列号', icon: 'none' });
        }
        uni.showLoading({ title: '查询中...' });
        $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].customername = res.data[0].customername || res.data[0].name;
            res.data[0].customerphonenumber = res.data[0].customerphonenumber || res.data[0].phonenumber;
            res.data[0].serviceenterprisename = res.data[0].serviceenterprisename || res.data[0].enterprisename;
            ["customername", 'customerphonenumber', 'sa_customersid', 'phonenumber', 'serviceenterprisename', 'cardno', 'itemid', 'itemname', 'itemno', 'model', 'unitname', 'spec'].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.customername = item.customername || item.name;
    item.customerphonenumber = item.customerphonenumber || item.phonenumber;

    if (item.itemid == detail.itemid) {
        handle();
    } else {
        uni.showModal({
            title: '提示',
            content: `当前选择的产品与工单中的产品不一致，是否继续？`,
            success: function ({ confirm }) {
                if (confirm) handle()
            }
        });
    }

    function handle() {
        item.serviceenterprisename = item.serviceenterprisename || item.enterprisename;
        ['serviceenterprisename', "customername", 'customerphonenumber', 'sa_customersid', 'sku', 'cardno', 'itemid', 'itemname', 'itemno', 'model', 'phonenumber', 'unitname', 'spec'].forEach(key => {
            form[key] = item[key] || '';
        });
        uni.showToast({ title: '已填充表单', icon: 'none' });
        querySku.value = true;
        closePopup();
    }
}

function phonenumberConfirm() {
    // 校验手机号
    const phoneRegex = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/;
    if (!phoneRegex.test(form.customerphonenumber)) {
        return uni.showToast({ title: '请输入正确的手机号', icon: 'none' });
    }
    uni.showLoading({ title: '查询中...' });
    $Http.basic({
        "id": 2025080813465203,
        "content": {
            "pageNumber": 1,
            "pageSize": 50,
            "where": {
                phonenumber: form.customerphonenumber,
            }
        }
    }).then(res => {
        uni.hideLoading();
        console.log("根据用户手机查询", res)
        if (res.code !== 1) return uni.showToast({ title: res.msg, icon: 'none' });
        if (res.data.length === 0) return uni.showToast({ title: '未找到对应的客户信息', icon: 'none' });
        if (res.data.length == 1 && detail.itemid == res.data[0].itemid) {
            changeItem(res.data[0]);
        } else {
            products.value = res.data;
        }
    })
}

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' });
        }
    });
}

//去选择产品
function toSelectProduct() {
    uni.navigateTo({
        url: '/pages/select/product'
    });
    $Http.onSelected = (item) => {
        ['serviceenterprisename', 'sku', 'cardno', 'itemid', 'itemname', 'itemno', 'model', 'phonenumber', 'unitname', 'spec'].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;
    }
}
</style>