<template>
  <div class="project-info">
    <div class="header">
      <div class="go-back" @click="router.replace({ name: 'Automate' })">
        <van-button size="small"><van-icon name="arrow-left" />返回</van-button>
      </div>
      <div class="project-name">
        <div class="name">
          {{ crtProject!.name }}
        </div>
        <van-tag type="primary" v-show="crtProject?.isCompiled" size="medium">已编译</van-tag>
        <van-tag type="warning" v-show="!crtProject?.isCompiled" size="medium">未编译</van-tag>
      </div>
      <div class="more"><van-button type="primary" size="small" @click="showMorePopup = true">更多</van-button></div>
    </div>

    <div class="command-container">
      <van-swipe-cell v-for="item in crtProject!.commandList" :key="item.id" :disabled="touchStatus">
        <van-cell
          clickable
          :border="false"
          :title="item.name"
          :label="item.time"
          @click="!touchStatus && router.push(`/command-info/${crtProject!.id}/${item.id}`)"
          @touchstart="handleTouchStart"
          @touchmove="handleTouchMove"
          @touchend="handleTouchEnd"
        >
        </van-cell>
        <template #right>
          <van-button square type="danger" text="删除" class="del-button" @click="handleDelete(item.id)" />
        </template>
      </van-swipe-cell>
    </div>
    <div class="add-btn">
      <van-button type="primary" block @click="handleAddCommond">添加任务</van-button>
    </div>

    <van-popup v-model:show="showMorePopup" position="right" :style="{ width: '50%', height: '100%' }">
      <van-cell-group :style="{ marginTop: '16px' }">
        <van-cell title="编辑工程名称" clickable @click="handleEditName" :title-style="{ color: '#07c160' }" />
        <van-cell title="编译文件" @click="getXMLFile" clickable :title-style="{ color: '#1989fa' }" />
        <van-cell clickable v-show="crtProject?.isCompiled">
          <template #title>
            <div v-html="wxtag"></div>
          </template>
        </van-cell>
        <van-cell title="删除工程" @click="delProject" clickable :title-style="{ color: '#fd5632' }" />
        <van-cell title="分享" @click="shareProject" clickable />
      </van-cell-group>
    </van-popup>

    <van-popup v-model:show="showEditPopup" 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>

    <van-popup v-model:show="showSharePopup" round :style="{ width: '80%' }">
      <div class="share-container">
        <!-- <canvas ref="qrcodeCanvas"></canvas> -->
        <img :src="shareImg" alt="" width="100%" />
        <div class="tip">长按图片进行分享</div>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { useGlobalStore } from '@/stores/global'
import type { CommandType, ProjectType } from '@/types/global'
import { formatDateTime, deepEqual, deepClone } from '@/utils/tools'
import { storeToRefs } from 'pinia'
import { v4 as uuid4 } from 'uuid'
import { showConfirmDialog, showLoadingToast, showFailToast } from 'vant'
import qrcode from 'qrcode'

const route = useRoute()
const router = useRouter()

const { projectList } = storeToRefs(useGlobalStore())
const crtProject = ref<ProjectType>()

const wxtag = ref('')

let wx = window.wx
// fetch('https://plceditor.worldflying.cn/api/build/getjsconfig', {
//   method: 'POST',
//   body: JSON.stringify({ url: location.origin + location.pathname + location.search })
// })
//   .then((res) => res.json())
//   .then((res) => {
//     wx.config(res.data)
//     wx.ready(function () {
//       console.log('微信初始化成功')
//       showWxAppBtn.value = true
//     })
//     wx.error(function (res: any) {
//       console.log('微信初始化失败', res)
//     })
//   })
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()

watch(
  () => route,
  () => {
    crtProject.value = projectList.value.find((item) => item.id === route.params.id)
    let imgobjStr = localStorage.getItem('imgobj' + crtProject.value!.id)
    if (imgobjStr) {
      try {
        let imgobj = JSON.parse(imgobjStr)
        let now = new Date().getTime() // 当前时间戳
        if (now < imgobj.deadline) {
          crtProject.value!.isCompiled = true
          wxtag.value = `<wx-open-launch-weapp appid="wx4c5a777c71f2981c" path="pages/index/rj45cfgbybt/plc/index?imgurl=${imgobj.url}"><template><text style="color: #7232dd">烧录设备</text></template></wx-open-launch-weapp>`
        } else {
          crtProject.value!.isCompiled = false
          localStorage.removeItem('imgobj' + crtProject.value!.id)
        }
      } catch (e) {
        console.log(e)
      }
    }
  },
  {
    deep: true,
    immediate: true,
    once: true
  }
)

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 showMorePopup = ref(false)
const handleEditName = () => {
  showEditPopup.value = true
  showMorePopup.value = false
  newProjectName.value = crtProject.value!.name
}

const showEditPopup = 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 {
    crtProject.value!.name = values.newProjectName
    handleCancel()
  }
}
const handleCancel = async () => {
  showEditPopup.value = false
  await nextTick()
  newProjectName.value = ''
}

const handleDelete = (val: string) => {
  if (val) {
    const project = projectList.value.find((item) => (item.id = crtProject.value!.id))
    if (project) {
      project.commandList = project.commandList.filter((item) => item.id !== val)
      if (crtProject.value?.isCompiled) {
        crtProject.value.isCompiled = false
        localStorage.removeItem('imgobj' + crtProject.value!.id)
      }
    }
  }
}

const handleAddCommond = () => {
  let name = `任务${crtProject.value!.commandList.length + 1}`
  if (crtProject.value!.commandList.length) {
    const beforeName = crtProject.value!.commandList[crtProject.value!.commandList.length - 1].name
    const index = beforeName.split('任务')[1]
    name = `任务${+index + 1}`
  }
  crtProject.value!.commandList.push({
    id: '' + Date.now(),
    name,
    time: new Date().toLocaleString(),
    stepList: [],
    x: 100,
    y: 100 + crtProject.value!.commandList.length * 2000,
    parentId: crtProject.value!.id
  })
  if (crtProject.value?.isCompiled) {
    crtProject.value.isCompiled = false
    localStorage.removeItem('imgobj' + crtProject.value!.id)
  }
}

