<template>
  <div class="app-container organization-manage">
    <el-divider content-position="left" v-if="false">公众号配置</el-divider>
    <el-card shadow="never" v-if="false">
      <el-form label-position="top" label-width="100px" :model="state.form" :rules="state.rules" ref="infoFormRef">
        <el-row :gutter="10">
          <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
            <el-form-item label="公众号名称" prop="wxpz_wxname">
              <el-input size="large" v-model="state.form.wxpz_wxname" clearable placeholder="输入公众号名称" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
            <el-form-item label="微信code（公众号原始ID）" prop="wxpz_wxcode">
              <el-input size="large" v-model="state.form.wxpz_wxcode" clearable placeholder="微信code（公众号原始ID）" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
            <el-form-item label="开发者ID（AppID）" prop="wxpz_appid">
              <el-input size="large" v-model="state.form.wxpz_appid" clearable placeholder="开发者ID（AppID）" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
            <el-form-item label="开发者密码（AppSecret）" prop="wxpz_appsecret">
              <el-input size="large" v-model="state.form.wxpz_appsecret" clearable placeholder="开发者密码（AppSecret）" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
            <el-form-item label="微信接口token" prop="wxpz_token">
              <el-input size="large" v-model="state.form.wxpz_token" clearable placeholder="微信接口token" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
            <el-form-item label="微信消息密钥" prop="wxpz_encodingaeskey">
              <el-input size="large" v-model="state.form.wxpz_encodingaeskey" clearable placeholder="微信消息密钥" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="微信关注欢迎信息" prop="wxpz_gzwelcomemsg">
              <el-input v-model="state.form.wxpz_gzwelcomemsg" style="width: 100%" :rows="10" type="textarea" placeholder="微信关注欢迎信息" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="footer">
        <el-button type="primary" size="large" :disabled="state.wxconfig.wxpz_status == 0" @click="handleSave">保存</el-button>
      </div>
    </el-card>

    <el-divider content-position="left" v-if="false">接口配置信息</el-divider>
    <el-card shadow="never" v-if="false">
      <el-input size="large" v-model="state.pzStr" clearable placeholder="接口配置信息" readonly>
        <template #append>
          <el-button :icon="CopyDocument" @click="copyText" />
        </template>
      </el-input>
      <p class="tips text-sm mt-4">需要将此配置信息，配置于微信公众号后台，用于正确响应微信发送的Token验证。</p>
    </el-card>

    <el-divider content-position="left" v-if="false">公众号菜单配置</el-divider>
    <el-card shadow="never">
      <div class="menu-config-container w-full flex justify-between">
        <div class="left-menu">
          <div class="phone-model h-full flex flex-col justify-between">
            <img src="@/assets/images/phone-head.png" alt="" />
            <div class="wx-footer flex">
              <!-- 一级菜单 -->
              <el-popover
                :placement="index >= 2 ? 'top-end' : 'top-start'"
                :width="150"
                :visible="item.showSub"
                trigger=""
                class="relative"
                v-for="(item, index) in sortList(menuState.menuList)"
                :key="`menu_item_${index}`"
              >
                <template #reference>
                  <el-button :type="item.active ? 'primary' : ''" plain class="flex-1" @click="handleSelectTopLevelMenu(item)">{{ item.name }}</el-button>
                </template>
                <!-- 二级菜单 -->
                <div class="item-list">
                  <div class="menu-item" v-for="(subItem, subIndex) in sortList(item.children)" :key="`subitem_${subIndex}`">
                    <el-button class="w-full" :type="subItem.active ? 'primary' : ''" @click="handleSelectSecondLevelMenu(subItem)">{{ subItem.name }}</el-button>
                  </div>
                  <div class="menu-item" v-show="item.children.length <= 4">
                    <el-button :icon="Plus" class="w-full" @click="handleAddSecondLevelMenu(index)">添加子菜单</el-button>
                  </div>
                </div>
                <!-- 子菜单控制 -->
                <div class="control-box" :class="{'control-left': index >= 2}" v-show="menuState.currentMenu.level === 2">
                  <el-button :icon="Top" size="small" circle class="!mx-0" v-show="menuState.controlVisible.up" @click="handleMenuControl({type: 'up'})" />
                  <el-button :icon="Delete" size="small" circle class="!mx-0 !my-2" v-show="menuState.controlVisible.del" @click="handleMenuControl({type: 'del'})" />
                  <el-button :icon="Bottom" size="small" circle class="!mx-0" v-show="menuState.controlVisible.down" @click="handleMenuControl({type: 'down'})" />
                </div>
              </el-popover>
              <el-button :icon="Plus" plain class="flex-1" v-show="menuState.menuList.length < 3" @click="handleAddTopLevelMenu">添加菜单</el-button>
            </div>
            <!-- 一级菜单控制 -->
            <div class="control-box-horizontal flex" v-show="menuState.currentMenu.level === 1">
              <el-button :icon="Back" size="small" circle class="!mx-0" v-show="menuState.controlVisible.up" @click="handleMenuControl({type: 'up'})" />
              <el-button :icon="Delete" size="small" circle class="!mx-2" v-show="menuState.controlVisible.del" @click="handleMenuControl({type: 'del'})" />
              <el-button :icon="Right" size="small" circle class="!mx-0" v-show="menuState.controlVisible.down" @click="handleMenuControl({type: 'down'})" />
            </div>
          </div>
        </div>
        <div class="right-form flex-1 ml-4">
          <el-form label-position="top" label-width="100px" :model="menuState.form" :rules="menuState.rules" ref="menuFormRef">
            <el-form-item label="菜单名称" prop="wxmenuname">
              <el-input size="large" v-model="menuState.form.wxmenuname" clearable placeholder="输入菜单名称" />
              <p class="text-xs mt-4 text-red-400">仅支持中英文和数字，字数不超过4个汉字或8个字母。</p>
            </el-form-item>
            <el-form-item label="菜单名称" prop="wxmenuntype" v-if="!hasChildren">
              <el-radio-group v-model="menuState.form.wxmenuntype" class="ml-4" @change="wxmenuntypeChange">
                <el-radio label="click" size="large">发送消息</el-radio>
                <el-radio label="view" size="large">跳转网页</el-radio>
                <el-radio label="miniprogram" size="large">跳转小程序</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="消息内容" prop="wxmenukey" v-if="menuState.form.wxmenuntype === 'click'">
              <el-input size="large" :rows="5" type="textarea" v-model="menuState.form.wxmenukey" clearable placeholder="输入消息内容" />
            </el-form-item>
            <el-form-item label="网页链接" prop="wxmenuurl" v-if="menuState.form.wxmenuntype === 'view'">
              <el-input size="large" v-model="menuState.form.wxmenuurl" clearable placeholder="输入网页链接" />
              <p class="text-xs mt-4 text-red-400">必须以http://或者https://开头</p>
            </el-form-item>
            <el-form-item label="小程序appid" prop="wxmenuappid" v-if="menuState.form.wxmenuntype === 'miniprogram'">
              <el-input size="large" v-model="menuState.form.wxmenuappid" clearable placeholder="输入小程序appid" />
            </el-form-item>
            <el-form-item label="小程序路径" prop="wxmenupagepath" v-if="menuState.form.wxmenuntype === 'miniprogram'">
              <el-input size="large" v-model="menuState.form.wxmenupagepath" clearable placeholder="输入小程序路径" />
            </el-form-item>
          </el-form>
          <div class="footer mt-12">
            <el-button type="primary" size="large" @click="handleSaveMenu">保存菜单</el-button>
            <el-button size="large" :icon="Switch" @click="handleUpWXMenu" :loading="menuState.tongbuLoading">上传并同步至公众号</el-button>
          </div>
        </div>
      </div>
    </el-card>
  </div>
  <!-- 新增/修改 内容弹窗 -->
  <!-- <el-dialog v-model="state.aiTimeConfig.dialogVisible" title="请选择周期规则" width="400">
    <el-form-item label="周期类型" prop="wxmenuntype" v-if="!hasChildren">
      <el-radio-group v-model="state.aiTimeConfig.type" class="ml-4">
        <el-radio label="click"></el-radio>
        <el-radio label="view">跳转网页</el-radio>
        <el-radio label="miniprogram">跳转小程序</el-radio>
      </el-radio-group>
    </el-form-item>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="upList()"> 确定 </el-button>
        <el-button type="primary" @click="upList(state.form)"> 修改 </el-button>
      </div>
    </template>
  </el-dialog> -->
