<script setup name="AssetLibrary">
import { ref, toRefs, reactive, getCurrentInstance, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import QueryForm from './QueryForm.vue'
import FormGroup from './modules/formGroup.vue'
import img from '@/assets/images/assetLibrary/index.js'
import { queryAll, checkDatasystemUsed, del } from '@/api/assetLibrary/index'
import { getCueryCharset } from "@/api/assetLibrary/dict";
import ModalPop from "@/components/EditPop/ModalPop.vue"
import AddEdit from "./addEdit.vue"

const emit = defineEmits(['page'])

const { proxy } = getCurrentInstance()

const data = reactive({
  form: {
    name: ''
  },
  queryParams: {
    sysname: '',
    dbtype: '',
    ip: '',
    userId: '1',
    projectId: ''
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

const modalData = reactive({
  show: false,
  text: ''
})
const activeName = ref('') // 内部切换
// 数据源信息
const dataSource = reactive({
  current: 0, // 当前索引
  currentId: '', // 当前id
  currentFlag: '',
  list: [], // 数据源列表
  del: {
    id: '',
    sysname: ''
  }
})

// 新增弹窗
const dialogVisible = ref(false)

// 新增
const handleAdd = () => {
  // emit('page', 'add')
  dialogVisible.value = true
}

// 筛选查询
const onQuery = () => {
  console.log('onQuery')
  getList()
}
// 查询组件事件重置
const onReset = (formQuery) => {
  console.log('onReset')
  formQuery.resetFields()
  getList()
}

// 预览
const onPreview = (index) => {
  dataSource.current = index
  dataSource.currentId = dataSource.list[dataSource.current].items[0].id
  dataSource.currentFlag = dataSource.list[dataSource.current].items[0].flag
  activeName.value = dataSource.currentId
}

// 删除
const onDelete = (val) => {
  const { id, sysname } = val
  checkDatasystemUsed({ id: id }).then(res => {
    const flag = { res }
    if (flag) {
      dataSource.current = 0
      dataSource.del.id = id
      dataSource.del.sysname = sysname
      modalData.text = `删除后无法恢复，是否确认删除[${sysname}]？`
      modalData.show = true
    }
  })
}

// 确认删除回调
const modalConfirm = () => {
  del(dataSource.del).then(res => {
    const flag = { res }
    if (flag) {
      ElMessage.success({
        message: '删除成功',
        type: 'success',
      })
      getList()
    }
  })
  modalData.show = false
}

// 编辑成功回调
const onConfirm = () => {
  // console.log('编辑成功')
  getList()
}

// 列表查询
const getList = () => {
  queryAll(queryParams.value).then(res => {
    // console.log(res)
    dataSource.list = []
    if (res.data.length <= 0) return
    const groupedItems = res.data.reduce((acc, item) => {
      // 如果acc中还没有当前dbtype的键，则创建一个空数组
      if (!acc[item.dbtype]) {
        acc[item.dbtype] = [];
      }
      // 将当前项添加到对应dbtype的数组中
      acc[item.dbtype].push(item);
      return acc;
    }, {});

    // 将分组对象转换为数组（可选步骤，如果你需要数组形式的输出）
    dataSource.list = Object.keys(groupedItems).map(key => ({
      dbtype: key,
      items: groupedItems[key]
    }));
    dataSource.currentId = dataSource.list[dataSource.current].items[0].id
    dataSource.currentFlag = dataSource.list[dataSource.current].items[0].flag
    activeName.value = dataSource.currentId
  })
}

const tabClick = (tab) => {

  const { props, index } = tab
  activeName.value = props.name
  dataSource.currentId = activeName.value
  dataSource.currentFlag = dataSource.list[dataSource.current].items[index].flag
}

onMounted(() => {
  getCueryCharset()
  getList()
})
</script>

<template>
  <div class="app-container scroller">
    <div class="app-container__body" style="padding: 30px 0 10px 0;">
      <IconTitle :icon="img.pageTitle" title="资产库" />
      <query-form ref="QueryFormRef" v-model="queryParams" @query="onQuery" @reset="onReset" @add="handleAdd" />
      <div class="mainBox">
        <div class="mainBox-left">
          <el-scrollbar>
            <div class="scroll">
              <div class="left-card" :class="dataSource.current === index ? 'active' : ''"
                v-for="(item, index) in dataSource.list" :key="index" @click="onPreview(index)">
                <img class="img" :src="img[item.dbtype]" alt="">
                <img class="arrow" v-if="dataSource.current === index" :src="img.arrow" alt="">
              </div>
            </div>
            <div class="line"></div>
            <div class="lineBg"></div>
          </el-scrollbar>
        </div>
        <div class="mainBox-right">
          <div class="line"></div>
          <el-empty description="暂无数据" v-if="dataSource.list.length <= 0"
            style="position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);"></el-empty>
          <div class="right-container" v-if="dataSource.list.length > 0">
            <el-tabs v-model="activeName" @tab-click="tabClick">
              <el-tab-pane :label="item.sysname" :name="item.id"
                v-for="(item, index) in dataSource.list[dataSource.current].items" :key="index"></el-tab-pane>
            </el-tabs>
            <div class="form-box mt20" v-if="dataSource.list.length > 0">
              <el-scrollbar>
                  <FormGroup :id="dataSource.currentId" :flag="dataSource.currentFlag" page="edit" @confirm="onConfirm"
                  @on-delete="onDelete" />
              </el-scrollbar>
            </div>
          </div>
        </div>
      </div>
    </div>
    <Modal v-model="modalData.show" icon="error" :cancel="true" :text="modalData.text" @confirm="modalConfirm"></Modal>
    
    <!-- 新增 -->
    <AddEdit v-model:visible="dialogVisible" @confirm="onConfirm" />
  </div>
</template>

<style lang="scss" scoped>
.mainBox {
  flex: 1;
  width: 100%;
  display: flex;
  overflow: hidden;

  &-left {
    position: relative;
    padding-left: 25px;
    width: 134px;
    height: 100%;

    .line {
      position: absolute;
      top: 0;
      right: 6px;
      width: 3px;
      height: 100%;
      background: rgba(204, 204, 204, 1);
      border-radius: 3px 0 0 3px;
    }
    .lineBg {
      position: absolute;
      top: 0;
      right: 0;
      width: 6px;
      height: 100%;
      background: #fff;
      border-top: 2px solid rgba(33, 103, 217, 1);
    }

    .scroll {
      padding: 17px 0;
      overflow: hidden;

      .left-card {
        position: relative;
        margin-bottom: 8px;
        width: 80px;
        height: 50px;
        border-radius: 5px;
        border: 1px solid rgba(134, 191, 252, 1);
        cursor: pointer;

        .img {
          width: 100%;
          height: 100%;
        }
        .arrow {
          z-index: 1;
          position: absolute;
          top: -1px;
          right: -29px;
          width: 8px;
          height: 50px;
        }
      }

      .left-card:last-child {
        margin-bottom: 0;
      }

      .active {
        background: rgba(255, 255, 255, 1);
        border: 1px solid rgba(33, 103, 217, 1);
      }
    }
  }
  &-right {
    position: relative;
    flex: 1;
    height: 100%;
    background: rgba(255, 255, 255, 1);
    border-radius: 0 3px 3px 0;
    .line {
      width: 100%;
      height: 2px;
      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%
      );
    }
    .right-container {
      height: calc(100% - 2px);
      padding: 20px 33px;
      display: flex;
      flex-direction: column;
      .form-box {
        flex: 1;
        overflow: hidden;
        :deep(inputBox) {
          margin-left: 1px;
          background: #f5fcff;
        }
        :deep(.foundationBox) {
          border-radius: 5px;
          background: #ebebeb;
          border: 1px solid #1db2f5;
          overflow: hidden;
        }
        :deep(.el-form-item__label) {
          height: 40px;
          line-height: 40px;
          background: #f5fcff;
          color: rgba(148, 148, 148, 1);
        }
        :deep(.el-form-item) {
          margin-bottom: 1px;
        }
        :deep(.el-input),
        :deep(.el-select),
        :deep(.el-select__wrapper) {
          height: 40px;
          line-height: 40px;
        }
        :deep(.is-disabled) {
          background: #f5fcff;
          .el-input__wrapper {
            background: #f5fcff;
            box-shadow: none;
            border-radius: 0;
          }
          .el-input__inner {
            -webkit-text-fill-color: rgba(53, 64, 79, 1);
          }
        }
        :deep(.is-disabled).el-select__wrapper {
          background: #f5fcff;
          box-shadow: none;
          border-radius: 0;
          .el-select__tags-text {
            color: rgba(53, 64, 79, 1);
          }
        }
      }
    }
  }
}
</style>