<template>
  <view>
    <navbar-back title="打印服务">
      <view class="navbar-right" slot="right">
        <view class="message-box right-item" @click="refreshPrint">
          <up-icon name="reload" color="#fff" size="20" />
        </view>
        <view class="dot-box right-item" @click="addPrintShow">
          <up-icon name="plus" color="#fff" size="20" />
        </view>
      </view>
    </navbar-back>

    <view>
      <up-swipe-action>
        <up-swipe-action-item
          v-for="(print, index) in printList"
          :key="index"
          :index="index"
          :options="options"
          @click="printSwipeClick"
        >
          <view class="x-f p10 border-b">
            <image :src="`/static/images/print${print.isOpen ? '' : '-close'}.png`" mode="aspectFill" />
            <view>
              <view>服务名称：{{ print.printName }}</view>

              <view>服务IP地址：{{ print.printIp }}</view>

              <view>服务端口：{{ print.printPort }}</view>

              <view>连接状态：{{ print.isOpen ? '连接正常！！！' : '连接关闭！！！' }}</view>
            </view>
          </view>
        </up-swipe-action-item>
      </up-swipe-action>
    </view>

    <u-modal
      :show="printShow"
      title="添加打印服务"
      show-cancel-button
      confirm-text="添加"
      @confirm="addPrint"
      @cancel="printShow = false"
    >
      <view class="slot-content">
        <u-form :model="form">
          <u-form-item label="名称">
            <u-input v-model="form.printName" />
          </u-form-item>
          <u-form-item label="IP">
            <u-input v-model="form.printIp" />
          </u-form-item>
          <u-form-item label="端口">
            <u-input v-model="form.printPort" type="number" />
          </u-form-item>
        </u-form>
      </view>
    </u-modal>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import nx from '@/nx'

// 响应式数据
const printShow = ref(false)
const printList = ref([])

const form = ref({
  printName: '',
  printIp: '',
  printPort: 22333
})

const options = [
  {
    text: '删除',
    style: {
      fontSize: '14px',
      backgroundColor: 'rgb(255,58,49)'
    }
  }
]

// 方法
const addPrintShow = () => {
  if (printList.value.length > 0) {
    uni.showToast({
      title: '已存在打印服务！',
      icon: 'none'
    })
    return
  }
  form.value = {
    printName: '',
    printIp: '',
    printPort: 22333
  }
  printShow.value = true
}

const refreshPrint = () => {
  const printListData = uni.getStorageSync('KEY_PRINT_LIST') || []
  if (printListData.length > 0) {
    printListData.forEach(print => {
      nx.$print.open(print.printIp)
    })
    uni.showToast({
      title: '刷新成功！',
      icon: 'none'
    })
  } else {
    uni.showModal({
      title: '提示',
      content: '未配置打印服务，请点击右边的“+”配置打印服务！',
      showCancel: false
    })
  }
}

const addPrint = () => {
  const { printName, printIp, printPort } = form.value

  if (!printName.trim()) {
    uni.showToast({ title: '打印服务名称不允许为空！', icon: 'none' })
    return
  }
  if (!printIp.trim()) {
    uni.showToast({ title: '打印服务IP不允许为空！', icon: 'none' })
    return
  }

  const ipReg =
    /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
  if (!ipReg.test(printIp)) {
    uni.showToast({ title: '打印服务IP不正确！', icon: 'none' })
    return
  }

  let storedList = uni.getStorageSync('KEY_PRINT_LIST') || []
  const exists = storedList.some(p => p.printIp === printIp)
  if (exists) {
    uni.showToast({ title: '打印服务已存在！', icon: 'none' })
    return
  }

  storedList.push({
    printName,
    printIp,
    printPort,
    isDefault: storedList.length === 0
  })

  nx.$print.open(printIp)
  uni.setStorageSync('KEY_PRINT_LIST', storedList)
  refreshList()
  printShow.value = false
}

const printSwipeClick = ({ index }) => {
  if (index === 0) {
    const delPrint = printList.value[index]
    nx.$print.close(delPrint.printIp)

    printList.value.splice(index, 1)

    if (delPrint.isDefault && printList.value.length > 0) {
      printList.value[0].isDefault = true
    }

    uni.setStorageSync('KEY_PRINT_LIST', printList.value)
    uni.showToast({ title: '删除成功！', icon: 'none' })
  }
}

const refreshList = () => {
  const stored = uni.getStorageSync('KEY_PRINT_LIST') || []
  printList.value = stored.map(print => {
    const printer = nx.$print.printMap?.get(print.printIp)
    return {
      ...print,
      isOpen: printer ? printer.isOpen : false
    }
  })
}

// 生命周期
onMounted(() => {
  refreshList()
  uni.$on('printStatus', refreshList)
})

onUnmounted(() => {
  uni.$off('printStatus', refreshList)
})
</script>

<style lang="scss" scoped>
.navbar-right {
  margin-right: 12px;
  display: flex;
}

.right-item {
  margin: 0 6px;
  position: relative;
  color: #ffffff;
  display: flex;
}

.slot-content {
  font-size: 14px;
  color: $u-content-color;
  padding-left: 15px;
  padding-right: 15px;
}

.item {
  display: flex;
  padding: 20rpx;
}

image {
  width: 60px;
  flex: 0 0 60px;
  height: 60px;
  margin-right: 10px;
  border-radius: 6px;
}
</style>