</template>

<script setup>
import {CopyDocument, Plus, Switch, Top, Delete, Bottom, Back, Right} from '@element-plus/icons-vue'
import {
  admin_sh_get_wxconfig_list,
  admin_sh_wxmenu_list,
  admin_sh_wxmenu_detail,
  admin_sh_wxmenu_add,
  admin_sh_wxmenu_del,
  admin_sh_wxmenu_up,
  admin_sh_wxmenu_tongbu
} from '@/api/app'
import {reformateObjectRes} from '@/utils/index'
import _ from 'lodash'

const props = defineProps({
  aiInfo: {
    type: Object,
    default: () => {}
  }
})
const config = {}
const adminStore = {}
const infoFormRef = ref(null)
const menuFormRef = ref(null)
const state = reactive({
  form: {},
  rules: {},
  pzStr: '',
  zhouData: [
    {
      label: '周一'
    },
    {
      label: '周二'
    },
    {
      label: '周三'
    },
    {
      label: '周四'
    },
    {
      label: '周五'
    },
    {
      label: '周六'
    },
    {
      label: '周日'
    }
  ], // 工作日
  aiTimeConfig: [
    // {
    //   type: '', // 类型
    //   sfmTime: '', // 时间
    //   rqTime: '', // 日期
    //   airuntimestatus: false // 启用
    // }
  ],
  wxconfig: {} // 微信配置信息
})

