<template>
    <z-paging ref="paging" bgColor="#fff" safe-area-inset-bottom paging-class="paging-btm-shadow" scroll-with-animation>
        <template #top>
            <ut-navbar :title="did ? '编辑往来单位信息' : '新增往来单位信息'" :fixed="false" border></ut-navbar>
        </template>
        <up-form class="p-rtv" labelPosition="top" :model="form" :rules="rules" labelWidth="auto" ref="upFormRef">
            <view class="pd-24 bg-#fff mb-10">
                <!-- 往来单位类型（多个可用逗号分隔） -->
                <view class="h-1" id="cpyTypepppp"></view>
                <ut-action-sheet v-model="form.cpyType" :tabs="pt_cpy_type" valueType="array" mode="custom" title="选择往来单位类型" multiple>
                    <up-form-item borderBottom label="往来单位类型" required prop="cpyType">
                        <view v-if="form.cpyType?.length" class="f-s-30 c-333 f-w-5 flex1">{{ selectDictLabels(pt_cpy_type, form.cpyType, ',') }}</view>
                        <view v-else class="f-s-30 c-ccc f-w-4 flex1">请选择往来单位类型</view>
                        <template #right>
                            <up-icon size="22rpx" color="#2A6D52" name="arrow-down-fill"></up-icon>
                        </template>
                    </up-form-item>
                </ut-action-sheet>
                <!-- 往来单位性质 -->
                <view class="h-1" id="cusTypepppp"></view>
                <ut-action-sheet v-model="form.cusType" :tabs="pt_cus_type" mode="custom" title="选择往来单位性质">
                    <up-form-item borderBottom label="往来单位性质" required prop="cusType">
                        <view v-if="form.cusType" class="f-s-30 c-333 f-w-5 flex1">{{ selectDictLabel(pt_cus_type, form.cusType) }}</view>
                        <view v-else class="f-s-30 c-ccc f-w-4 flex1">请选择往来单位性质</view>
                        <template #right>
                            <up-icon size="22rpx" color="#2A6D52" name="arrow-down-fill"></up-icon>
                        </template>
                    </up-form-item>
                </ut-action-sheet>
                <!-- 往来单位名称 -->
                <template v-if="form.cusType == '1'">
                    <view class="h-1" id="cusNamepppp"></view>
                    <up-form-item borderBottom label="姓名" required prop="cusName">
                        <up-input v-model="form.cusName" placeholder="请输入姓名" border="none" clearable></up-input>
                    </up-form-item>
                    <!-- 统一社会信用代码 -->
                    <view class="h-1" id="cusCodepppp"></view>
                    <up-form-item borderBottom label="身份证号" prop="cusCode" required>
                        <up-input v-model="form.cusCode" placeholder="请输入身份证号" maxlength="18" border="none" clearable></up-input>
                    </up-form-item>
                </template>
                <!-- 往来单位名称 -->
                <template v-else>
                    <view class="h-1" id="cusNamepppp"></view>
                    <up-form-item borderBottom label="往来单位名称" required prop="cusName">
                        <up-input v-model="form.cusName" placeholder="请输入往来单位名称" border="none" clearable></up-input>
                    </up-form-item>
                    <!-- 统一社会信用代码 -->
                    <view class="h-1" id="cusCodepppp"></view>
                    <up-form-item borderBottom label="统一社会信用代码/组织机构代码" prop="cusCode" required>
                        <up-input v-model="form.cusCode" placeholder="请输入统一社会信用代码/组织机构代码" maxlength="30" border="none" clearable></up-input>
                    </up-form-item>
                </template>

                <ut-action-sheet v-model="form.subdivisionType" :tabs="pt_subdivision_type" mode="custom" title="选择细分类型">
                    <up-form-item borderBottom label="细分类型" prop="subdivisionType">
                        <view v-if="form.subdivisionType" class="f-s-30 c-333 f-w-5 flex1">{{ selectDictLabel(pt_subdivision_type, form.subdivisionType) }}</view>
                        <view v-else class="f-s-30 c-ccc f-w-4 flex1">请选择细分类型</view>
                        <template #right>
                            <up-icon size="22rpx" color="#2A6D52" name="arrow-down-fill"></up-icon>
                        </template>
                    </up-form-item>
                </ut-action-sheet>

                <!-- 联系人 -->
                <up-form-item borderBottom label="联系人" prop="contact">
                    <up-input v-model="form.contact" placeholder="请输入联系人" border="none" clearable></up-input>
                </up-form-item>

                <!-- 联系电话 -->
                <view class="h-1" id="contactTelpppp"></view>
                <up-form-item borderBottom label="联系电话" prop="contactTel">
                    <up-input v-model="form.contactTel" placeholder="请输入联系电话" border="none" clearable></up-input>
                </up-form-item>
                <!-- 所在地区 -->
                <view class="h-1" id="adcdCodepppp"></view>
                <up-form-item @click="showArea = true" borderBottom label="往来单位所在地区" required prop="adcdCode">
                    <view v-if="form.adcdCode" class="f-s-30 c-333 f-w-5 flex1">{{ form.adcdCodeName }}</view>
                    <view v-else class="f-s-30 c-ccc f-w-4 flex1">请选择往来单位所在地区</view>
                    <template #right>
                        <up-icon size="22rpx" color="#2A6D52" name="arrow-down-fill"></up-icon>
                    </template>
                </up-form-item>

                <!-- 详细地址 -->
                <up-form-item borderBottom label="往来单位具体地址" prop="address">
                    <up-input v-model="form.address" placeholder="请输入往来单位具体地址" border="none" clearable></up-input>
                </up-form-item>
                <!-- 邮编 -->
                <up-form-item v-if="form.cpyType?.includes('3')" borderBottom label="邮编" prop="postcode">
                    <up-input v-model="form.postcode" placeholder="请输入邮编" border="none" clearable></up-input>
                </up-form-item>
                <!-- 备注 -->
                <up-form-item label="备注" prop="remark">
                    <up-textarea v-model="form.remark" placeholder="请输入备注" maxlength="300" autoHeight clearable></up-textarea>
                </up-form-item>
            </view>
        </up-form>
        <template #bottom>
            <view class="pd-20">
                <up-button type="primary" @click="submit">
                    <text>{{ did ? '保存' : '提交' }}</text>
                </up-button>
            </view>
        </template>
    </z-paging>
    <ut-picker-area v-model:show="showArea" v-model="form.adcdCode" @confirm="confirmArea"></ut-picker-area>
