<template>
  <ContentWrap>
    <div class="flex gap-x-10px">
      <div class="flex-basis-180px flex-shrink-0">
        <avue-tree
          ref="treeRef"
          v-model="treeForm"
          :option="treeOption"
          :data="treeData"
          :permission="treePermission"
          :before-open="treeBeforeOpen"
          @node-contextmenu="treeNodeContextmenu"
          @node-click="treeNodeClick"
          @update="treeUpdate"
          @save="treeSave"
          @del="treeDel"
        >
        </avue-tree>
      </div>
      <avue-crud
        class="table-content flex-1"
        ref="crudRef"
        v-model="tableForm"
        v-model:page="tablePage"
        v-model:search="tableSearch"
        :table-loading="loading"
        :data="tableData"
        :option="tableOption"
        :permission="permission"
        :before-open="beforeOpen"
        @search-change="searchChange"
        @search-reset="resetChange"
        @row-save="rowSave"
        @row-update="rowUpdate"
        @row-del="rowDel"
        @refresh-change="getTableData"
        @size-change="sizeChange"
        @current-change="currentChange"
        @selection-change="selectionChange"
      >
        <template #menu-left="{ size }">
          <el-dropdown @command="menuLeftHandle" v-hasPermi="['lideeyunji:tab:js']">
            <el-button type="primary" :size="size" class="ml-10px">
              <Icon :size="14" icon="teenyicons:webpack-outline" />
              <span class="ml-3px!">前端增强</span>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="js">JS增强</el-dropdown-item>
                <el-dropdown-item command="scss">SCSS增强</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
        <template #menu="{ size, row, index }">
          <div class="flex justify-center flex-items-center">
            <el-button
              type="primary"
              text
              :size="size"
              @click="menuHandle({ type: 'edit', row, index })"
              v-hasPermi="['lideeyunji:tab:update']"
            >
              <Icon :size="14" icon="ep:edit-pen"></Icon>
              <span>编辑</span>
            </el-button>
            <span
              v-if="
                checkPermi(['lideeyunji:tab:update']) &&
                checkPermi([
                  'lideeyunji:tab:create',
                  'lideeyunji:tab:update',
                  'lideeyunji:tab:delete'
                ])
              "
              class="ml-8px mr-8px mt-2px inline-block h-16px w-1px bg-#e8e8e8 .dark:bg-[var(--el-border-color-dark)]"
            ></span>
            <el-dropdown
              @command="menuHandle"
              v-if="
                checkPermi([
                  'lideeyunji:tab:create',
                  'lideeyunji:tab:update',
                  'lideeyunji:tab:delete'
                ])
              "
            >
              <div class="mt--2px cursor-pointer">
                <el-text :size="size" type="primary">
                  更多
                  <Icon :size="16" icon="iconamoon:arrow-down-2-light" />
                </el-text>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{ type: 'test', row }"> 功能测试 </el-dropdown-item>
                  <el-dropdown-item :command="{ type: 'routeAddress', row }">
                    路由地址
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="checkPermi(['lideeyunji:tab:update'])"
                    :command="{ type: 'jsUnlock', row }"
                  >
                    js增强解锁
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="checkPermi(['lideeyunji:tab:update'])"
                    :command="{ type: 'scssUnlock', row }"
                  >
                    scss增强解锁
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="checkPermi(['lideeyunji:tab:delete'])"
                    :command="{ type: 'del', row }"
                  >
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
        <template #lowSelectRadio="{ row }">
          <el-radio
            class="low-select-radio"
            v-model="radioValue"
            :label="row.id"
            @click="radioClick(row)"
          />
        </template>
        <template #optionList-form>
          <avue-crud ref="moduleCrudRef" :option="moduleOption" :data="tableForm.optionList">
            <template #menu="{ size, index }">
              <el-button text :size="size" type="danger" @click="delModuleTableRow(index)">
                <span>删除</span>
              </el-button>
            </template>
            <template #darg="{ index }">
              <el-dropdown trigger="hover" placement="bottom" @command="dropdownCommand">
                <div>
                  <Icon :size="20" icon="gg:menu-grid-r" />
                </div>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="{ index: index, type: 'up' }" :disabled="index == 0"
                      >向上移</el-dropdown-item
                    >
                    <el-dropdown-item
                      :command="{ index: index, type: 'down' }"
                      :disabled="index == tableForm.optionList?.length - 1"
                      >向下移</el-dropdown-item
                    >
                    <el-dropdown-item :command="{ index: index, type: 'add' }"
                      >插入一行</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
            <template #tabIcon="{ row }">
              <Icon v-if="row.tabIcon" :size="14" :icon="row.tabIcon" />
            </template>
            <template #tabIcon-form="{ row, column, size, disabled }">
              <IconSelectInput
                v-model="row.tabIcon"
                :prop="column.prop"
                :column="column"
                :size="size"
                :disabled="disabled"
              />
            </template>
            <template #moduleValue-form="{ row }">
              <avue-select
                v-if="row.moduleType == 'table'"
                v-model="row.moduleValue"
                placeholder="请选择表单开发配置"
                :dic="tableDicData"
                :virtualize="true"
                :filterable="true"
              ></avue-select>
              <avue-select
                v-else-if="row.moduleType == 'form'"
                v-model="row.moduleValue"
                placeholder="请选择自定义表单配置"
                :dic="formDicData"
                :virtualize="true"
                :filterable="true"
              ></avue-select>
              <avue-select
                v-else-if="row.moduleType == 'report'"
                v-model="row.moduleValue"
                placeholder="请选择报表配置"
                :dic="reportDicData"
                :virtualize="true"
                :filterable="true"
              ></avue-select>
              <avue-input
                v-else-if="row.moduleType == 'custom'"
                v-model="row.moduleValue"
                placeholder="模块所在文件路径"
                prepend="src/"
              >
              </avue-input>
            </template>
            <template #isLazy-header="{ column }">
              <span>{{ column.label }}</span>
              <div class="pos-absolute right-1px top-0">
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="第一次切换到当前标签页之前模块内容都不会加载"
                  placement="top-start"
                >
                  <Icon :size="14" icon="ep:info-filled"></Icon>
                </el-tooltip>
              </div>
            </template>
            <template #isLazy-form="{ row }">
              <el-checkbox v-model="row.isLazy" true-value="Y" false-value="N" />
            </template>
            <template #isRefresh-header="{ column }">
              <span>{{ column.label }}</span>
              <div class="pos-absolute right-1px top-0">
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="切换到当前标签页时，会刷新当前模块内容的数据"
                  placement="top-start"
                >
                  <Icon :size="14" icon="ep:info-filled"></Icon>
                </el-tooltip>
              </div>
            </template>
            <template #isRefresh-form="{ row }">
              <el-checkbox v-model="row.isRefresh" true-value="Y" false-value="N" />
            </template>
            <template #tabI18n-form="{ row }">
              <I18nInput v-model="row.tabI18n" :def-name="row.tabName"></I18nInput>
            </template>
          </avue-crud>
        </template>
      </avue-crud>
    </div>
    <DesignPopup v-model="MEDialog.value" v-bind="MEDialog.params" :isBodyFull="true">
      <template #default>
        <el-container class="h-100%">
          <el-main class="p-0!">
            <MonacoEditor
              class="flex-1"
              v-model="MEData.value"
              v-bind="MEData.params"
            ></MonacoEditor>
          </el-main>
          <el-aside width="300px" v-if="MEDialog.otherParams">
            <TipView v-bind="MEDialog.otherParams"></TipView>
          </el-aside>
        </el-container>
      </template>
    </DesignPopup>
    <DesignPopup v-model="samplePopup" title="控件使用示例" :width="280">
      <template #default>
        <div class="text-center p-20px">
          <div class="b b-b-0 b-solid b-#f1f1f1 .dark:b-[var(--el-border-color-dark)]">
            <div
              v-for="(item, key) in controlPath"
              :key="key"
              class="h-50px flex items-center b-b b-b-solid b-#f1f1f1 .dark:b-[var(--el-border-color-dark)] pr-10px"
            >
              <div class="text-14px flex-1">{{ item.name }}</div>
              <el-button
                class="flex-basis-80px flex-shrink-0"
                size="small"
                type="primary"
                @click="copySampleStr(key)"
                >点击复制</el-button
              >
            </div>
          </div>
        </div>
      </template>
    </DesignPopup>
  </ContentWrap>