const menuState = reactive({
  currentDataOrigin: {}, //当前选中菜单的原始数据（request）
  form: {},
  rules: {
    wxmenuname: [{required: true, message: '请输入菜单名称', trigger: 'blur'}],
    wxmenuntype: [{required: true, message: '请选择菜单类型', trigger: 'change'}],
    wxmenukey: [{required: true, message: '请输入消息内容', trigger: 'blur'}],
    wxmenuurl: [{required: true, message: '请输入网页链接', trigger: 'blur'}],
    wxmenuappid: [{required: true, message: '请输入小程序appid', trigger: 'blur'}],
    wxmenupagepath: [{required: true, message: '请输入小程序路径', trigger: 'blur'}]
  },
  menuVisible: true,
  menuList: [],
  currentMenu: {}, //当前操作的菜单（包含一级、二级菜单）
  controlVisible: {
    up: false,
    down: false,
    del: true
  },
  tongbuLoading: false
})

const onSearch = (data) => {
  console.log(data, state.aiTimeConfig.zhouTime, 'state.aiTimeConfig.zhouTime')
}

// 请求时间规则
const getAiWorkingTime = async () => {
  state.aiTimeConfig = []
  await _list({
    airuntimeaiid: props.aiInfo.aiid,
    pagevalue: 217,
    pageindex: 1,
    rows: 9999
  }).then((res) => {
    // console.log(res.Data, 'res.Data')
    if (res.Status === 0) {
      res.Data.Data.forEach((value) => {
        let val = {}
        val.airuntimestarttime = value.airuntimestarttime
        val.airuntimeendtime = value.airuntimeendtime
        val.airuntimestartdate = value.airuntimestartdate
        val.airuntimeenddate = value.airuntimeenddate

        if (value.airuntimetitle == '每天') {
          val.type = '1'
        } else if (value.airuntimetitle == '周一,周二,周三,周四,周五') {
          val.zhouTime = '周一,周二,周三,周四,周五'.split(',')
          val.type = '2'
        } else if (value.airuntimetitle == '按周期') {
          val.type = '4'
          val.airuntimestarttime = value?.airuntimestartdate?.split(' ')[1]
          val.airuntimeendtime = value?.airuntimeenddate?.split(' ')[1]
          val.airuntimestartdate = value?.airuntimestartdate?.split(' ')[0]
          val.airuntimeenddate = value?.airuntimeenddate?.split(' ')[0]
        } else {
          val.type = '3'
          val.zhouTime = value.airuntimetitle.split(',')
        }
        // console.log(val.airuntimestarttime, 'state.zhouTime')

        state.aiTimeConfig.push({
          airuntimeid: value.airuntimeid,
          title: value.airuntimetitle,
          zhouTime: val.zhouTime || [],
          type: val.type, // 类型
          sfmTime: [val.airuntimestarttime, val.airuntimeendtime], // 时间
          rqTime: [val.airuntimestartdate, val.airuntimeenddate], // 日期
          airuntimestatus: value.airuntimestatus // 启用
        })
      })
    }
  })
}