</template>
<script setup lang="ts">
import type { CustomerAddDTO } from '../models/type';
import { useClientRequest } from '@/utils/request';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { pt_cus_type, pt_cpy_type, pt_subdivision_type } = toRefs<any>(proxy?.useDict('pt_cus_type', 'pt_cpy_type', 'pt_subdivision_type'));
const upFormRef = ref();
const paging = ref();
const did = ref<string>('');
const showArea = ref(false);

const form = ref<CustomerAddDTO & { adcdCodeName?: string }>({
    cusType: '',
    cusName: '',
    abbravName: '',
    adcdCode: '',
    adcdCodeName: '',
    address: '',
    contact: '',
    contactTel: '',
    cpyType: [],
    cusCode: '',
    postcode: '',
    remark: '',
    subdivisionType: '',
} as CustomerAddDTO & { adcdCodeName?: string });

// 用于输入展示，提交时再转换为数组
const cpyTypeText = ref('');

const rules = reactive({
    cpyType: [{ required: true, type: 'array', message: '请选择往来单位类型', trigger: 'blur' }],
    cusType: [{ required: true, message: '请选择往来单位性质', trigger: 'blur' }],
    // cusName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    // cusCode: [{ required: true, message: '请输入身份证号', trigger: 'blur' }],
    // 如果是选择个人是姓名和身份证号必填，否则单位名称和统一社会信用代码必填
    cusName: [
        {
            asyncValidator: (rule: any, value: string, callback: (error?: Error) => void) => {
                if (form.value.cusType == '1') {
                    if (!value || !value.trim()) {
                        return callback(new Error('请输入姓名'));
                    }
                } else {
                    if (!value || !value.trim()) {
                        return callback(new Error('请输入往来单位名称'));
                    }
                }
                callback();
            },
        }
    ],
    cusCode: [
        {
            asyncValidator: (rule: any, value: string, callback: (error?: Error) => void) => {
                if (form.value.cusType == '1') {
                    if (!value || !value.trim()) {
                        return callback(new Error('请输入身份证号'));
                    }
                } else {
                    if (!value || !value.trim()) {
                        return callback(new Error('请输入统一社会信用代码/组织机构代码'));
                    }
                }
                callback();
            },
        }
    ],
    adcdCode: [{ required: true, message: '请选择往来单位所在地区', trigger: 'blur' }],
    contactTel: [
        {
            pattern: /^(\+?\d{1,4}[-\s]?)?((\d{3,4}[-\s]?)?\d{7,8}|1[1-9]\d{9})$/,
            message: '请输入正确的联系电话',
            trigger: 'blur',
        },
    ],
});

const loadDetail = async (id: string) => {
    if (!id) return;
    const res = await useClientRequest.get(`/plt-api/app/customer/getInfo/${id}`);
    if (res && res.code === 200) {
        const data = res.data || {};
        form.value = {
            ...data,
        } as CustomerAddDTO & { adcdCodeName?: string };
    }
};

const submit = async () => {
    try {
        await upFormRef.value?.validate();
    } catch (error: any) {
        const firstErrorField = error && error[0].prop + 'pppp';
        paging.value?.scrollIntoViewById(firstErrorField, 30, true);
        return;
    }

    try {
        await uni.showLoading({ title: did.value ? '保存中...' : '提交中...', mask: true });
        const url = did.value ? '/plt-api/app/customer/edit' : '/plt-api/app/customer/add';
        const payload: any = { ...(form.value as any) };
        if (did.value) payload.id = did.value;
        const res = await useClientRequest.post(url, payload);
        uni.hideLoading();
        if (res && res.code === 200) {
            uni.showToast({ title: did.value ? '保存成功' : '新增成功', icon: 'success' });
            uni.$emit('refreshContactUnitDetail');
            uni.$emit('refreshContactUnitList');
            setTimeout(() => uni.navigateBack(), 300);
        }
    } catch (e) {
        uni.hideLoading();
        console.error('保存往来单位失败:', e);
    }
};

const confirmArea = (area: any) => {
    form.value.adcdCodeName = area.fullName;
};

onLoad((options: any) => {
    did.value = options?.id || '';
    if (did.value) {
        loadDetail(did.value);
    }
    paging.value?.complete();
});
</script>
<style lang="scss" scoped>
.startline-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
}
.base-bottom-wrap {
    background-color: #fff;
}
</style>