</template>
<script lang="ts" setup>
import { TipView } from '../general/components/index'
import * as ModuleApi from '@/api/design/module'
import * as FormApi from '@/api/design/form'
import * as TableApi from '@/api/design/table'
import * as ReportApi from '@/api/design/report'
import { ElLoading } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { useGroup } from '@/hooks/design/useGroup'
import { checkPermi } from '@/utils/permission'
import { ElButton } from 'element-plus'
import { I18nInput } from '@/components/LowDesign/src/shareControl/index'
import controlPath from '@/components/LowDesign/src/controlPath'
import useCopyText from '@/hooks/design/useCopyText'
import useMEDialog from '@/hooks/design/useMEDialog'
import {
  moduleScssEnhanceExample,
  controlInitExample
} from '@/components/LowDesign/src/utils/example'
import { formattingLengStr } from '@/utils/lowDesign'
defineOptions({ name: 'FormDesign' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const router = useRouter() // 路由
const { getCurrPermi } = useCrudPermi()
const { copyText } = useCopyText()
const { MEDialog, MEData, openMEDialog } = useMEDialog()
const loading = ref(true) // 列表的加载中
//表格配置
const tabsType = [
  { label: '默认风格', value: 'default' },
  { label: '卡片风格', value: 'card' },
  { label: '带边框的卡片风格', value: 'border-card' }
]
const tabsPosition = [
  { label: '上边', value: 'top' },
  { label: '左边', value: 'left' },
  { label: '右边', value: 'right' },
  { label: '下边', value: 'bottom' }
]
const moduleType = [
  { label: '表单开发', value: 'table' },
  { label: '自定义表单', value: 'form' },
  { label: '报表设计', value: 'report' },
  { label: '自定义模块', value: 'custom' }
]
const getRules = (label, type?) => {
  return [
    {
      required: true,
      message: (type == 'select' ? '请选择' : '请输入') + label,
      trigger: type == 'select' ? 'change' : 'blur'
    }
  ]
}
const tableOption = ref({
  align: 'center',
  headerAlign: 'center',
  searchMenuSpan: 6,
  searchMenuPosition: 'left',
  labelSuffix: ' ',
  dialogWidth: '90%',
  dialogFullscreen: false,
  dialogCustomClass: 'tabs-design-form',
  editBtn: false,
  delBtn: false,
  border: true,
  index: false,
  menuWidth: 180,
  span: 12,
  column: {
    lowSelectRadio: {
      label: '',
      display: false,
      width: 50,
      overHidden: false,
      fixed: true,
      showColumn: false
    },
    id: { label: '模块id', display: false, search: true, overHidden: true, width: 170 },
    moduleName: { label: '模块名称', display: false, search: true, overHidden: true },
    tabsType: { label: '风格类型', display: false, type: 'select', dicData: tabsType, width: 140 },
    tabsPosition: {
      label: '选项卡位置',
      display: false,
      type: 'select',
      dicData: tabsPosition,
      width: 120
    },
    updateTime: {
      label: '修改时间',
      type: 'datetime',
      format: 'YYYY-MM-DD HH:mm:ss',
      valueFormat: 'x',
      display: false,
      width: 160
    }
  },
  group: [
    {
      label: '基本信息',
      collapse: true,
      prop: 'group_info',
      column: {
        moduleName: { label: '模块名称', rules: getRules('模块名称') },
        groupModuleId: {
          label: '分组类型',
          type: 'tree',
          value: '',
          dicData: [],
          filterable: true,
          defaultExpandAll: true,
          props: { label: 'name', value: 'id' }
        },
        tabsType: {
          label: '风格类型',
          type: 'select',
          dicData: tabsType,
          value: 'border-card',
          clearable: false
        },
        tabsPosition: {
          label: '选项卡位置',
          type: 'select',
          dicData: tabsPosition,
          value: 'top',
          clearable: false
        }
      }
    },
    {
      label: '模块配置',
      collapse: true,
      prop: 'group_module',
      labelWidth: 20,
      column: {
        optionList: {
          hide: false,
          span: 24,
          dataType: 'array',
          value: [
            {
              $cellEdit: true,
              tabName: '',
              tabCode: '',
              moduleType: 'table',
              moduleValue: '',
              tabIcon: '',
              isLazy: false,
              isRefresh: false
            }
          ],
          rules: [
            {
              validator: (rule, value, callback) => {
                if (value?.length) callback()
                else callback(new Error('请添加模块信息'))
              },
              trigger: 'blur'
            }
          ]
        }
      }
    }
  ]
})
const tableForm = ref<any>({})
const tableData = ref([])
const tableSearch = ref({})
const tablePage = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})
const tableSelect = ref<any[]>([])
const radioValue = ref('')
const jsEnhanceData = ref({})
const designPop = ref({
  value: {},
  dialog: false,
  params: {}
})