// 文件编译
const getXMLFile = () => {
  if (!crtProject.value) return
  if (crtProject.value.commandList.length === 0) return showFailToast('请先添加任务!')
  if (crtProject.value.commandList.length === 1 && crtProject.value.commandList[0].stepList.length === 0) {
    return showFailToast('任务内容为空!')
  }
  if (crtProject.value.isCompiled) {
    return showFailToast('工程已编译!')
  }
  const isExistExec = crtProject.value.commandList.some((item) =>
    item.stepList.some((cItem) => cItem.type === 'exec' && cItem.list?.length !== 0)
  )
  if (!isExistExec) return showFailToast('请先添加执行任务!')
  const loading = showLoadingToast({
    message: '正在编译中...',
    forbidClick: true,
    duration: 0
  })
  let xml = ''
  // 头部
  xml += `<?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://www.plcopen.org/xml/tc6_0201" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:ns1="http://www.plcopen.org/xml/tc6.xsd">
      <fileHeader companyName="${'未知'}" productName="${'未命名'}" productVersion="1.0" creationDateTime="${formatDateTime(new Date(), 'T')}" />
      <contentHeader name="${crtProject.value.name}" modificationDateTime="${formatDateTime(new Date(), 'T')}">
        <coordinateInfo>
          <fbd>
            <scaling x="10" y="10"/>
          </fbd>
          <ld>
            <scaling x="10" y="10"/>
          </ld>
          <sfc>
            <scaling x="10" y="10"/>
          </sfc>
        </coordinateInfo>
      </contentHeader>
      <types>
        <dataTypes/>
        <pous>
        `
  // <pou name="proogram0" pouType="program">
  //   <interface>
  // <localVars>

  const commandVarMap: Record<string, string> = {}

  const weekMap: Record<string, number> = {
    周一: 4,
    周二: 5,
    周三: 6,
    周四: 0,
    周五: 1,
    周六: 2,
    周日: 3
  }

  const globalVarList = [
    'DI0',
    'DI1',
    'DI2',
    'DI3',
    'DI4',
    'DI5',
    'DI6',
    'DI7',
    'DI8',
    'DI9',
    'AI0',
    'AI1',
    'AI2',
    'AI3',
    'DO0',
    'DO1',
    'DO2',
    'DO3',
    'DO4',
    'DO5',
    'DO6',
    'DO7',
    'DO8',
    'DO9',
    'AO0',
    'AO1'
  ]

  let instanceXml = ''
  let globalVarsXml = ''
  globalVarList.forEach((item) => {
    globalVarsXml += `<variable name="${item}">
                        <type><${item.includes('A') ? 'INT' : 'BOOL'} /></type>
                      </variable>`
  })
  crtProject.value.commandList.forEach((item, index) => {
    if (!item.stepList.some((cItem) => cItem.type === 'exec' && cItem.list?.length !== 0)) return
    instanceXml += `<pouInstance name="instance${index}" typeName="program${index}"/>`
    xml += `<pou name="program${index}" pouType="program">
              <interface>
                <externalVars>
                ${globalVarsXml}
                    <variable name="CRT_DATA">
                      <type><DT /></type>
                    </variable>
                </externalVars>
                <localVars>
                  <variable name="MOD_HOUR">
                    <type><ULINT /></type>
                    <initialValue>
                      <simpleValue value="24" />
                    </initialValue>
                  </variable>
                  <variable name="HOURS">
                    <type><ULINT /></type>
                    <initialValue>
                      <simpleValue value="3600" />
                    </initialValue>
                  </variable>
                  <variable name="DAYS">
                    <type><ULINT /></type>
                    <initialValue>
                      <simpleValue value="86400" />
                    </initialValue>
                  </variable>
                  <variable name="MOD_WEEK">
                    <type><ULINT /></type>
                    <initialValue>
                      <simpleValue value="7" />
                    </initialValue>
                  </variable>
                  <variable name="MINUTE">
                    <type><ULINT /></type>
                    <initialValue>
                      <simpleValue value="60" />
                    </initialValue>
                  </variable>
                  <variable name="MUL_NUM">
                    <type><INT /></type>
                    <initialValue>
                      <simpleValue value="1" />
                    </initialValue>
                  </variable>
                `
    // 临时变量
    // const tempVarNum = item.stepList.filter((cItem) => cItem.type === 'condition').length
    const tempVarNum = item.stepList.length
    for (let i = 1; i <= tempVarNum; i++) {
      xml += `<variable name="temp${i - 1}">
                <type><BOOL /></type>
              </variable>`
    }
    // 定义所需变量
    item.stepList.forEach((item, index) => {
      if (item.type === 'delay') {
        // RTC 数量
        xml += `<variable name="TON${index}">
                  <type>
                    <derived name="TON" />
                  </type>
                </variable>
                <variable name="PT${index}">
                  <type>
                    <TIME />
                  </type>
                  <initialValue>
                    <simpleValue value="T#${item.value}s" />
                  </initialValue>
                </variable>`
      } else {
        item.list?.forEach((cItem, cIndex) => {
          // PT 数量
          if (cItem.type === 'time') {
            xml += `<variable name="RTC${index}_${cIndex}">
                      <type>
                        <derived name="RTC" />
                      </type>
                    </variable>`
            const timeArr = cItem.value.split(':')
            xml += `<variable name="HOUR${index}_${cIndex}">
                      <type><ULINT /></type>
                        <initialValue>
                          <simpleValue value="${+timeArr[0]}" />
                        </initialValue>
                    </variable>`
            xml += `<variable name="MIN${index}_${cIndex}">
                      <type><ULINT /></type>
                        <initialValue>
                          <simpleValue value="${+timeArr[1]}" />
                        </initialValue>
                    </variable>`
            if (Object.keys(weekMap).includes(cItem.label)) {
              xml += `<variable name="RTC${index}_${cIndex}_WEEK">
                        <type><ULINT /></type>
                        <initialValue>
                          <simpleValue value="${weekMap[cItem.label]}" />
                        </initialValue>
                      </variable>`
            } else if (cItem.label !== '每天') {
              const timeArr = cItem.value.split('-')
              xml += `<variable name="RTC${index}_${cIndex}_START">
                        <type><ULINT /></type>
                        <initialValue>
                          <simpleValue value="${new Date(timeArr[0] + '').getTime() / 1000}" />
                        </initialValue>
                      </variable>`
              xml += `<variable name="RTC${index}_${cIndex}_END">
                        <type><ULINT /></type>
                        <initialValue>
                          <simpleValue value="${new Date(timeArr[2] + '').getTime() / 1000}" />
                        </initialValue>
                      </variable>`
            }
          } else if (cItem.type === 'input' && cItem.label.includes('AI')) {
            // 判断AI变量
            xml += `<variable name="COMPARE_AI${index}_${cIndex}">
                      <type><INT /></type>
                      <initialValue>
                        <simpleValue value="${cItem.value}" />
                      </initialValue>
                    </variable>`
          } else if (cItem.type === 'output' && cItem.label.includes('AO')) {
            // 赋值AO变量
            xml += `<variable name="SET_AI${index}_${cIndex}">
                      <type><INT /></type>
                      <initialValue>
                        <simpleValue value="${cItem.value}" />
                      </initialValue>
                    </variable>`
          }
        })
      }
    })

    xml += `</localVars></interface>`
    xml += `<body><LD>`

    // 左侧电源导轨
    const firstStep = item.stepList[0]
    // const powerRailH = firstStep.type === 'delay' ? 40 : 40 + 20 * firstStep.list!.length
    xml += `<leftPowerRail localId="${item.id}"  width="20" height="40">
        <position x="${item.x}" y="${item.y}"/>`
    // if (firstStep.type === 'delay') {
    xml += `<connectionPointOut formalParameter="">`
    xml += `<relPosition x="40" y="20"/>`
    xml += `</connectionPointOut>`
    // } else {
    //   for (let i = 1; i <= firstStep.list!.length; i++) {
    //     xml += `<connectionPointOut formalParameter="">`
    //     xml += `<relPosition x="20" y="${20 * i}"/>`
    //     xml += `</connectionPointOut>`
    //   }
    // }
    xml += `</leftPowerRail>`

    let tempVarId = `99${index}`
    item.stepList.forEach((sItem, sIndex) => {
      let tempXML = ''
      let tempConnectXML = ''
      if (sItem.type === 'condition' || sItem.type === 'exec') {
        for (let i = 0; i < sItem.list!.length; i++) {
          const cItem = sItem.list![i]
          if (cItem.label.includes('DI') || cItem.label.includes('DO')) {
            xml += `<${cItem.label.includes('DI') ? 'contact' : 'coil'} localId="${cItem.id}" negated="${cItem.value === '打开'}" width="40" height="40">`
            xml += `<position x="${cItem.x}" y="${cItem.y}" />
            <connectionPointIn>
              <relPosition x="-20" y="20" />
              <connection refLocalId="${sIndex === 0 ? item.id : tempVarId}">
                <position x="${sIndex === 0 ? item.x + 40 : sItem.x - 40}" y="${sItem.y + 20}" />
                <position x="${cItem.x - 20}" y="${cItem.y + 20}" />
              </connection>
            </connectionPointIn>
            <connectionPointOut>
              <relPosition x="60" y="20"/>
            </connectionPointOut>
            <variable>${cItem.label}</variable>
            `
            xml += `</${cItem.label.includes('DI') ? 'contact' : 'coil'}>`

            tempConnectXML += `
              <connection refLocalId="${cItem.id}" >
                <position x="${cItem.x + 60}" y="${cItem.y + 20}" />
                <position x="${sItem.x - 120}" y="${sItem.y + 20}" />
              </connection>`
          } else if (cItem.type === 'time') {
            let setTimeVarID = `${index + 1}${sIndex}${i}11`
            // 赋值当前时间
            xml += `
            <inVariable localId="${setTimeVarID}" width="40" height="40" negated="false">
              <position x="${cItem.x - 100}" y="${cItem.y + 200}" />
              <connectionPointOut>
                <relPosition x="60" y="20" />
              </connectionPointOut>
              <expression>CRT_DATA</expression>
            </inVariable>`
            let RTCID1 = `${index + 1}${sIndex}${i}12`
            // 定义RTC变量
            xml += `
            <block
              localId="${RTCID1}"
              typeName="RTC"
              instanceName="RTC${sIndex}_${i}"
              width="80"
              height="80"
            >
              <position x="${cItem.x}" y="${cItem.y}" />
              <inputVariables>
                <variable formalParameter="IN">
                  <connectionPointIn>
                    <relPosition x="-20" y="20" />
                    <connection refLocalId="${sIndex === 0 ? item.id : tempVarId}">
                      <position x="${sIndex === 0 ? item.x + 40 : sItem.x - 40}" y="${sItem.y + 20}" />
                      <position x="${cItem.x - 20}" y="${cItem.y + 20}" />
                    </connection>
                  </connectionPointIn>
                </variable>
                <variable formalParameter="PDT">
                  <connectionPointIn>
                    <relPosition x="-20" y="60" />
                    <connection refLocalId="${setTimeVarID}">
                      <position x="${cItem.x - 40}" y="${cItem.y + 220}" />
                      <position x="${cItem.x - 20}" y="${cItem.y + 60}" />
                    </connection>
                  </connectionPointIn>
                </variable>
              </inputVariables>
              <inOutVariables />
              <outputVariables>
                <variable formalParameter="Q">
                  <connectionPointOut>
                    <relPosition x="100" y="20" />
                  </connectionPointOut>
                </variable>
                <variable formalParameter="CDT">
                  <connectionPointOut>
                    <relPosition x="100" y="60" />
                  </connectionPointOut>
                </variable>
              </outputVariables>
            </block>
            `

            // DT TO ULINGT
            let dtToULIntId1 = `${index + 1}${sIndex}${i}13`
            xml += `
            <block localId="${dtToULIntId1}" typeName="DT_TO_ULINT" width="100" height="40">
              <position x="${cItem.x + 200}" y="${cItem.y}" />
              <inputVariables>
                <variable formalParameter="IN">
                  <connectionPointIn>
                    <relPosition x="-20" y="20" />
                    <connection refLocalId="${RTCID1}" formalParameter="CDT">
                      <position x="${cItem.x + 100}" y="${cItem.y + 60}" />
                      <position x="${cItem.x + 180}" y="${cItem.y + 20}" />
                    </connection>
                  </connectionPointIn>
                </variable>
              </inputVariables>
              <inOutVariables />
              <outputVariables>
                <variable formalParameter="OUT">
                  <connectionPointOut>
                    <relPosition x="120" y="20" />
                  </connectionPointOut>
                </variable>
              </outputVariables>
            </block>`

            let joinXML = ''
            let isJoin = false

            if (Object.keys(weekMap).includes(cItem.label)) {
              isJoin = true
              let varId6 = `${index + 1}${sIndex}${i}14`
              // 天被除数变量
              xml += `
                <inVariable localId="${varId6}" width="40" height="40" negated="false">
                  <position x="${cItem.x + 300}" y="${cItem.y + 200}" />
                  <connectionPointOut>
                    <relPosition x="60" y="20" />
                  </connectionPointOut>
                  <expression>DAYS</expression>
                </inVariable>`
              let DIVID3 = `${index + 1}${sIndex}${i}15`
              // 计算天数
              xml += `
                <block localId="${DIVID3}" typeName="DIV" width="70" height="60">
                  <position x="${cItem.x + 400}" y="${cItem.y}" />
                  <inputVariables>
                    <variable formalParameter="IN1">
                      <connectionPointIn>
                        <relPosition x="-20" y="20" />
                        <connection refLocalId="${dtToULIntId1}" formalParameter="OUT">
                          <position x="${cItem.x + 320}" y="${cItem.y + 20}" />
                          <position x="${cItem.x + 380}" y="${cItem.y + 20}" />
                        </connection>
                      </connectionPointIn>
                    </variable>
                    <variable formalParameter="IN2">
                      <connectionPointIn>
                        <relPosition x="-20" y="40" />
                        <connection refLocalId="${varId6}">
                          <position x="${cItem.x + 360}" y="${cItem.y + 220}" />
                          <position x="${cItem.x + 380}" y="${cItem.y + 40}" />
                        </connection>
                      </connectionPointIn>
                    </variable>
                  </inputVariables>
                  <inOutVariables />
                  <outputVariables>
                    <variable formalParameter="OUT">
                      <connectionPointOut>
                        <relPosition x="90" y="20" />
                      </connectionPointOut>
                    </variable>
                  </outputVariables>
                </block>
                `
              let varId7 = `${index + 1}${sIndex}${i}16`
              // 取模变量
              xml += `
                <inVariable localId="${varId7}" width="40" height="40" negated="false">
                  <position x="${cItem.x + 500}" y="${cItem.y + 200}" />
                  <connectionPointOut>
                    <relPosition x="60" y="20" />
                  </connectionPointOut>
                  <expression>MOD_WEEK</expression>
                </inVariable>`
              let MODID4 = `${index + 1}${sIndex}${i}17`
              // 计算当前为周几 0为周四
              xml += `
                <block localId="${MODID4}" typeName="MOD" width="70" height="60">
                  <position x="${cItem.x + 600}" y="${cItem.y}" />
                  <inputVariables>
                    <variable formalParameter="IN1">
                      <connectionPointIn>
                        <relPosition x="-20" y="20" />
                        <connection refLocalId="${DIVID3}" formalParameter="OUT">
                          <position x="${cItem.x + 490}" y="${cItem.y + 20}" />
                          <position x="${cItem.x + 580}" y="${cItem.y + 20}" />
                        </connection>
                      </connectionPointIn>
                    </variable>
                    <variable formalParameter="IN2">
                      <connectionPointIn>
                        <relPosition x="-20" y="40" />
                        <connection refLocalId="${varId7}">
                          <position x="${cItem.x + 560}" y="${cItem.y + 220}" />
                          <position x="${cItem.x + 580}" y="${cItem.y + 40}" />
                        </connection>
                      </connectionPointIn>
                    </variable>
                  </inputVariables>
                  <inOutVariables />
                  <outputVariables>
                    <variable formalParameter="OUT">
                      <connectionPointOut>
                        <relPosition x="90" y="20" />
                      </connectionPointOut>
                    </variable>
                  </outputVariables>
                </block>
                `
              // 设置的周几变量
              let weekVarId = `${index + 1}${sIndex}${i}18`
              xml += `
                <inVariable localId="${weekVarId}" width="40" height="40" negated="false">
                  <position x="${cItem.x + 700}" y="${cItem.y + 200}" />
                  <connectionPointOut>
                    <relPosition x="60" y="20" />
                  </connectionPointOut>
                  <expression>RTC${sIndex}_${i}_WEEK</expression>
                </inVariable>`
              let GTID3 = `${index + 1}${sIndex}${i}19`
              // 判断是否为指定的周几(等于)
              xml += `
                <block localId="${GTID3}" typeName="EQ" width="70" height="60">
                  <position x="${cItem.x + 800}" y="${cItem.y}" />
                  <inputVariables>
                    <variable formalParameter="IN1">
                      <connectionPointIn>
                        <relPosition x="-20" y="20" />
                        <connection refLocalId="${MODID4}" formalParameter="OUT">
                          <position x="${cItem.x + 690}" y="${cItem.y + 20}" />
                          <position x="${cItem.x + 780}" y="${cItem.y + 20}" />
                        </connection>
                      </connectionPointIn>
                    </variable>
                    <variable formalParameter="IN2">
                      <connectionPointIn>
                        <relPosition x="-20" y="40" />
                        <connection refLocalId="${weekVarId}">
                          <position x="${cItem.x + 760}" y="${cItem.y + 20}" />
                          <position x="${cItem.x + 780}" y="${cItem.y + 20}" />
                        </connection>
                      </connectionPointIn>
                    </variable>
                  </inputVariables>
                  <inOutVariables />
                  <outputVariables>
                    <variable formalParameter="OUT">
                      <connectionPointOut>
                        <relPosition x="90" y="20" />
                      </connectionPointOut>
                    </variable>
                  </outputVariables>
                </block>
                `

              joinXML += `
                  <variable formalParameter="EN">
                    <connectionPointIn>
                      <relPosition x="-20" y="20" />
                      <connection refLocalId="${GTID3}" formalParameter="OUT">
                        <position x="${cItem.x + 890}" y="${cItem.y + 20}" />
                        <position x="${cItem.x + 980}" y="${cItem.y + 20}" />
                      </connection>
                    </connectionPointIn>
                  </variable>
                `
            } else if (cItem.label !== '每天') {
              isJoin = true
              // 判断是否再日期范围内
              let startTimeID = `${index + 1}${sIndex}37`
              let endTimeID = `${index + 1}${sIndex}36`
              // 开始时间变量
              xml += `
                <inVariable localId="${startTimeID}" width="40" height="40" negated="false">
                  <position x="${cItem.x + 300}" y="${cItem.y + 200}" />
                  <connectionPointOut>
                    <relPosition x="60" y="20" />
                  </connectionPointOut>
                  <expression>RTC${sIndex}_${i}_START</expression>
                </inVariable>`
              // 大于等于最小值
              let GEID1 = `${index + 1}${sIndex}35`
              xml += `
                <block localId="${GEID1}" typeName="GE" width="70" height="60">
                  <position x="${cItem.x + 400}" y="${cItem.y}" />
                  <inputVariables>
                    <variable formalParameter="IN1">
                      <connectionPointIn>
                        <relPosition x="-20" y="20" />
                        <connection refLocalId="${dtToULIntId1}" formalParameter="OUT">
                          <position x="${cItem.x + 320}" y="${cItem.y + 20}" />
                          <position x="${cItem.x + 380}" y="${cItem.y + 20}" />
                        </connection>
                      </connectionPointIn>
                    </variable>
                    <variable formalParameter="IN2">
                      <connectionPointIn>
                        <relPosition x="-20" y="40" />
                        <connection refLocalId="${startTimeID}">
                          <position x="${cItem.x + 360}" y="${cItem.y + 220}" />
                          <position x="${cItem.x + 380}" y="${cItem.y + 40}" />
                        </connection>
                      </connectionPointIn>
                    </variable>
                  </inputVariables>
                  <inOutVariables />
                  <outputVariables>
                    <variable formalParameter="OUT">
                      <connectionPointOut>
                        <relPosition x="90" y="30" />
                      </connectionPointOut>
                    </variable>
                  </outputVariables>
                </block>
                `
              // 结束时间变量
              xml += `
                <inVariable localId="${endTimeID}" width="40" height="40" negated="false">
                  <position x="${cItem.x + 500}" y="${cItem.y + 200}" />
                  <connectionPointOut>
                    <relPosition x="60" y="20" />
                  </connectionPointOut>
                  <expression>RTC${sIndex}_${i}_END</expression>
                </inVariable>`
              // 小于等于最大值
              let LEID1 = `${index + 1}${sIndex}34`
              xml += `
                <block localId="${LEID1}" typeName="LE" width="70" height="60">
                  <position x="${cItem.x + 600}" y="${cItem.y}" />
                  <inputVariables>
                    <variable formalParameter="EN">
                      <connectionPointIn>
                        <relPosition x="-20" y="20" />
                        <connection refLocalId="${GEID1}" formalParameter="OUT">
                          <position x="${cItem.x + 490}" y="${cItem.y + 30}" />
                          <position x="${cItem.x + 580}" y="${cItem.y + 20}" />
                        </connection>
                      </connectionPointIn>
                    </variable>
                    <variable formalParameter="IN1">
                      <connectionPointIn>
                        <relPosition x="-20" y="40" />
                        <connection refLocalId="${dtToULIntId1}" formalParameter="OUT">
                          <position x="${cItem.x + 320}" y="${cItem.y + 20}" />
                          <position x="${cItem.x + 580}" y="${cItem.y + 40}" />
                        </connection>
                      </connectionPointIn>
                    </variable>
                    <variable formalParameter="IN2">
                      <connectionPointIn>
                        <relPosition x="-20" y="60" />
                        <connection refLocalId="${endTimeID}" formalParameter="OUT">
                          <position x="${cItem.x + 560}" y="${cItem.y + 220}" />
                          <position x="${cItem.x + 580}" y="${cItem.y + 60}" />
                        </connection>
                      </connectionPointIn>
                    </variable>
                  </inputVariables>
                  <inOutVariables />
                  <outputVariables>
                    <variable formalParameter="ENO">
                      <connectionPointOut>
                        <relPosition x="90" y="20" />
                      </connectionPointOut>
                    </variable>
                    <variable formalParameter="OUT">
                      <connectionPointOut>
                        <relPosition x="90" y="40" />
                      </connectionPointOut>
                    </variable>
                  </outputVariables>
                </block>
                `

              joinXML += `
                  <variable formalParameter="EN">
                    <connectionPointIn>
                      <relPosition x="-20" y="20" />
                      <connection refLocalId="${LEID1}" formalParameter="OUT">
                        <position x="${cItem.x + 690}" y="${cItem.y + 40}" />
                        <position x="${cItem.x + 980}" y="${cItem.y + 20}" />
                      </connection>
                    </connectionPointIn>
                  </variable>
                `
            }

            let varId2 = `${index + 1}${sIndex}${i}20`
            // 小时被除数
            xml += `
            <inVariable localId="${varId2}" width="40" height="40" negated="false">
              <position x="${cItem.x + 900}" y="${cItem.y + 200}" />
              <connectionPointOut>
                <relPosition x="60" y="20" />
              </connectionPointOut>
              <expression>HOURS</expression>
            </inVariable>`

            let DIVID1 = `${index + 1}${sIndex}${i}21`
            // 计算小时
            xml += `
            <block localId="${DIVID1}" typeName="DIV" width="70" height="60">
              <position x="${cItem.x + 1000}" y="${cItem.y}" />
              <inputVariables>
                ${joinXML}
                <variable formalParameter="IN1">
                  <connectionPointIn>
                    <relPosition x="-20" y="${isJoin ? 40 : 20}" />
                    <connection refLocalId="${dtToULIntId1}" formalParameter="OUT">
                      <position x="${cItem.x + 320}" y="${cItem.y + 20}" />
                      <position x="${cItem.x + 980}" y="${cItem.y + (isJoin ? 40 : 20)}" />
                    </connection>
                  </connectionPointIn>
                </variable>
                <variable formalParameter="IN2">
                  <connectionPointIn>
                    <relPosition x="-20" y="${isJoin ? 60 : 40}" />
                    <connection refLocalId="${varId2}">
                      <position x="${cItem.x + 960}" y="${cItem.y + 220}" />
                      <position x="${cItem.x + 980}" y="${cItem.y + (isJoin ? 60 : 40)}" />
                    </connection>
                  </connectionPointIn>
                </variable>
              </inputVariables>
              <inOutVariables />
              <outputVariables>
              ${
                isJoin
                  ? `<variable formalParameter="ENO">
                  <connectionPointOut>
                    <relPosition x="90" y="20" />
                  </connectionPointOut>
                </variable>`
                  : ''
              }
                <variable formalParameter="OUT">
                  <connectionPointOut>
                    <relPosition x="90" y="40" />
                  </connectionPointOut>
                </variable>
              </outputVariables>
            </block>
            `
            let varId3 = `${index + 1}${sIndex}${i}22`
            // 小时取模变量
            xml += `
            <inVariable localId="${varId3}" width="40" height="40" negated="false">
              <position x="${cItem.x + 1100}" y="${cItem.y + 200}" />
              <connectionPointOut>
                <relPosition x="60" y="20" />
              </connectionPointOut>
              <expression>MOD_HOUR</expression>
            </inVariable>`
            let MODID1 = `${index + 1}${sIndex}${i}23`
            // 计算当前时间为几点
            xml += `
            <block localId="${MODID1}" typeName="MOD" width="70" height="60">
              <position x="${cItem.x + 1200}" y="${cItem.y}" />
              <inputVariables>
                <variable formalParameter="IN1">
                  <connectionPointIn>
                    <relPosition x="-20" y="20" />
                    <connection refLocalId="${DIVID1}" formalParameter="OUT">
                      <position x="${cItem.x + 1090}" y="${cItem.y + 40}" />
                      <position x="${cItem.x + 1180}" y="${cItem.y + 20}" />
                    </connection>
                  </connectionPointIn>
                </variable>
                <variable formalParameter="IN2">
                  <connectionPointIn>
                    <relPosition x="-20" y="40" />
                    <connection refLocalId="${varId3}">
                      <position x="${cItem.x + 1160}" y="${cItem.y + 220}" />
                      <position x="${cItem.x + 1180}" y="${cItem.y + 40}" />
                    </connection>
                  </connectionPointIn>
                </variable>
              </inputVariables>
              <inOutVariables />
              <outputVariables>
                <variable formalParameter="OUT">
                  <connectionPointOut>
                    <relPosition x="90" y="20" />
                  </connectionPointOut>
                </variable>
              </outputVariables>
            </block>
            `
            // 设置的小时数变量
            let hourVarId = `${index + 1}${sIndex}${i}24`
            xml += `
            <inVariable localId="${hourVarId}" width="40" height="40" negated="false">
              <position x="${cItem.x + 1300}" y="${cItem.y + 200}" />
              <connectionPointOut>
                <relPosition x="60" y="20" />
              </connectionPointOut>
              <expression>HOUR${sIndex}_${i}</expression>
            </inVariable>`
            let GTID1 = `${index + 1}${sIndex}${i}25`
            // 判断小时数是否相等
            xml += `
            <block localId="${GTID1}" typeName="EQ" width="70" height="60">
              <position x="${cItem.x + 1400}" y="${cItem.y}" />
              <inputVariables>
                <variable formalParameter="IN1">
                  <connectionPointIn>
                    <relPosition x="-20" y="20" />
                    <connection refLocalId="${MODID1}" formalParameter="OUT">
                      <position x="${cItem.x + 1290}" y="${cItem.y + 20}" />
                      <position x="${cItem.x + 1380}" y="${cItem.y + 20}" />
                    </connection>
                  </connectionPointIn>
                </variable>
                <variable formalParameter="IN2">
                  <connectionPointIn>
                    <relPosition x="-20" y="40" />
                    <connection refLocalId="${hourVarId}" formalParameter="OUT">
                      <position x="${cItem.x + 1360}" y="${cItem.y + 220}" />
                      <position x="${cItem.x + 1380}" y="${cItem.y + 40}" />
                    </connection>
                  </connectionPointIn>
                </variable>
              </inputVariables>
              <inOutVariables />
              <outputVariables>
                <variable formalParameter="OUT">
                  <connectionPointOut>
                    <relPosition x="90" y="20" />
                  </connectionPointOut>
                </variable>
              </outputVariables>
            </block>
            `

            let varId4 = `${index + 1}${sIndex}${i}26`
            // 分钟被除数
            xml += `
            <inVariable localId="${varId4}" width="40" height="40" negated="false">
              <position x="${cItem.x + 1500}" y="${cItem.y + 200}" />
              <connectionPointOut>
                <relPosition x="60" y="20" />
              </connectionPointOut>
              <expression>MINUTE</expression>
            </inVariable>`
            let DIVID2 = `${index + 1}${sIndex}${i}27`
            // 计算分钟
            xml += `
            <block localId="${DIVID2}" typeName="DIV" width="70" height="60">
              <position x="${cItem.x + 1600}" y="${cItem.y}" />
              <inputVariables>
              <variable formalParameter="EN">
                  <connectionPointIn>
                    <relPosition x="-20" y="20"/>
                    <connection refLocalId="${GTID1}" formalParameter="OUT">
                      <position x="${cItem.x + 1490}" y="${cItem.y + 20}"/>
                      <position x="${cItem.x + 1580}" y="${cItem.y + 20}"/>
                    </connection>
                  </connectionPointIn>
                </variable>
                      <variable formalParameter="IN1">
                      <connectionPointIn>
                      <relPosition x="-20" y="40" />
                      <connection refLocalId="${dtToULIntId1}" formalParameter="OUT">
                      <position x="${cItem.x + 320}" y="${cItem.y + 20}" />
                      <position x="${cItem.x + 1580}" y="${cItem.y + 40}" />
                    </connection>
                  </connectionPointIn>
                </variable>
                <variable formalParameter="IN2">
                  <connectionPointIn>
                    <relPosition x="-20" y="60" />
                    <connection refLocalId="${varId4}">
                      <position x="${cItem.x + 1560}" y="${cItem.y + 220}" />
                      <position x="${cItem.x + 1580}" y="${cItem.y + 60}" />
                    </connection>
                  </connectionPointIn>
                </variable>
              </inputVariables>
              <inOutVariables />
              <outputVariables>
              <variable formalParameter="ENO">
                <connectionPointOut>
                  <relPosition x="90" y="20"/>
                </connectionPointOut>
              </variable>
                <variable formalParameter="OUT">
                  <connectionPointOut>
                    <relPosition x="90" y="40" />
                  </connectionPointOut>
                </variable>
              </outputVariables>
            </block>
            `
            let varId5 = `${index + 1}${sIndex}${i}28`
            // 取模变量
            xml += `
            <inVariable localId="${varId5}" width="40" height="40" negated="false">
              <position x="${cItem.x + 1700}" y="${cItem.y + 200}" />
              <connectionPointOut>
                <relPosition x="60" y="20" />
              </connectionPointOut>
              <expression>MINUTE</expression>
            </inVariable>`
            let MODID2 = `${index + 1}${sIndex}${i}29`
            // 计算当前时间为几分
            xml += `
            <block localId="${MODID2}" typeName="MOD" width="70" height="60">
              <position x="${cItem.x + 1800}" y="${cItem.y}" />
              <inputVariables>
                <variable formalParameter="IN1">
                  <connectionPointIn>
                    <relPosition x="-20" y="20" />
                    <connection refLocalId="${DIVID2}" formalParameter="OUT">
                      <position x="${cItem.x + 1690}" y="${cItem.y + 40}" />
                      <position x="${cItem.x + 1780}" y="${cItem.y + 20}" />
                    </connection>
                  </connectionPointIn>
                </variable>
                <variable formalParameter="IN2">
                  <connectionPointIn>
                    <relPosition x="-20" y="40" />
                    <connection refLocalId="${varId5}">
                      <position x="${cItem.x + 1760}" y="${cItem.y + 220}" />
                      <position x="${cItem.x + 1780}" y="${cItem.y + 40}" />
                    </connection>
                  </connectionPointIn>
                </variable>
              </inputVariables>
              <inOutVariables />
              <outputVariables>
                <variable formalParameter="OUT">
                  <connectionPointOut>
                    <relPosition x="90" y="20" />
                  </connectionPointOut>
                </variable>
              </outputVariables>
            </block>
            `
            // 设置的分钟数变量
            let minVarId = `${index + 1}${sIndex}${i}30`
            xml += `
            <inVariable localId="${minVarId}" width="40" height="40" negated="false">
              <position x="${cItem.x + 1900}" y="${cItem.y + 200}" />
              <connectionPointOut>
                <relPosition x="60" y="20" />
              </connectionPointOut>
              <expression>MIN${sIndex}_${i}</expression>
            </inVariable>`
            let GTID2 = `${index + 1}${sIndex}${i}31`
            // 判断分钟数是否相等
            xml += `
            <block localId="${GTID2}" typeName="EQ" width="70" height="60">
              <position x="${cItem.x + 2000}" y="${cItem.y}" />
              <inputVariables>
                <variable formalParameter="IN1">
                  <connectionPointIn>
                    <relPosition x="-20" y="20" />
                    <connection refLocalId="${MODID2}" formalParameter="OUT">
                      <position x="${cItem.x + 1990}" y="${cItem.y + 20}" />
                      <position x="${cItem.x + 1980}" y="${cItem.y + 20}" />
                    </connection>
                  </connectionPointIn>
                </variable>
                <variable formalParameter="IN2">
                  <connectionPointIn>
                    <relPosition x="-20" y="40" />
                    <connection refLocalId="${minVarId}">
                      <position x="${cItem.x + 1960}" y="${cItem.y + 220}" />
                      <position x="${cItem.x + 1980}" y="${cItem.y + 40}" />
                    </connection>
                  </connectionPointIn>
                </variable>
              </inputVariables>
              <inOutVariables />
              <outputVariables>
                <variable formalParameter="OUT">
                  <connectionPointOut>
                    <relPosition x="90" y="20" />
                  </connectionPointOut>
                </variable>
              </outputVariables>
            </block>
            `

            tempConnectXML += `
              <connection refLocalId="${GTID2}" formalParameter="OUT">
                <position x="${cItem.x + 2090}" y="${cItem.y + 20}" />
                <position x="${sItem.x - 120}" y="${sItem.y + 20}" />
              </connection>`
          } else if (cItem.label.includes('AI')) {
            let compareVarID = `${index + 1}${sIndex}${i}33`
            // 对AI进行比较的变量
            xml += `
            <inVariable localId="${compareVarID}" width="40" height="40" negated="false">
              <position x="${cItem.x - 100}" y="${cItem.y + 200}" />
              <connectionPointOut>
                <relPosition x="60" y="20" />
              </connectionPointOut>
              <expression>COMPARE_AI${sIndex}_${i}</expression>
            </inVariable>`
            // AI变量
            let AIID = `${index + 1}${sIndex}${i}34`
            xml += `
            <inVariable localId="${AIID}" width="40" height="40" negated="false">
              <position x="${cItem.x - 100}" y="${cItem.y + 200}" />
              <connectionPointOut>
                <relPosition x="60" y="20" />
              </connectionPointOut>
              <expression>${cItem.label}</expression>
            </inVariable>`
            let compareBlockID = `${index + 1}${sIndex}${i}35`
            let operationMap: Record<string, string> = {
              '≥': 'GE',
              '≤': 'LE',
              '>': 'GT',
              '<': 'LT',
              '=': 'EQ',
              '≠': 'NE'
            }
            xml += `<block localId="${compareBlockID}" typeName="${operationMap[cItem.operation!]}" width="70" height="60">
                  <position x="${cItem.x}" y="${cItem.y + 200}" />
                  <inputVariables>
                    <variable formalParameter="IN1">
                      <connectionPointIn>
                        <relPosition x="-20" y="40" />
                        <connection refLocalId="${compareVarID}" formalParameter="OUT">
                          <position x="${cItem.x - 40}" y="${cItem.y + 220}" />
                          <position x="${cItem.x - 20}" y="${cItem.y + 240}" />
                        </connection>
                      </connectionPointIn>
                    </variable>
                    <variable formalParameter="IN2">
                      <connectionPointIn>
                        <relPosition x="-20" y="60" />
                        <connection refLocalId="${AIID}" formalParameter="OUT">
                          <position x="${cItem.x - 40}" y="${cItem.y + 220}" />
                          <position x="${cItem.x - 20}" y="${cItem.y + 260}" />
                        </connection>
                      </connectionPointIn>
                    </variable>
                  </inputVariables>
                  <inOutVariables />
                  <outputVariables>
                    <variable formalParameter="OUT">
                      <connectionPointOut>
                        <relPosition x="90" y="20" />
                      </connectionPointOut>
                    </variable>
                  </outputVariables>
                </block>`

            tempConnectXML += `
              <connection refLocalId="${compareBlockID}" formalParameter="OUT">
                <position x="${cItem.x + 690}" y="${cItem.y + 20}" />
                <position x="${sItem.x - 120}" y="${sItem.y + 20}" />
              </connection>`
          } else if (cItem.label.includes('AO')) {
            // 乘数id
            let mulID = `${index + 1}${sIndex}${i}36`
            xml += `
            <inVariable localId="${mulID}" width="40" height="40" negated="false">
              <position x="${cItem.x - 100}" y="${cItem.y + 200}" />
              <connectionPointOut>
                <relPosition x="60" y="20" />
              </connectionPointOut>
              <expression>MUL_NUM</expression>
            </inVariable>`
            // 赋值id
            let setID = `${index + 1}${sIndex}${i}37`
            xml += `
            <inVariable localId="${setID}" width="40" height="40" negated="false">
              <position x="${cItem.x - 100}" y="${cItem.y + 200}" />
              <connectionPointOut>
                <relPosition x="60" y="20" />
              </connectionPointOut>
              <expression>SET_AI${sIndex}_${i}</expression>
            </inVariable>`

            let mulBlockId = `${index + 1}${sIndex}${i}38`
            xml += `
            <block localId="${mulBlockId}" typeName="DIV" width="70" height="60">
              <position x="${cItem.x}" y="${cItem.y}" />
              <inputVariables>
              <variable formalParameter="EN">
                  <connectionPointIn>
                    <relPosition x="-20" y="20"/>
                    <connection refLocalId="${sIndex === 0 ? item.id : tempVarId}" formalParameter="OUT">
                      <position x="${sIndex === 0 ? item.x + 40 : sItem.x - 40}" y="${sItem.y + 20}"/>
                      <position x="${cItem.x - 20}" y="${cItem.y + 20}"/>
                    </connection>
                  </connectionPointIn>
                </variable>
                      <variable formalParameter="IN1">
                      <connectionPointIn>
                      <relPosition x="-20" y="40" />
                      <connection refLocalId="${mulID}" formalParameter="OUT">
                      <position x="${cItem.x - 40}" y="${cItem.y + 220}" />
                      <position x="${cItem.x - 20}" y="${cItem.y + 40}" />
                    </connection>
                  </connectionPointIn>
                </variable>
                <variable formalParameter="IN2">
                  <connectionPointIn>
                    <relPosition x="-20" y="60" />
                    <connection refLocalId="${setID}">
                      <position x="${cItem.x - 40}" y="${cItem.y + 220}" />
                      <position x="${cItem.x - 20}" y="${cItem.y + 60}" />
                    </connection>
                  </connectionPointIn>
                </variable>
              </inputVariables>
              <inOutVariables />
              <outputVariables>
              <variable formalParameter="ENO">
                <connectionPointOut>
                  <relPosition x="90" y="20"/>
                </connectionPointOut>
              </variable>
                <variable formalParameter="OUT">
                  <connectionPointOut>
                    <relPosition x="90" y="40" />
                  </connectionPointOut>
                </variable>
              </outputVariables>
            </block>
            `

            // 赋值AO变量
            let AOID = `${index + 1}${sIndex}${i}38`
            xml += `
            <outVariable localId="${AOID}" width="40" height="40" negated="false">
              <position x="${cItem.x - 400}" y="${cItem.y + 200}" />
              <connectionPointIn>
                <relPosition x="60" y="20" />
                <connection refLocalId="${mulBlockId}" formalParameter="OUT">
                  <position x="${cItem.x + 90}" y="${cItem.y + 4}" />
                  <position x="${cItem.x - 340}" y="${cItem.y + 20}" />
                </connection>
              </connectionPointIn>
              <expression>${cItem.label}</expression>
            </outVariable>`
          }
        }
      } else if (sItem.type === 'delay') {
        // 延时时间变量
        let delayVarId = `${index + 1}${sIndex}32`
        xml += `
            <inVariable localId="${delayVarId}" width="40" height="40" negated="false">
              <position x="${sItem.x - 100}" y="${sItem.y + 200}" />
              <connectionPointOut>
                <relPosition x="60" y="20" />
              </connectionPointOut>
              <expression>PT${sIndex}</expression>
            </inVariable>
            `
        xml += `
            <block
              localId="${sItem.id}"
              typeName="TON"
              instanceName="TON${sIndex}"
              width="50"
              height="60"
            >
              <position x="${sItem.x}" y="${sItem.y}" />
              <inputVariables>
                <variable formalParameter="IN">
                  <connectionPointIn>
                    <relPosition x="-20" y="20" />
                    <connection refLocalId="${sIndex === 0 ? item.id : tempVarId}">
                      <position x="${sIndex === 0 ? item.x + 40 : sItem.x - 40}" y="${sItem.y + 20}" />
                      <position x="${sItem.x - 20}" y="${sItem.y + 20}" />
                    </connection>
                  </connectionPointIn>
                </variable>
                <variable formalParameter="PT">
                  <connectionPointIn>
                    <relPosition x="-20" y="40" />
                    <connection refLocalId="${delayVarId}">
                      <position x="${sItem.x - 40}" y="${sItem.y + 220}" />
                      <position x="${sItem.x - 20}" y="${sItem.y + 40}" />
                    </connection>
                  </connectionPointIn>
                </variable>
              </inputVariables>
              <inOutVariables />
              <outputVariables>
                <variable formalParameter="Q">
                  <connectionPointOut>
                    <relPosition x="70" y="20" />
                  </connectionPointOut>
                </variable>
                <variable formalParameter="ET">
                  <connectionPointOut>
                    <relPosition x="70" y="40" />
                  </connectionPointOut>
                </variable>
              </outputVariables>
            </block>
        `
        tempConnectXML += `
              <connection refLocalId="${sItem.id}" formalParameter="Q">
                <position x="${sItem.x + 70}" y="${sItem.y + 20}" />
                <position x="${sItem.x - 120}" y="${sItem.y + 20}" />
              </connection>`
      }
      if (sIndex !== 0) {
        tempVarId = `${index + 1}${sIndex}33`
      }
      tempXML += `<inOutVariable localId="${tempVarId}"  width="40" height="40" negatedOut="false" negatedIn="false">
        <position x="${sItem.x - 100}" y="${sItem.y}" />
        <connectionPointIn>
          <relPosition x="-20" y="20" />
      `
      tempXML += tempConnectXML
      tempXML += `
            </connectionPointIn>
            <connectionPointOut>
              <relPosition x="60" y="20"/>
            </connectionPointOut>
            <expression>temp${sIndex}</expression></inOutVariable>`
      if (sIndex !== item.stepList.length - 1) {
        xml += tempXML
      }
    })
    xml += `
    </LD>
    </body>
    </pou>
    `
  })

  // 尾部
  xml += `
        </pous>
      </types>
      <instances>
        <configurations>
          <configuration name="Config0">
            <resource name="Res0">
              <task name="task0" priority="0" interval="T#20ms">
              ${instanceXml}
              </task>
            </resource>
            <globalVars>
              ${globalVarsXml}
              <variable name="CRT_DATA">
                <type><DT /></type>
                <initialValue>
                  <simpleValue value="DT#${formatDateTime(new Date(), '-')}" />
                </initialValue>
              </variable>
            </globalVars>
          </configuration>
        </configurations>
      </instances>
    </project>`

  // console.log(xml)
  // 生成文件下载
  // const blob = new Blob([xml], { type: 'text/plain;charset=utf-8' })
  // const formdata = new FormData()
  // formdata.append('file', blob, 'project.xml')
  const params = {
    devicetype: 'PLC101',
    xml
  }
  fetch('https://plceditor.worldflying.cn/api/build/buildcode', {
    method: 'POST',
    body: JSON.stringify(params),
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Content-Length': xml.length + ''
    }
  })
    .then((res) => res.json())
    .then((res) => {
      console.log(res)
      // 关闭loading
      loading.close()
      if (res.errcode === 3000) {
        showFailToast('编译失败！')
      } else if (res.errcode === 0) {
        localStorage.setItem(
          'imgobj' + crtProject.value!.id,
          JSON.stringify({
            url: res.url,
            deadline: new Date().getTime() + 30 * 60 * 1000
          })
        )
        crtProject.value!.isCompiled = true
        crtProject.value!.CompileTime = formatDateTime(new Date())!
        wxtag.value = `<wx-open-launch-weapp appid="wx4c5a777c71f2981c" path="pages/index/rj45cfgbybt/plc/index?imgurl=${res.url}"><template><text style="color: #7232dd">烧录设备</text></template></wx-open-launch-weapp>`
        console.log('本地存储成功')
        showSuccessToast('编译成功！')
      }
    })

  // const link = document.createElement('a')
  // link.href = URL.createObjectURL(blob)
  // link.download = 'project.xml'
  // link.click()
  // URL.revokeObjectURL(link.href)
  // link.remove()
}