const delTime = async (config, index) => {
  if (config.airuntimeid) {
    const res = await _del({
      pagevalue: 219,
      airuntimeid: config.airuntimeid
    })
    if (res.Status === 0) {
      proxy.$modal.msgSuccess('删除成功')
    }
  }
  state.aiTimeConfig.splice(index, 1)
}

const saveTime = async (config) => {
  // 新增
  // _ 深拷贝
  const val = _.cloneDeep(config)

  if (val.type == '' || !val.sfmTime) {
    msgError('请把时间周期填写完整！')
    return
  } else if (val.type == 4 && !val.rqTime) {
    msgError('请把时间周期填写完整！')
    return
  }

  if (val.type == 1) {
    val.airuntimetitle = '每天'
  } else if (val.type == 2) {
    val.airuntimetitle = '周一,周二,周三,周四,周五'
  } else if (val.type == 3) {
    val.airuntimetitle = val.zhouTime.toString()
  } else if (val.type == 4) {
    val.airuntimetitle = '按周期'
    // console.log(val.rqTime[0], 'wdwdadwdw', val.sfmTime[0], 'val.rqTime[0]')
    val.airuntimestartdate = val.rqTime[0] + ' ' + val.sfmTime[0]
    val.airuntimeenddate = val.rqTime[1] + ' ' + val.sfmTime[1]
    val.sfmTime = ['', '']
  }

  const param = {
    airuntimeaiid: props.aiInfo.aiid,
    // 名称
    airuntimetitle: val.airuntimetitle,
    airuntimestartdate: val.airuntimestartdate,
    airuntimeenddate: val.airuntimeenddate,
    airuntimestarttime: val.sfmTime[0],
    airuntimeendtime: val.sfmTime[1],
    airuntimestatus: val.airuntimestatus
  }
  //   console.log(config, 'param')
  if (config.airuntimeid) {
    // 修改列表
    const res = await _up({
      pagevalue: 220,
      airuntimeid: config.airuntimeid,
      ...param
    })
    if (res.Status === 0) {
      proxy.$modal.msgSuccess('保存成功！')
    }
  } else {
    const res = await _add({
      pagevalue: 218,
      ...param
    })
    if (res.Status === 0) {
      proxy.$modal.msgSuccess('保存成功！')
    }
  }
}

//切换时，重置form
const wxmenuntypeChange = (val) => {
  if (val === menuState.currentDataOrigin.wxmenuntype) {
    menuState.form.wxmenuappid = menuState.currentDataOrigin.wxmenuappid
    menuState.form.wxmenukey = menuState.currentDataOrigin.wxmenukey
    menuState.form.wxmenupagepath = menuState.currentDataOrigin.wxmenupagepath
    menuState.form.wxmenuurl = menuState.currentDataOrigin.wxmenuurl
    menuState.form.wxpz_gzwelcomemsg = menuState.currentDataOrigin.wxpz_gzwelcomemsg
  } else {
    menuState.form.wxmenukey = ''
    menuState.form.wxmenuurl = ''
    menuState.form.wxmenuappid = ''
    menuState.form.wxmenupagepath = ''
    menuState.form.wxpz_gzwelcomemsg = ''
  }
}