const moduleOption = ref({
  addBtn: false,
  editBtn: false,
  addRowBtn: true,
  refreshBtn: false,
  columnBtn: false,
  addBtnText: '新增模块',
  menuWidth: 70,
  height: undefined,
  calcHeight: undefined,
  maxHeight: 300,
  index: true,
  column: {
    darg: { width: 45 },
    tabName: { label: '标签名称', cell: true, minWidth: 150, rules: getRules('标签名称') },
    tabCode: { label: '标签编码', cell: true, width: 150, rules: getRules('标签名称') },
    moduleType: {
      label: '模块类型',
      type: 'select',
      dicData: moduleType,
      value: 'table',
      cell: true,
      width: 140,
      clearable: false
    },
    moduleValue: {
      label: '模块内容',
      cell: true,
      minWidth: 180,
      rules: getRules('模块内容', 'select')
    },
    tabI18n: { label: '国际化配置', cell: true, width: 100 },
    tabIcon: { label: '标签图标', cell: true, width: 140 },
    isLazy: { label: '懒加载', cell: true, width: 70, value: 'N' },
    isRefresh: { label: '刷新数据', cell: true, width: 85, value: 'N' }
  }
})

const tableDicData = ref([])
const formDicData = ref([])
const reportDicData = ref([])
const samplePopup = ref(false)

