<script setup name="Discover">
import { onMounted, ref, toRefs } from 'vue'
import { Split } from 'view-ui-plus';
import { ElMessage } from 'element-plus'
import { parseTime } from '@/utils/ruoyi'
import CollapseView from '@/components/CollapseView/index.vue'
import AddEncryption from './modules/AddEncryption.vue' // 加密表单
import AddKey from './modules/AddKey.vue' // 密钥表单
import ModalPop from "@/components/EditPop/ModalPop.vue"
import UploadModule from './modules/UploadModule.vue' // 上传模块

import { query, initEncryptionTypeList, getDictinaryTypes, deleteType, delSecretKey, exportExcel, importfile } from '@/api/ruleConfig/encryption'

const splitNum = ref(0.31) // 左右分割比例
const collapseList = ref([]) // 左侧列表数据
const encryptionTypeList = ref([]) // 加密类型列表
const dictinaryTypes = ref([]) // 字典类型列表
const typeNameList = ref([]) // 分类名称列表
const keyNameList = ref([]) // 分类名称列表

const data = reactive({
  encryptionForm: {},
  keyForm: {},
  queryParams: {
    encryption_name: ''
  },
  delData: {
    id: ''
  }
});

const { encryptionForm, keyForm, queryParams, delData } = toRefs(data);
const rightType = ref('encryption') // 右侧展示类型
const modalData = reactive({
  show: false,
  text: '',
  icon: 'error',
  cancel: true,
  type: ''
})

const modalPopData = reactive({
  show: false,
  title: '',
  type: 'encryption'
})

// 获取数据
const getCollapse = (type) => {
  query(queryParams.value).then(res => {
    const { data } = res
    collapseList.value = data.map(item => {
      const list = item.list.map(itemTwo => {
        return {
          ...itemTwo,
          name: itemTwo.secret_key_name,
          isCheck: false,
          isDelete: true,
        }
      })
      return {
        ...item,
        dataarea: item.encryption_name,
        list: list,
        isAdd: true,
        isView: true,
        isDelete: true,
      }
    })
    if (type === 'edit') return
    if (collapseList.value.length <= 0) return
    modalData.type = 'encryption'
    encryptionForm.value = collapseList.value[0]
  })
}

// 获取加密类型列表
const getInitEncryptionTypeList = () => {
  initEncryptionTypeList({}).then(res => {
    const { data } = res
    encryptionTypeList.value = data
  })
}

// 新增关闭
const modalPopCancel = () => {
  modalPopData.show = false
}

// 新增加密
const addDomainClick = (item) => {
  typeNameList.value = []
  collapseList.value.forEach(item => { 
    typeNameList.value.push(item.encryption_name)
  })
  modalPopData.title = '新增加密'
  modalPopData.type = 'encryption'
  encryptionForm.value = {}
  modalPopData.show = true
}

// 新增密钥
const collapseAdd = (item) => {
  keyNameList.value = []
  item.list.forEach(item => {
    keyNameList.value.push(item.secret_key_name)
  })
  const { encryption_name, encryption_type, id } = item
  modalPopData.title = '新增密钥'
  modalPopData.type = 'key'
  keyForm.value = {
    encryption_name: encryption_name,
    encryption_type: encryption_type,
    encryption_id: id
  }
  modalPopData.show = true
}

// 删除加密
const collapseMainDeletion = (item) => {
  const { encryption_name } = item
  delData.value = item
  modalData.type = 'encryption'
  modalData.cancel = false
  modalData.icon = 'error'
  modalData.text = '删除后无法恢复，是否确认删除[' + encryption_name + ']?'
  modalData.show = true
}

// 删除密钥
const collapseDelete = (item) => {
  const { secret_key_name } = item
  delData.value = item
  modalData.type = 'key'
  modalData.cancel = true
  modalData.icon = 'error'
  modalData.text = '删除后无法恢复，是否确认删除[' + secret_key_name + ']?'
  modalData.show = true
}

// 提示回调
const modalConfirm = () => {
  if (modalData.type === 'encryption') {
    const { id } = delData.value
    deleteType({ encryptionId: id }).then(res => {
      const { flag } = res
      if (flag) {
        ElMessage.success('删除成功')
        getCollapse()
      } else {
        ElMessage.error('删除失败')
      }
    })
  } else if (modalData.type === 'key') {
    const { id } = delData.value
    delSecretKey({ keyId: id }).then(res => {
      const { flag } = res
      if (flag) {
        ElMessage.success('删除成功')
        getCollapse()
      } else {
        ElMessage.error('删除失败')
      }
    })
  }
  modalData.show = false
}

// 加密查看
const collapseView = (item) => {
  typeNameList.value = []
  collapseList.value.forEach(item => { 
    typeNameList.value.push(item.encryption_name)
  })
  encryptionForm.value = item
  rightType.value = 'encryption'
}

// 密钥点击监听
const collapseChange = (itemData) => {
  const { parentItem, item } = itemData
  const { encryption_name, encryption_type } = parentItem
  keyNameList.value = []
  parentItem.list.forEach(itemLi => {
    keyNameList.value.push(itemLi.secret_key_name)
  })
  console.log('密钥点击监听', item)
  keyForm.value = { ...item, ...{ encryption_name: encryption_name, encryption_type: encryption_type } }
  rightType.value = 'key'
}