//当前选中菜单是否有子菜单
const hasChildren = computed(() => {
  if (menuState.currentMenu.level === 1) {
    return menuState.currentMenu.children && menuState.currentMenu.children.length
  }
  return false
})

//菜单-监听当前菜单
watch(
  () => menuState.currentMenu,
  (val) => {
    // console.log(val.wxmenuid, '监听当前菜单')
    if (val.wxmenuid) {
      const wxmenuid = val.wxmenuid
      admin_sh_wxmenu_detail({
        ['wxmenuid.value']: wxmenuid
      }).then(({Data, Status}) => {
        if (Status === 0) {
          const dataObj = reformateObjectRes(Data)
          menuState.currentDataOrigin = dataObj
          menuState.form = {
            wxmenuid: dataObj.wxmenuid,
            wxmenuappid: dataObj.wxmenuappid,
            wxmenukey: dataObj.wxmenukey,
            wxmenuname: dataObj.wxmenuname,
            wxmenuntype: dataObj.wxmenuntype,
            wxmenupagepath: dataObj.wxmenupagepath,
            wxmenuurl: dataObj.wxmenuurl,
            wxmenuappid: dataObj.wxmenuappid
          }
        }
      })
    }
  }
)

//菜单-判断当前菜单是否可以向下移动
watchEffect(() => {
  //根据orderIndex判断在当前级别菜单中是否是最大值
  if (Object.keys(menuState.currentMenu).length) {
    const currentOrderIndex = menuState.currentMenu.orderIndex
    const currentLevel = menuState.currentMenu.level
    let currentMenuList = []
    if (currentLevel === 1) {
      currentMenuList = sortList(menuState.menuList)
    }
    if (currentLevel === 2) {
      // console.log(menuState.menuList)
      // console.log(menuState.currentMenu)
      const parent = menuState.menuList.find((item) => {
        return item.wxmenuid === menuState.currentMenu.wxmenuparentid
      })
      currentMenuList = sortList(parent.children)
    }
    menuState.controlVisible.down = currentOrderIndex < currentMenuList[currentMenuList.length - 1].orderIndex
    menuState.controlVisible.up = currentOrderIndex > currentMenuList[0].orderIndex
  }
})

/**
 * 清除其他菜单的active状态
 * 传入{ subShow: false }，不清除showSub状态
 * @param {*} config
 */
const resetActive = (config) => {
  menuState.menuList.forEach((item) => {
    item.active = false
    if (!config || config.subShow === true) {
      item.showSub = false
    }
    if (item.children) {
      item.children.forEach((child) => {
        child.active = false
      })
    }
  })
}

//同步至微信公众号
const handleUpWXMenu = () => {
  menuState.tongbuLoading = true
  const params = {
    wxcode: state.wxconfig.wxpz_wxcode,
    wxpzid: state.wxconfig.wxpz_id
  }
  console.log('同步微信配置：', params)
  admin_sh_wxmenu_tongbu(params)
    .then(({Status, Data, Message}) => {
      if (Status === 0) {
        proxy.$modal.msgSuccess('同步成功')
      } else {
        proxy.$modal.msgError('同步失败:' + Message)
      }
      menuState.tongbuLoading = false
    })
    .catch(() => {
      menuState.tongbuLoading = false
    })
}

//菜单-保存配置
const handleSaveMenu = () => {
  menuFormRef.value.validate((valid) => {
    if (valid) {
      const params = {
        ...menuState.form
      }
      //去掉值是空或者null的参数
      for (const key in params) {
        if (params.hasOwnProperty(key)) {
          const element = params[key]
          if (element === '' || element === null) {
            delete params[key]
          }
        }
      }
      admin_sh_wxmenu_up(params).then(({Data, Status, Message}) => {
        if (Status === 0) {
          proxy.$modal.msgSuccess('保存成功')
          const currentid = menuState.currentMenu.wxmenuid
          //两层循环，通过wxmenuid找到更新的菜单数据，更新当前菜单显示(名称)
          menuState.menuList.forEach((item) => {
            if (item.wxmenuid === currentid) {
              item.name = menuState.form.wxmenuname
            }
            if (item.children) {
              item.children.forEach((child) => {
                if (child.wxmenuid === currentid) {
                  child.name = menuState.form.wxmenuname
                }
              })
            }
          })
        } else {
          msgError('保存失败:' + Message)
        }
      })
    }
  })
}