const crudRef = ref()
const treeRef = ref()

const isUnload = ref(false)

const permission = getCurrPermi(['lideeyunji:tab'])
useCrudHeight(crudRef)
const {
  treeForm,
  treeOption,
  treeData,
  groupValue,
  treePermission,
  treeBeforeOpen,
  treeNodeContextmenu,
  treeNodeClick,
  getTreeData,
  treeUpdate,
  treeSave,
  treeDel
} = useGroup(treeRef, ModuleApi, () => resetChange())

const radioClick = (row) => {
  if (row.id == radioValue.value) {
    setTimeout(() => {
      radioValue.value = ''
      tableSelect.value = []
    }, 30)
  } else {
    tableSelect.value = [row]
  }
}

const delModuleTableRow = (index) => {
  tableForm.value.optionList.splice(index, 1)
}

const menuLeftHandle = (type) => {
  if (['js', 'scss'].includes(type) && tableSelect.value.length !== 1) {
    return message.warning('请勾选一条表格数据')
  }
  if (['js', 'scss'].includes(type)) openModuleEnhance(type)
}

const dropdownCommand = ({ index, type }) => {
  if (type == 'up' || type == 'down') {
    const delItem = tableForm.value.optionList.splice(index, 1)[0]
    nextTick(() =>
      tableForm.value.optionList.splice(type == 'up' ? index - 1 : index + 1, 0, delItem)
    )
  } else if (type == 'add') {
    tableForm.value.optionList.splice(index + 1, 0, { $cellEdit: true, moduleType: 'table' })
  }
}

const handleWebEnhance = (moduleId, enhanceType) => {
  return new Promise(async (resolve) => {
    let apiType = 'updateJsData'
    let apiData = {
      id: jsEnhanceData.value['id'],
      tabId: moduleId,
      jsType: enhanceType,
      jsJson: MEData.value.value
    }
    if (!apiData.id) {
      apiType = 'saveJsData'
      delete apiData.id
    }
    const data = await ModuleApi[apiType](apiData).catch(() => false)
    if (data) message.success('保存成功')
    resolve(data)
  })
}

const getAllDic = () => {
  TableApi.getAllDbDicData({ onlyTableName: 'Y' }).then(async (res) => {
    tableDicData.value = res.map((item) => {
      return { label: `${item.tableDescribe}[${item.tableName}]`, value: item.tableId }
    })
  })
  FormApi.getFormList({}).then((res) => {
    formDicData.value = res.records.map((item) => {
      return { label: item.desformName, value: item.id }
    })
  })
  ReportApi.getDbList({}).then((res) => {
    reportDicData.value = res.records.map((item) => {
      return { label: item.reportName, value: item.reportCode }
    })
  })
}

const menuHandle = async ({ type, row, index }) => {
  if (type == 'edit') crudRef.value.rowEdit(row, index)
  else if (type == 'test') router.push({ path: '/low/module/test/' + row.id })
  else if (type == 'routeAddress') showRouteAddress(row)
  else if (type.indexOf('Unlock') != -1) unlockEnhance(type, row)
  else if (type == 'del') rowDel(row)
}