// 删除工程
const delProject = () => {
  if (crtProject.value) {
    showConfirmDialog({
      title: '提示',
      message: '确定要删除这个工程吗'
    })
      .then(() => {
        // on confirm
        console.log(projectList.value)
        localStorage.removeItem('imgobj' + crtProject.value!.id)
        projectList.value = projectList.value.filter((item) => crtProject.value?.id !== item.id)
        router.replace({ name: 'Automate' })
      })
      .catch(() => {
        // on cancel
      })
  }
}

const showSharePopup = ref(false)
const shareImg = ref('')
// const qrcodeCanvas = ref<HTMLCanvasElement>()
const shareProject = async () => {
  if (!window.isInWx) return
  showSharePopup.value = true
  await nextTick()
  qrcode.toDataURL(
    JSON.stringify({ ...crtProject.value, qrcodeType: 'worldflying_plc_editor' }),
    function (error, url) {
      if (error) console.error(error)
      // console.log(url)
      const ratio = window.devicePixelRatio
      const canvasEl = document.createElement('canvas')
      const windowWidth = window.innerWidth
      const windowHeight = window.innerHeight
      const minWindowSize = Math.floor(Math.min(windowWidth, windowHeight) * 0.7)
      canvasEl.style.width = `${minWindowSize}px`
      canvasEl.style.height = `${minWindowSize + 50}px`
      canvasEl.width = minWindowSize * ratio
      canvasEl.height = (minWindowSize + 50) * ratio
      const ctx = canvasEl?.getContext('2d')
      if (ctx) {
        const fontSize = 16 * ratio
        ctx.font = `${fontSize}px Arial`
        ctx.fillText(`工程名称：${crtProject.value?.name}`, 20 * ratio, 35 * ratio)
        const img = new Image()
        img.src = url
        img.onload = function () {
          ctx.drawImage(img, 0, 50 * ratio, minWindowSize * ratio, minWindowSize * ratio)
          shareImg.value = canvasEl.toDataURL('image/png')
        }
      }
      canvasEl.remove()
    }
  )
}