//根据菜单orderIndex排序返回并显示
const sortList = (list) => {
  list.sort((a, b) => {
    return a.orderIndex - b.orderIndex
  })
  return list
}
const {proxy} = getCurrentInstance()

//菜单控制
const handleMenuControl = async ({type}) => {
  // console.log(menuState.currentMenu)
  const currentMenu = menuState.currentMenu
  const isTopLevel = currentMenu.level === 1
  if (type === 'del') {
    const alertMsg = isTopLevel ? '删除该菜单将会同时删除该菜单下的子菜单，确定删除吗？' : '确定删除该菜单吗？'
    proxy.$modal.confirm(alertMsg).then((res) => {
      if (res === 'confirm') {
        const ids = isTopLevel
          ? currentMenu.children
              .map((item) => {
                return item.wxmenuid
              })
              .join(',') +
            ',' +
            currentMenu.wxmenuid
          : currentMenu.wxmenuid

        admin_sh_wxmenu_del({
          ids
        }).then(({Status, Data, Message}) => {
          if (Status === 0) {
            proxy.$modal.msgSuccess('删除成功')
            if (!isTopLevel) {
              const parent = menuState.menuList.find((item) => {
                return item.wxmenuid === currentMenu.wxmenuparentid
              })
              const index = parent.children.findIndex((item) => {
                return item.wxmenuid === currentMenu.wxmenuid
              })
              parent.children.splice(index, 1)
              menuState.currentMenu = {}
            } else {
              const index = menuState.menuList.findIndex((item) => {
                return item.wxmenuid === currentMenu.wxmenuid
              })
              menuState.menuList.splice(index, 1)
              menuState.currentMenu = {}
            }
          } else {
            msgError('删除失败:' + Message)
          }
        })
      }
    })
  } else {
    const currentMenuId = currentMenu.wxmenuid
    const currentMenuOrderIndex = currentMenu.orderIndex
    const menusList = isTopLevel
      ? menuState.menuList
      : menuState.menuList.find((item) => {
          return item.wxmenuid === currentMenu.wxmenuparentid
        }).children

    const menusListSort = sortList(menusList)
    //获取当前点击菜单的index
    const currentIndex = menusListSort.findIndex((item) => {
      return item.wxmenuid === currentMenuId
    })
    const nextIndex = type === 'up' ? currentIndex - 1 : currentIndex + 1
    //获取上/下一个菜单的id
    const nextMenuId = menusListSort[nextIndex].wxmenuid
    const nextMenuOrderIndex = menusListSort[nextIndex].orderIndex

    Promise.all([
      admin_sh_wxmenu_up({
        wxmenuid: currentMenuId,
        wxmenurankingcount: nextMenuOrderIndex
      }),
      admin_sh_wxmenu_up({
        wxmenuid: nextMenuId,
        wxmenurankingcount: currentMenuOrderIndex
      })
    ]).then((res) => {
      const [currentRes, nextRes] = res
      if (currentRes.Status === 0 && nextRes.Status === 0) {
        menusListSort[currentIndex].orderIndex = nextMenuOrderIndex
        menusListSort[nextIndex].orderIndex = currentMenuOrderIndex
        // menuState.currentMenu = menusListSort[nextIndex]
      } else {
        msgError('移动失败')
      }
    })
  }
  // console.log(menuState.menuList)
}