const showRouteAddress = (row) => {
  const url = `module/view/` + row.id
  message.alert(`路由地址：</br>${url}`, '菜单的路由地址', {
    confirmButtonText: '复制',
    dangerouslyUseHTMLString: true,
    callback: (action) => {
      if (action == 'confirm') copyText(url)
    }
  })
}

const unlockEnhance = (type, row) => {
  const enhanceType = type.split('Unlock')[0]
  message.confirm(`是否强制解除${enhanceType}增强锁定？`, '提示').then(async () => {
    await ModuleApi.unlockJs(row.id, enhanceType)
    message.success('解除锁定成功')
    if (type.indexOf('Open') !== -1 && tableSelect.value.length) menuLeftHandle(enhanceType)
  })
}

const openModuleEnhance = async (enhanceType) => {
  loading.value = true
  jsEnhanceData.value = { jsJson: '' }
  const moduleId = tableSelect.value[0].id
  const detailData = await ModuleApi.getJsDetail({
    tabId: moduleId,
    type: enhanceType,
    lock: true
  }).catch(() => false)
  loading.value = false
  if (detailData === false) return
  if (detailData) {
    if (detailData.timeStr) {
      message
        .confirm(
          `<div>
        <div style="font-size:16px"><span style="font-size:14px">锁定操作人：</span>${detailData.userName}</div>
        <div style="font-size:16px"><span style="font-size:14px">开始锁定时间：</span>${detailData.timeStr}</div>
        <div style="color:#E6A23C">注：如果确认没有人正在编辑，可点击下方强制解锁</div>
      </div>`,
          '当前增强已锁定',
          {
            dangerouslyUseHTMLString: true,
            cancelButtonText: '关闭',
            confirmButtonText: '强制解锁'
          }
        )
        .then(() => {
          menuHandle({
            type: `${enhanceType}UnlockOpen`,
            row: tableSelect.value[0],
            index: tableSelect.value[0].$index
          })
        })
      return
    }
    if (detailData.jsJson) {
      jsEnhanceData.value = detailData
    }
  }
  let params = {
    title: `${enhanceType}增强 【${tableSelect.value[0].moduleName}】`,
    fullscreen: true,
    handleClose: async (done) => {
      await ModuleApi.unlockJs(moduleId, enhanceType)
      isUnload.value = false
      done()
    },
    footerBtn: [
      {
        params: { type: 'primary' },
        name: '保 存',
        icon: 'mingcute:save-line',
        loading: true,
        clickFun: async (loading) => {
          const id = await handleWebEnhance(moduleId, enhanceType)
          if (id) jsEnhanceData.value['id'] = id
          loading()
        }
      },
      {
        params: { type: 'success' },
        name: '保存并关闭',
        icon: 'mingcute:save-line',
        loading: true,
        clickFun: async (loading) => {
          const bool = await handleWebEnhance(moduleId, enhanceType)
          await ModuleApi.unlockJs(moduleId, enhanceType)
          loading()
          if (bool) {
            MEDialog.value.value = false
            isUnload.value = false
          }
        }
      },
      {
        params: {},
        name: '关 闭',
        icon: 'material-symbols:close',
        clickFun: async () => {
          await message.confirm('是否确认关闭？')
          await ModuleApi.unlockJs(moduleId, enhanceType)
          MEDialog.value.value = false
          isUnload.value = false
        }
      }
    ]
  }
  if (enhanceType == 'js') {
    params['providerType'] = 'moduleJsEnhance'
    params['otherParams'] = { type: 'simple', width: '300px', tipKeyList: ['ModuleJsEnhance'] }
    params['language'] = 'javascript'
    params['headerBtn'] = [
      {
        params: { type: 'success' },
        name: '控件使用示例',
        icon: 'jam:code-sample',
        clickFun: async () => (samplePopup.value = true)
      }
    ]
    if (!jsEnhanceData.value['jsJson']) {
      jsEnhanceData.value['jsJson'] = `return {

}`
    }
  } else if (enhanceType == 'scss') {
    params['language'] = 'scss'
    if (!jsEnhanceData.value['jsJson']) {
      jsEnhanceData.value['jsJson'] = moduleScssEnhanceExample(moduleId)
    }
  }

  openMEDialog({ params, prop: 'jsJson' }, jsEnhanceData.value)
  isUnload.value = true
}