// 新增确认
const AddFormConfirm = (item) => {
  if (modalPopData.type === 'encryption') {
    getCollapse(item)
  } else if (modalPopData.type === 'key') {
    getCollapse(item)
  } else if (modalPopData.type === 'upload') {
    getCollapse()
  }
  modalPopData.show = false
}

//  备份导出excel
const exportExcelFunc = () => {
  const name = parseTime(new Date(), '{y}-{m}-{d}')
  exportExcel({}).then(response => {
    const blob = new Blob([response], { type: 'application/vnd.ms-excel,charset=utf-8' });
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = `${name}加密规则.xls`
    link.click()
    URL.revokeObjectURL(link.href)
    ElMessage.success('导出成功')
  })
}

// 导入功能
const importClick = () => {
  modalPopData.title = '上传文件'
  modalPopData.type = 'upload'
  modalPopData.show = true
}

onMounted(() => {
  getCollapse()
  getInitEncryptionTypeList()
})

</script>
<template>
  <div class="app-container scroller">
    <PageTitle>
      <template #title>
        加密规则
      </template>
    </PageTitle>
    <div class="app-container__body">
      <Split v-model="splitNum">
        <template #left>
          <div class="demo-split-pane" style="padding: 0 38px 10px 0;width: 100%;overflow: auto;height: 100%;display: flex;flex-direction: column;">
            <div class="mb20" style="display: flex;flex-direction: row-reverse;">
              <el-button icon="Upload" type="success" @click="importClick">恢复</el-button>
              <el-button class="mr10" icon="Download" type="primary" @click="exportExcelFunc">备份</el-button>
            </div>
            <div class="mb20" style="display: flex;align-items: center;justify-content: space-between;">
              <el-input class="mr20" v-model="queryParams.encryption_name" placeholder="加密方式搜索">
                <template #suffix>
                  <el-icon style="vertical-align: middle;cursor: pointer;" @click="getCollapse">
                    <search />
                  </el-icon>
                </template>
              </el-input>
              <el-button type="primary" icon="Plus" @click="addDomainClick">新增加密</el-button>
            </div>
            <el-scrollbar style="width: 100%;flex: 1;padding-right: 38px;">
              <CollapseView :list="collapseList" @add="collapseAdd" @mainDeletion="collapseMainDeletion"
              @childDelete="collapseDelete" @change="collapseChange" @view="collapseView" />
            </el-scrollbar>
          </div>
        </template>
        <template #right>
          <div class="demo-split-pane">
            <div class="right">
              <div class="right-title">
                <el-icon>
                  <info-filled />
                </el-icon>
                <span style="margin-left: 5px;">{{ rightType === 'encryption' ? '加密定义' : '密钥定义' }}</span>
              </div>
              <div class="right-content">
                <AddEncryption :itemData="encryptionForm" :encryptionTypeDict="encryptionTypeList"
                  :typeNameDict="typeNameList" type="edit" v-if="rightType === 'encryption'" @cancel="modalPopCancel"
                  @confirm="AddFormConfirm" />
                <AddKey :itemData="keyForm" :encryptionTypeDict="encryptionTypeList" :keyNameDict="keyNameList"
                  type="edit" v-if="rightType === 'key'" @cancel="modalPopCancel" @confirm="AddFormConfirm" />
              </div>
            </div>
          </div>
        </template>
      </Split>
    </div>
    <!-- 提示框 -->
    <Modal v-model="modalData.show" :icon="modalData.icon" :cancel="modalData.cancel" :text="modalData.text"
      @confirm="modalConfirm"></Modal>

    <!-- 新增加密 / 密钥 -->
    <ModalPop :width="modalPopData.type === 'upload' ? '600' : '850'" v-model="modalPopData.show" :title="modalPopData.title" @cancel="modalPopCancel">
      <template #content>
        <AddEncryption :itemData="encryptionForm" :encryptionTypeDict="encryptionTypeList" :typeNameDict="typeNameList"
          type="add" @cancel="modalPopCancel" @confirm="AddFormConfirm" v-if="modalPopData.type === 'encryption'" />
        <AddKey :itemData="keyForm" :encryptionTypeDict="encryptionTypeList" :keyNameDict="keyNameList" type="add"
          @cancel="modalPopCancel" @confirm="AddFormConfirm" v-if="modalPopData.type === 'key'" />
        <UploadModule @cancel="modalPopCancel" @confirm="AddFormConfirm" v-if="modalPopData.type === 'upload'" />
      </template>
    </ModalPop>
  </div>
</template>

<style lang="scss" scoped>
.app-container__body {
  // height: calc(
  //   100vh - var(--navbar-height) - var(--container-pd) - var(--container-pd)
  // ) !important;
  .right {
    padding: 6px 10px 10px;
    height: 100%;
    &-title {
      padding: 0px 0px 10px 10px;
      display: flex;
      align-items: center;
      font-weight: 700;
      color: #515a6e;
    }
    &-content {
      padding: 10px 0px;
      width: 80%;
      margin: 20px auto;
    }
  }
}
</style>