//添加二级菜单
const handleAddSecondLevelMenu = (currentIndex) => {
  resetActive({subShow: false})
  const topLevelMenu = menuState.menuList[currentIndex]
  const topLevelIndex = topLevelMenu.orderIndex
  const subLen = topLevelMenu.children.length

  const dafaultOrderIndex = topLevelIndex + subLen + 1
  let orderIndex = dafaultOrderIndex
  if (subLen) {
    const currentChildMenuList = sortList(topLevelMenu.children)
    const maxOrderIndex = currentChildMenuList[currentChildMenuList.length - 1].orderIndex
    orderIndex = maxOrderIndex + 1
  }

  const params = {
    wxmenuname: '子菜单名称',
    wxmenubaseid: topLevelMenu.wxmenuid,
    wxmenuntype: '',
    wxmenuwxpzid: state.wxconfig.wxpz_id,
    wxmenurankingcount: orderIndex,
    wxcode: state.wxconfig.wxpz_wxcode
  }
  admin_sh_wxmenu_add(params).then(({Data, Status, Message}) => {
    if (Status === 0) {
      const subMenu = {
        name: '子菜单名称',
        level: 2,
        orderIndex: orderIndex,
        active: true,
        wxmenuparentid: topLevelMenu.wxmenuid,
        wxmenuid: Data
      }
      topLevelMenu.children.push(subMenu)
      menuState.currentMenu = subMenu
    } else {
      alertError('添加失败:' + Message)
    }
  })
}

//选择一级菜单
const handleSelectTopLevelMenu = (item, index) => {
  resetActive()
  item.active = true
  item.showSub = true
  menuState.currentMenu = item
}

//选择二级菜单
const handleSelectSecondLevelMenu = (item, index) => {
  resetActive({subShow: false})
  item.active = true
  menuState.currentMenu = item
}

//添加一级菜单
const handleAddTopLevelMenu = () => {
  const len = menuState.menuList.length
  const defaultOrderIndex = (menuState.menuList.length + 1) * 1000
  let orderIndex = defaultOrderIndex
  if (len) {
    const currentTopLevelMenuList = sortList(menuState.menuList)
    const maxOrderIndex = currentTopLevelMenuList[currentTopLevelMenuList.length - 1].orderIndex
    orderIndex = maxOrderIndex + 1000
  }

  const params = {
    wxmenubaseid: '0',
    wxmenuname: '菜单名称',
    wxmenuntype: '',
    wxmenuwxpzid: state.wxconfig.wxpz_id,
    wxmenurankingcount: orderIndex,
    wxcode: state.wxconfig.wxpz_wxcode
  }
  admin_sh_wxmenu_add(params).then(({Data, Message, Status}) => {
    if (Status === 0) {
      resetActive()

      const menu = {
        wxmenuid: Data,
        wxmenuparentid: '0',
        name: '菜单名称',
        level: 1,
        orderIndex: orderIndex,
        active: true,
        showSub: true,
        children: []
      }
      menuState.menuList.push(menu)
      menuState.currentMenu = menu
    } else {
      alertError('添加失败:' + Message)
    }
  })
}

const handleSave = () => {
  infoFormRef.value.validate((valid) => {
    if (valid) {
      if (Object.keys(state.wxconfig).length) {
        // 更新微信配置的时候 将配置state状态改成1 不可编辑状态
        state.wxconfig.wxpz_status = 1
        //有配置信息，更新
        admin_sh_up_wxconfig({
          wxpz_id: state.wxconfig.wxpz_id,
          wxpz_wxname: state.form.wxpz_wxname,
          wxpz_appid: state.form.wxpz_appid,
          wxpz_appsecret: state.form.wxpz_appsecret,
          wxpz_token: state.form.wxpz_token,
          wxpz_encodingaeskey: state.form.wxpz_encodingaeskey,
          wxpz_wxcode: state.form.wxpz_wxcode,
          wxpz_gzwelcomemsg: state.form.wxpz_gzwelcomemsg,
          wxpz_status: 1
        }).then(({Data, Status}) => {
          if (Status === 0) {
            alertSuccess('保存成功')
            getWechatConfigList()
          }
        })
      } else {
        //没有配置信息，新增
        admin_sh_add_wxconfig({
          wxpz_aimodelid: props.aiInfo.aiid,
          wxpz_wxname: state.form.wxpz_wxname,
          wxpz_appid: state.form.wxpz_appid,
          wxpz_appsecret: state.form.wxpz_appsecret,
          wxpz_token: state.form.wxpz_token,
          wxpz_encodingaeskey: state.form.wxpz_encodingaeskey,
          wxpz_wxcode: state.form.wxpz_wxcode,
          wxpz_gzwelcomemsg: state.form.wxpz_gzwelcomemsg
        }).then(({Data, Status}) => {
          if (Status === 0) {
            alertSuccess('保存成功')
            getWechatConfigList()
          }
        })
      }
    }
  })
}