const copySampleStr = (type) => {
  copyText(controlInitExample(type))
  samplePopup.value = false
}

const selectionChange = (data) => {
  tableSelect.value = data
}

/** 查询列表 */
const getTableData = async () => {
  loading.value = true
  let searchObj = {
    ...tableSearch.value,
    pageNo: tablePage.value.currentPage,
    pageSize: tablePage.value.pageSize
  }
  if (groupValue.value) searchObj['groupModuleId'] = groupValue.value
  for (let key in searchObj) if (searchObj[key] === '') delete searchObj[key]
  try {
    const data = await ModuleApi.getModuleList(searchObj)
    tableData.value = data.records
    tablePage.value.total = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const searchChange = (params, done) => {
  if (Object.keys(params).length && groupValue.value) {
    treeRef.value.setCurrentKey(0)
    groupValue.value = 0
  }
  tablePage.value.currentPage = 1
  getTableData().finally(() => {
    done()
  })
}

/** 清空按钮操作 */
const resetChange = () => {
  searchChange({}, () => {})
}

const sizeChange = (pageSize) => {
  tablePage.value.pageSize = pageSize
  resetChange()
}

const currentChange = (currentPage) => {
  tablePage.value.currentPage = currentPage
  getTableData()
}

/** 表单打开前 */
const beforeOpen = async (done, type) => {
  const groupData = cloneDeep(treeData.value)
  const groupModuleId = tableOption.value.group[0].column.groupModuleId
  if (groupModuleId) groupModuleId.dicData = groupData[0].children
  if (['edit', 'view'].includes(type) && tableForm.value['id']) {
    loading.value = true
    const data = await ModuleApi.getModuleDetail(tableForm.value['id'])
    tableForm.value = {
      ...data.tab,
      optionList: data.optionList.map((item) => {
        if (type == 'edit') item.$cellEdit = true
        return item
      })
    }
    loading.value = false
  }
  if (type == 'add' && groupValue.value) {
    tableForm.value.groupModuleId = groupValue.value
  }
  done()
}

const initI18nData = (list) => {
  if (!list?.length) return []
  return list.map((item) => {
    item.tabI18n = formattingLengStr(item.tabI18n, item.tabName)
    return item
  })
}

/** 新增操作 */
const rowSave = async (form: object, done, loading, isId?) => {
  const elLoading = ElLoading.service({ fullscreen: true })
  const saveData = { tab: { ...form }, optionList: initI18nData(form['optionList']) }
  delete saveData.tab['optionList']
  let bool = await ModuleApi.saveModuleData(saveData).catch(() => false)
  if (bool) {
    message.success(t('common.createSuccess'))
    resetChange()
    if (isId) done(bool)
    else done()
  } else loading()
  elLoading.close()
}

/** 编辑操作 */
const rowUpdate = async (form, index, done, loading, onData?) => {
  const editData = { tab: { ...form }, optionList: initI18nData(form['optionList']) }
  delete editData.tab['optionList']
  let bool = await ModuleApi.updateModuleData(editData).catch(() => false)
  if (bool) {
    message.success(t('common.updateSuccess'))
    if (!onData) getTableData()
    done()
  } else loading()
}

/** 删除按钮操作 */
const rowDel = async (data) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ModuleApi.deleteModuleData(data instanceof Array ? data : [data.id])
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getTableData()
  } catch {}
}

const beforeUnload = (event) => {
  if (isUnload.value) return (event.returnValue = '您确定要关闭页面吗？')
}

/** 初始化 **/
onMounted(async () => {
  window.addEventListener('beforeunload', beforeUnload)
  getTableData()
  getTreeData()
  getAllDic()
})

onBeforeUnmount(() => {
  window.removeEventListener('beforeunload', beforeUnload)
})
</script>

<style lang="scss" scoped>
.table-content {
  max-width: calc(100% - 190px);
}
</style>
<style lang="scss">
.form-design-address-box {
  .el-message-box__container {
    display: block;
  }
}
</style>
<style lang="scss">
.tabs-design-form {
  .el-dialog__body {
    padding-top: 0 !important;
  }

  .avue-crud {
    .avue-crud__empty {
      padding: 0;

      .el-empty {
        padding: 0;
      }

      .el-empty__description {
        margin: 0;
      }
    }
  }
}
</style>
