<template>
    <view class="flex1">
        <view>
            <up-swipe-action>
                <template v-for="(item, index) in list" :key="index">
                    <up-swipe-action-item class="mb-20" :options="options" @click="clickPlotSwipe($event, item, index)">
                        <view class="ul-block-item pd-24">
                            {{ item.animalId }}
                        </view>
                    </up-swipe-action-item>
                </template>
            </up-swipe-action>
        </view>
        <view class="d-flex">
            <up-button class="flex1 mr-20" color="#18BECA" plain @click="onScan">
                <image class="w-36 h-36 mr-10" src="https://ta.zycpzs.cn/oss-file/smart-trace/szyy/images-plt/common/scan_icon_o.png" mode="widthFix" />
                <span>扫一扫添加</span>
            </up-button>
            <up-button @click="onAddClick" class="flex1" color="#37A954" plain>
                <image class="w-36 h-36 mr-10" src="https://ta.zycpzs.cn/oss-file/smart-trace/szyy/images-plt/common/edit_icon.png" mode="widthFix" />
                <span>手动输入添加</span>
            </up-button>
        </view>
    </view>
    <ut-confirm-dialog title="添加个体标识" v-model:show="showPop" width="680rpx">
        <view>
            <up-form ref="upFormRef" :model="form" :rules="rules" labelWidth="auto" class="p-rtv" labelPosition="top">
                <up-form-item label="个体标识号" border-bottom prop="animalId" required>
                    <up-input v-model="form.animalId" border="none" :maxlength="200" clearable placeholder="请输入个体标识号"></up-input>
                </up-form-item>
            </up-form>
        </view>
        <template #footer>
            <view class="d-flex j-c pd-30">
                <up-button @click="showPop = false" class="mr-30" style="color: #333" color="#F2F2F2">取消</up-button>
                <up-button @click="onConfirm" type="primary">确认</up-button>
            </view>
        </template>
    </ut-confirm-dialog>
</template>
<script setup lang="ts">
const props = defineProps({
    modelValue: {
        type: Array,
        default: () => [],
    },
});
const upFormRef = ref();
const rules = reactive({
    animalId: [{ required: true, message: '请输入个体标识号', trigger: 'blur' }],
});
const showPop = ref(false);
const form = ref({
    animalId: '',
});
// -1 表示新增，其它为编辑的下标
const editIndex = ref<number>(-1);
const emit = defineEmits(['update:modelValue']);
const list = ref<any[]>(props.modelValue);
const options = ref([
    {
        text: '编辑',
        name: 'edit',
        style: {
            backgroundColor: '#37a954',
            color: '#fff',
        },
    },
    {
        text: '删除',
        name: 'delete',
        style: {
            backgroundColor: '#FF3B30',
            color: '#fff',
        },
    },
]);
const clickPlotSwipe = (e: any, item: any, index: number) => {
    console.log(e);
    
    if (e.index == 0) {
        // 编辑个体标识
        console.log('编辑个体标识', item, index);
        editIndex.value = index;
        form.value.animalId = item?.animalId || '';
        showPop.value = true;
    } else if (e.index == 1) {
        // 删除个体标识
        list.value.splice(index, 1);
        emit('update:modelValue', [...list.value]);
        
    }
};
const onConfirm = async () => {
    try {
        // uview-plus 的 up-form 暴露 validate 方法
        await upFormRef.value?.validate();
        if (editIndex.value > -1) {
            // 编辑模式：更新当前项
            list.value[editIndex.value] = { ...list.value[editIndex.value], ...form.value };
        } else {
            // 新增模式：追加一项
            list.value.push({ ...form.value });
        }
        emit('update:modelValue', [...list.value]);
        showPop.value = false;
        form.value.animalId = '';
        editIndex.value = -1;
    } catch (e) {
        // 校验不通过
    }
};
// 手动新增按钮点击
const onAddClick = () => {
    editIndex.value = -1;
    form.value.animalId = '';
    showPop.value = true;
};

// 扫一扫添加
const onScan = () => {
    // #ifdef MP-WEIXIN
    uni.scanCode({
        onlyFromCamera: true,
        success: (res) => {
            const code = (res.result || '').trim();
            if (!code) return;
            // 直接追加到列表
            list.value.push({ animalId: code });
            emit('update:modelValue', [...list.value]);
        },
        fail: () => {},
    });
    // #endif
    // 其他端如 H5/App 可按需再做兼容
};
watch(
    () => props.modelValue,
    (newVal) => {
        console.log(newVal, '------');
        
        list.value = newVal;
    },
);
</script>
<script lang="ts">
export default {
    options: {
        // 微信小程序中 options 选项
        multipleSlots: true, //  在组件定义时的选项中启动多slot支持，默认启用
        styleIsolation: 'shared', //  启动样式隔离。当使用页面自定义组件，希望父组件影响子组件样式时可能需要配置。具体配置选项参见：微信小程序自定义组件的样式
        addGlobalClass: true, //  表示页面样式将影响到自定义组件，但自定义组件中指定的样式不会影响页面。这个选项等价于设置 styleIsolation: apply-shared
        virtualHost: true, //  将自定义节点设置成虚拟的，更加接近Vue组件的表现。我们不希望自定义组件的这个节点本身可以设置样式、响应 flex 布局等，而是希望自定义组件内部的第一层节点能够响应 flex 布局或者样式由自定义组件本身完全决定
    },
};
</script>
<style lang="scss" scoped>
.ul-block-item {
    border-radius: 16rpx;
    border: 1px solid #AFDDBB;
    // 字体数字可换行
    word-break: break-all;
}
</style>