const getSTFile = () => {
  if (!crtProject.value) return
  let st = ''
  crtProject.value.commandList.forEach((item, index) => {
    st += `
    PROGRAM program${index}
      VAR
        DI0: BOOL
        DI1: BOOL
        AI0: INT
        AI1: INT
        DO0: BOOL
        DO1: BOOL
        AO0: INT
        AO1: INT
    `
    const tempVarNum = item.stepList.length
    for (let i = 1; i <= tempVarNum; i++) {
      st += `TEMP${i}: BOOL`
    }
  })
}
</script>

<style scoped>
.project-info {
  padding: 16px 0 0;
  height: 100%;
  overflow: hidden;
}
.van-button {
  padding: 2px 8px;
}
.more .van-button {
  padding: 2px 16px;
}
.header {
  padding: 0 16px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.header .project-name {
  height: 100%;
  max-width: 70%;
  display: flex;
  gap: 4px;
  align-items: center;
  justify-content: center;
}
.header .project-name .name {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  max-width: 70%;
}
.command-container {
  height: calc(100% - 65px);
  padding-bottom: 16px;
  overflow: auto;
}
.command-container :deep(.van-cell__value) {
  width: 32px;
  flex: none;
}
.command-container :deep(.van-cell__title) {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.command-container :deep(.van-swipe-cell__right) {
}
.del-button {
  width: 64px;
  height: 100%;
}
.van-cell {
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2px;
  gap: 16px;
}
.add-btn {
  position: fixed;
  bottom: 64px;
  left: 50%;
  transform: translateX(-50%);
  width: 70%;
}
.van-button-group {
  margin: 16px;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
.share-container {
  padding: 16px;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
}
.share-container .tip {
  margin: 16px 0;
  font-size: 18px;
}
</style>