const getWechatConfigList = async () => {
  //获取微信菜单
  getWXmenuList()
}

const copyText = () => {
  handleCopyText(state.pzStr)
}

const handleAddConfig = () => {
  state.wxconfig = {}
  state.form = {
    wxpz_wxname: '',
    wxpz_appid: '',
    wxpz_appsecret: '',
    wxpz_token: '',
    wxpz_encodingaeskey: '',
    wxpz_wxcode: '',
    wxpz_gzwelcomemsg: ''
  }
}

const getWXmenuList = () => {
  const params = {
    wxmenuwxpzid: state.wxconfig.wxpz_id,
    pageindex: 1,
    rows: 9999
  }
  admin_sh_wxmenu_list(params).then(({Data, Status}) => {
    if (Status === 0) {
      if (Data.Data.length) {
        // [{
        //     wxmenuaccountid: null
        //     wxmenuappid: null
        //     wxmenuarticleid: null
        //     wxmenubaseid: "0"
        //     wxmenucreatedate: null
        //     wxmenucreateuser: null
        //     wxmenuid: "1"
        //     wxmenukey: null
        //     wxmenumediaid: null
        //     wxmenuname: "音乐"
        //     wxmenuntype: "click"
        //     wxmenupagepath: null
        //     wxmenurankingcount: 0
        //     wxmenuurl: null
        //     wxmenuwxpzid: "1"
        // }]

        //构建树形结构
        const menuList = []
        Data.Data.forEach((item) => {
          if (item.wxmenubaseid === '0') {
            const menu = {
              wxmenuid: item.wxmenuid,
              wxmenuparentid: item.wxmenubaseid,
              name: item.wxmenuname,
              level: 1,
              orderIndex: item.wxmenurankingcount,
              active: false,
              showSub: false,
              children: []
            }
            Data.Data.forEach((subItem) => {
              if (subItem.wxmenubaseid === item.wxmenuid) {
                const subMenu = {
                  wxmenuid: subItem.wxmenuid,
                  wxmenuparentid: subItem.wxmenubaseid,
                  name: subItem.wxmenuname,
                  level: 2,
                  orderIndex: subItem.wxmenurankingcount,
                  active: false
                }
                menu.children.push(subMenu)
              }
            })
            menuList.push(menu)
          }
        })
        menuState.menuList = menuList
      }
    }
  })
}

watch(
  () => props.aiInfo,
  (val, oldVal) => {
    getWechatConfigList()
  },
  {immediate: true}
)

defineExpose({
  getWechatConfigList
})
</script>

<style lang="scss" scoped>
.menu-config-container {
  .left-menu {
    width: 390px;
    height: 600px;
    border: 1px solid #ebeef5;
    box-sizing: border-box;
    padding: 5px;
    margin-bottom: 20px;
  }
}

.item-list {
  .menu-item {
    height: 32px;
    line-height: 32px;
    margin-bottom: 2px;

    &:last-child {
      margin-bottom: 0;
    }
  }
}

.control-box {
  position: absolute;
  right: -5px;
  top: 50%;
  transform: translate(100%, -50%);
  display: flex;
  flex-direction: column;
}

.control-left {
  left: -5px;
  right: auto;
  transform: translate(-100%, -50%);
}

.phone-model {
  position: relative;

  .control-box-horizontal {
    position: absolute;
    bottom: -10px;
    left: 50%;
    transform: translate(-50%, 100%);
  }
}
</style>
