123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125 |
- import { nextTick, ref } from 'vue'
- import type { MqttDevice } from '@/types'
- import { useLoad } from '@tarojs/taro'
- import Taro from '@tarojs/taro'
- import { addMqttDevice, updateMqttDevice } from '@/api/mqttDevice'
- import { useShopStoreHook } from '@/store/shopStore'
- export default function useMqttDeviceEditHook() {
- // 创建一个响应式的设备表单对象
- const deviceForm = ref<MqttDevice>({
- device_type: 1,
- device_key: '',
- shop_id: useShopStoreHook().currentShop.shop_id as number
- })
- //表单引用
- const formRef = ref()
- // 定义可选的设备类型列表
- const deviceTypes = [
- { text: '云打印', value: 1 },
- { text: '云音响', value: 2 },
- ]
- // 控制设备类型选择器的显示状态
- const showDeviceTypePicker = ref(false)
- // 处理设备类型选择确认事件
- const onConfirm = ({ selectedValue, selectedOptions }) => {
- deviceForm.value.device_type = selectedValue[0]
- showDeviceTypePicker.value = false
- nextTick(() => {
- customBlurValidate('deviceType')
- })
- }
- // 处理表单提交
- const submitForm = () => {
- // 这里可以添加表单验证逻辑
- formRef.value.validate().then(({ valid, errors }) => {
- if (valid) {
- if (deviceForm.value.id) {
- updateMqttDevice(deviceForm.value,deviceForm.value.id).then(res => {
-
- Taro.showToast({
- title: '修改成功',
- icon: 'success',
- duration:2000
- })
- }).catch(err => {
- Taro.showToast({
- title: err.data.message,
- icon: 'none'
- })
- })
- } else {
- addMqttDevice(deviceForm.value).then(res => {
- Object.assign(deviceForm.value, res.data)
- if(res.data.success){
- Taro.showToast({
- title: '添加成功',
- icon: 'success',
- duration:2000
- })
- }else{
- Taro.showToast({
- title: res.data.message || '添加失败',
- icon: 'error'
- })
- }
- }).catch(err => {
- Taro.showToast({
- title: err.data.message,
- icon: 'error'
- })
- })
- }
- } else {
- Taro.showToast({
- title: '请检查表单',
- icon: 'none'
- })
- }}).catch(err => {
- console.log(err)
- })
- }
- //自定义表单验证
- const customBlurValidate = (key: string) => {
- formRef.value.validate(key)
- }
- //onload
- useLoad(async (option) => {
- if (option?.id) {
- Taro.setNavigationBarTitle({
- title: '编辑设备'
- })
- // 设置 id,
- deviceForm.value.id = option.id
-
- } else {
- Taro.setNavigationBarTitle({
- title: '添加设备'
- })
- }
- //设置设备key和设备类型
- if(option?.device_key){
- deviceForm.value.device_key = option.device_key
- }
- if(option?.device_type){
- deviceForm.value.device_type = Number(option.device_type)
- }
- })
- // 返回hook中的响应式数据和方法
- return {
- deviceForm,
- formRef,
- deviceTypes,
- showDeviceTypePicker,
- onConfirm,
- submitForm,
- customBlurValidate,
- }
- }
|