<template>
  <div class="automate-container">
    <div class="header">
      <div class="title">
        <template v-if="!touchStatus">我的工程</template>
        <template v-else>
          <div class="back" @click="touchStatus = false"><van-icon name="arrow-left" />返回工程</div></template
        >
      </div>
      <div class="btn-group">
        <van-button v-show="!touchStatus" size="small" type="warning" @click="importProject" style="margin-right: 8px"
          >工程导入</van-button
        >
        <van-button v-show="!touchStatus" size="small" type="primary" @click="popupShow = true">新建工程</van-button>
      </div>
    </div>

    <div class="project-container">
      <van-checkbox-group v-model="checked" @change="handleCheckedChange">
        <van-swipe-cell v-for="item in projectList" :key="item.id" :disabled="touchStatus">
          <van-cell
            clickable
            :border="false"
            :title="item.name"
            :label="item.time"
            @click="!touchStatus && router.push(`/project-info/${item.id}`)"
            @touchstart="handleTouchStart"
            @touchmove="handleTouchMove"
            @touchend="handleTouchEnd"
          >
            <template #value>
              <van-checkbox :name="item.id" @click.stop="" shape="square" v-show="touchStatus"></van-checkbox>
            </template>
          </van-cell>
          <template #right>
            <van-button square type="danger" text="删除" class="del-button" @click="handleDelete([item.id])" />
          </template>
        </van-swipe-cell>
      </van-checkbox-group>
    </div>

    <div class="del-btn" v-show="touchStatus">
      <van-button type="danger" block @click="handleDelete(checked)">删除文件</van-button>
    </div>

    <van-popup v-model:show="popupShow" round :style="{ width: '80%' }">
      <div class="label" style="margin: 16px">新建工程</div>
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-field
            border
            v-model="newProjectName"
            name="newProjectName"
            placeholder="工程名称"
            maxlength="20"
            :rules="[{ required: true, message: '请填写工程名称' }]"
          />
        </van-cell-group>
        <div class="van-button-group">
          <van-button @click="handleCancel" size="small">取消</van-button>
          <van-button type="primary" native-type="submit" size="small">确定</van-button>
        </div>
      </van-form>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { useGlobalStore } from '@/stores/global'
import { storeToRefs } from 'pinia'

const { projectList } = storeToRefs(useGlobalStore())
const router = useRouter()

const checked = ref([])

const handleCheckedChange = (names: string[]) => {
  console.log(names)
}

let touchTimer: any
const touchStatus = ref(false)
const handleTouchStart = () => {
  touchTimer = setTimeout(() => {
    touchStatus.value = true
  }, 700)
}
const handleTouchMove = () => {
  if (touchTimer) {
    clearTimeout(touchTimer)
    touchTimer = 0
  }
}
const handleTouchEnd = () => {
  if (touchTimer) {
    clearTimeout(touchTimer)
    touchTimer = 0
  }
}

const handleDelete = (val: string[]) => {
  if (val.length) {
    projectList.value = projectList.value.filter((item) => !val.includes(item.id))
    checked.value = []
    if (projectList.value.length === 0) {
      touchStatus.value = false
    }
  }
}

const popupShow = ref(false)
const newProjectName = ref('')
const onSubmit = (values: Record<string, string>) => {
  console.log(values)
  const isExist = projectList.value.some((item) => item.name === values.newProjectName)
  if (isExist) {
    showFailToast('工程名称已存在')
    return
  } else {
    projectList.value.unshift({
      name: values.newProjectName,
      id: Date.now() + '',
      time: new Date().toLocaleString(),
      commandList: [],
      isCompiled: false,
      CompileTime: ''
    })
    handleCancel()
  }
}
const handleCancel = async () => {
  popupShow.value = false
  await nextTick()
  newProjectName.value = ''
}

const wx = window.wx
const initWxEnv = () => {
  if (!window.isInWx) return showFailToast('请在微信中打开')
  const url = location.origin + location.pathname + location.search
  const wxConfigStr = localStorage.getItem(url)
  if (!wxConfigStr) showFailToast('初始化失败')
  else {
    const wxConfig = JSON.parse(wxConfigStr)
    wx.config(wxConfig)
    wx.ready(function () {
      console.log('微信初始化成功')
    })
    wx.error(function (res: any) {
      console.log('微信初始化失败', res)
    })
  }
}
initWxEnv()
const importProject = () => {
  if (!window.isInWx) return
  wx.scanQRCode({
    needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
    scanType: ['qrCode', 'barCode'], // 可以指定扫二维码还是一维码，默认二者都有
    success: function (res: any) {
      if (res.errMsg !== 'scanQRCode:ok') return showFailToast('扫描失败')
      const projectStr = res.resultStr
      try {
        const newProject = JSON.parse(projectStr)
        if (newProject.qrcodeType !== 'worldflying_plc_editor') return showFailToast('扫描失败')
        newProject.id = Date.now() + ''
        newProject.time = new Date().toLocaleString()
        newProject.isCompiled = false
        newProject.CompileTime = ''
        projectList.value.unshift(newProject)
        showSuccessToast('导入成功')
      } catch (error) {
        showFailToast('扫描失败')
      }
    }
  })
}
</script>

<style scoped>
.automate-container {
  padding: 16px 0 0;
  height: 100%;
  overflow: hidden;
}
.header {
  padding: 0 16px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.del-button {
  height: 100%;
}
.van-cell {
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2px;
  gap: 16px;
}
.project-container {
  height: calc(100% - 48px);
  padding-bottom: 16px;
  overflow: auto;
}
.project-container :deep(.van-cell__value) {
  width: 32px;
  flex: none;
}
.project-container :deep(.van-cell__title) {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.del-btn {
  position: fixed;
  bottom: 84px;
  left: 50%;
  transform: translateX(-50%);
  width: 70%;
}
:deep(.van-field) {
  padding-left: 0;
}
:deep(.van-field__body) {
  border-bottom: 1px solid #eaeaea;
}
.van-button-group {
  margin: 16px;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
</style>
