<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 {
    const id = Date.now() + ''
    projectList.value.unshift({
      name: values.newProjectName,
      id,
      time: new Date().toLocaleString(),
      commandList: [
        {
          id: Date.now() + '',
          name: '任务1',
          parentId: id,
          stepList: [],
          time: new Date().toLocaleString(),
          // x: 100,
          // y: 100
        }
      ],
      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
  const inputEl = document.createElement('input')
  inputEl.type = 'file'
  inputEl.accept = '.jmpec'
  inputEl.onchange = (e) => {
    console.dir(e.target!)
    if (!e.target) return
    const files = (e.target as HTMLInputElement).files
    if (!files || !files?.length) return
    const file = files[0]
    const fileType = file.name.slice(-6)
    if (fileType !== '.jmpec') return showFailToast('文件类型错误！')
    const reader = new FileReader()
    reader.onload = (e) => {
      if (!e.target) return
      const projectStr = e.target.result as string
      console.log(projectStr)
      try {
        const newProject = JSON.parse(projectStr)
        if (newProject.qrcodeType !== 'worldflying_plc_editor') return showFailToast('导入失败！')
        const isExist = projectList.value.some((item) => item.name === newProject.name)
        if (isExist) {
          showFailToast('工程名称已存在')
          return
        }
        newProject.id = Date.now() + ''
        newProject.time = new Date().toLocaleString()
        newProject.isCompiled = false
        newProject.CompileTime = ''
        projectList.value.unshift(newProject)
        showSuccessToast('导入成功')
      } catch (error) {
        showFailToast('导入失败')
      }
    }
    reader.readAsText(file)
  }
  inputEl.click()
  inputEl.remove()

  // 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('扫描失败')
  //       const isExist = projectList.value.some((item) => item.name === newProject.name)
  //       if (isExist) {
  //         showFailToast('工程名称已存在')
  //         return
  //       }
  //       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>
