<script setup name="Discover">
import { onMounted, ref, toRefs } from 'vue'
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 pageIcon from '@/assets/images/ruleConfig/encryptionPage.png'

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

const fatherIndex = ref(0) // 父级索引
const currentId = ref('')
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) {
      modalData.type = 'encryption'
      encryptionForm.value = {}
      fatherIndex.value = null
      return
    }
    modalData.type = 'encryption'
    encryptionForm.value = collapseList.value[0]
    currentId.value = encryptionForm.value.id
    fatherIndex.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 = (val) => {
  const { index, item } = val
  typeNameList.value = []
  collapseList.value.forEach(item => { 
    typeNameList.value.push(item.encryption_name)
  })
  fatherIndex.value = index
  encryptionForm.value = item
  rightType.value = 'encryption'
  currentId.value = encryptionForm.value.id
}

// 密钥点击监听
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'
  currentId.value = keyForm.value.id
}

// 新增确认
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">
    <div class="app-container__body">
      <IconTitle :icon="pageIcon" title="加密规则" />
      <div class="box">
        <div class="left">
          <div class="searchBox">
            <el-input v-model="queryParams.encryption_name" placeholder="加密方式搜索" style="width: 325px;margin-bottom: 15px;">
              <template #prefix>
                <el-icon>
                  <search />
                </el-icon>
              </template>
              <template #append>
                <el-button icon="search" class="searchBut" @click="getCollapse">搜索</el-button>
              </template>
            </el-input>
            <el-button type="primary" icon="Plus" class="addBut" @click="addDomainClick">新增加密</el-button>
            <div style="height: 40px;display: flex;align-items: center;margin-left: 14px;" >
              <el-button class="mr8" icon="Download" type="primary" plain @click="exportExcelFunc">备份</el-button>
              <el-button icon="Upload" type="primary" plain @click="importClick">恢复</el-button>
            </div>
          </div>
          <div class="collapseView">
            <CollapseView :list="collapseList" :fatherIndex="fatherIndex" :currentId="currentId" @add="collapseAdd" @mainDeletion="collapseMainDeletion"
              @childDelete="collapseDelete" @change="collapseChange" @view="collapseView" />
          </div>
        </div>
        <div class="right">
          <div class="line"></div>
          <div style="padding: 26px 28px 0 28px;position: relative;flex: 1;">
            <DividerTitle :title-name="rightType === 'encryption' ? '加密定义' : '密钥定义'" />
            <div class="right-content" v-if="collapseList.length > 0">
              <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>
            <el-empty description="暂无数据" v-if="collapseList.length <= 0"
            style="position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);"></el-empty>
          </div>
        </div>
      </div>
    </div>
    <!-- 提示框 -->
    <Modal v-model="modalData.show" :icon="modalData.icon" :cancel="modalData.cancel" :text="modalData.text"
      @confirm="modalConfirm"></Modal>

    <!-- 新增加密 / 密钥 -->
    <el-dialog :title="modalPopData.title" v-model="modalPopData.show" :before-close="modalPopCancel" :width="modalPopData.type === 'upload' ? '600' : '850'">
      <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'" />
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.app-container__body {
  padding: 20px 0 0 0;
  .box {
    display: flex;
    flex: 1;
    overflow: hidden;
    .left {
      margin-right: 30px;
      width: 565px;
      overflow: auto;
      height: 100%;
      display: flex;
      flex-direction: column;
      .searchBox{
        display: flex;
        width: 100%;
        .searchBut {
          height: 40px;
          background: var(--el-color-primary);
          color: var(--el-color-white);
          border-radius: 0px 5px 5px 0px;
        }
        .addBut{
          height: 40px;
          margin-left: 10px;
          background: rgba(0, 189, 207, 1);
          border-color: rgba(0, 189, 207, 1);
        }
      }
      .collapseView {
        width: 100%;
        flex: 1;
        overflow: hidden;
      }
    }
    .right {
      display: flex;
      flex-direction: column;
      flex: 1;
      height: 100%;
      background: rgba(255, 255, 255, 1);
      .line {
        width: 100%;
        height: 2px;
        border-radius: 5px 5px 0px 0px;
        background: linear-gradient(
          90deg,
          rgba(33, 103, 217, 1) 0%,
          rgba(17, 200, 250, 1) 34.03%,
          rgba(33, 103, 217, 1) 64.58%,
          rgba(48, 128, 255, 1) 100%
        );
      }
      &-content {
        width: 100%;
        .openEditor {
          position: absolute;
          bottom: 0;
          right: 0;
        }
        :deep(.formBox) {
          border-radius: 5px;
          background: #ebebeb;
          border: 1px solid rgba(29, 178, 245, 1);
          overflow: hidden;
          .el-form-item__content {
            border-left: 1px solid #ebebeb;
            background: #f5fcff;
          }
          .el-form-item__label {
            height: 40px;
            line-height: 40px;
            background: #f5fcff;
            color: rgba(148, 148, 148, 1);
          }
          .el-form-item {
            margin-bottom: 1px;
            background: #f5fcff;
          }
          .el-input {
            height: 40px;
            line-height: 40px;
          }
          .is-disabled {
            background: #f5fcff;
            .el-input__wrapper,.el-textarea__inner {
              background: #f5fcff;
              box-shadow: none;
              border-radius: 0;
            }
            .el-input__inner,.el-textarea__inner {
              -webkit-text-fill-color: rgba(53, 64, 79, 1);
            }
          }
          .el-form-item__error {
            top: 30% !important;
            left: auto !important;
            right: 89px !important;
          }
        }
      }
      &-btn {
        padding: 20px 20px 20px 100px;
        display: flex;
        justify-content: center;
      }
    }
  }
}
</style>