<template>
  <div class="guns-layout">
    <div class="guns-layout">
      <div class="guns-layout">
        <guns-split-layout :resizable="false">
          <div class="guns-layout-sidebar width-100 p-t-12">
            <div class="sidebar-content">
              <list-type-tree @defaultSelect="defaultSelect" @selectNull="selectNull" @treeSelect="treeSelect"></list-type-tree>
            </div>
          </div>
          <template #content>
            <div class="guns-layout-content">
              <div class="guns-layout">
                <div class="guns-layout-content-header p-t-12">
                  <span>{{ businessTypeName }}</span>
                  <a-space :size="16">
                    <a-input
                      v-model:value="where.searchText"
                      placeholder="业务名称、编码"
                      @pressEnter="reload"
                      class="search-input"
                      allowClear
                      style="width: 300px; height: 36px"
                    >
                      <template #prefix>
                        <icon-font iconClass="icon-opt-search"></icon-font>
                      </template>
                    </a-input>
                    <a-button type="primary" class="border-radius" @click="openAddEdit()"><plus-outlined />新建</a-button>
                  </a-space>
                </div>
                <div class="guns-layout-content-application">
                  <div class="content-mian">
                    <div class="content-mian-body">
                      <div class="table-content" style="height: 100%">
                        <a-spin :spinning="loading" :delay="100">
                          <div style="height: calc(100% - 40px); overflow-y: auto; overflow-x: hidden">
                            <a-row :gutter="[16, 16]">
                              <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="6" :xxl="6" v-for="item in busiessList" :key="item.businessId"
                                ><div class="modular-item" @click="businessDesign(item, 'sheet')">
                                  <div class="modular-item-header">
                                    <div class="modular-item-header-top">
                                      <div class="modular-item-header-top-left">
                                        <img
                                          :src="filePreviewUrl + item.businessIconFileId"
                                          alt=""
                                          v-if="item.businessIconType == 1"
                                          class="modular-item-header-top-left-img"
                                        />
                                        <img
                                          :src="activeIconSrc(item)"
                                          alt=""
                                          v-if="item.businessIconType == 2"
                                          class="modular-item-header-top-left-img"
                                        />
                                        <div class="modular-item-header-top-left-content">
                                          <div class="modular-item-header-top-left-content-title">
                                            {{ item.businessName }}
                                          </div>
                                          <div class="modular-item-header-top-left-content-code">
                                            {{ item.businessCode }}
                                          </div>
                                        </div>
                                      </div>
                                      <div class="modular-item-header-top-right">
                                        <a-popover
                                          placement="bottomRight"
                                          overlayClassName="modular-pop"
                                          v-model:visible="item.showMore"
                                          trigger="click"
                                          @click.stop="moreClick(item)"
                                        >
                                          <template #content>
                                            <div class="btn-item" @click.stop="openAddEdit(item)">
                                              <icon-font iconClass="icon-opt-bianji" color="#60666B"></icon-font>
                                              <span class="btn-item-label">编辑</span>
                                            </div>
                                            <div class="btn-item" @click.stop="remove(item)">
                                              <icon-font iconClass="icon-opt-shanchu" color="#60666B" fontSize="20px"></icon-font>
                                              <span class="btn-item-label">删除</span>
                                            </div>
                                            <div class="btn-item" @click.stop="businessPreview(item)" v-permission="['APP_DESIGN_PREVIEW']">
                                              <icon-font iconClass="icon-opt-yulan" color="#60666B" fontSize="20px"></icon-font>
                                              <span class="btn-item-label">预览</span>
                                            </div>
                                            <div class="btn-item" @click.stop="initExcel(item)">
                                              <img src="@/assets/project/excel.svg" alt="" />
                                              <span class="btn-item-label">基于Excel初始化</span>
                                            </div>
                                            <div class="btn-item" @click.stop="exportSheetClick(item)">
                                              <icon-font iconClass="icon-opt-shangchuandaoshujuku" color="#60666B"></icon-font>
                                              <span class="btn-item-label">导出建表语句</span>
                                            </div>
                                          </template>
                                          <more-outlined class="more-btn" title="更多" />
                                        </a-popover>
                                      </div>
                                    </div>
                                    <a-row class="modular-item-center" :gutter="16">
                                      <a-col :span="24" class="modular-item-center-col">
                                        <div class="modular-item-center-label">归属部门：</div>
                                        <div class="modular-item-center-value">{{ item?.ownershipDeptIdWrapper }}</div>
                                      </a-col>
                                      <a-col :span="12" class="modular-item-center-col">
                                        <div class="modular-item-center-label">数据表：</div>
                                        <div class="modular-item-center-value">{{ item?.tableCount }}</div>
                                      </a-col>
                                      <a-col :span="12" class="modular-item-center-col">
                                        <div class="modular-item-center-label">表单：</div>
                                        <div class="modular-item-center-value">{{ item?.formCount }}</div>
                                      </a-col>
                                      <a-col :span="12" class="modular-item-center-col">
                                        <div class="modular-item-center-label">字典：</div>
                                        <div class="modular-item-center-value">{{ item?.dictCount }}</div>
                                      </a-col>
                                      <a-col :span="12" class="modular-item-center-col">
                                        <div class="modular-item-center-label">视图：</div>
                                        <div class="modular-item-center-value">{{ item?.viewCount }}</div>
                                      </a-col>
                                    </a-row>
                                    <a-row class="modular-item-header-bottom">
                                      <span>{{ item?.createUserWrapper }}</span>
                                      <span>{{ item?.createTime }}</span>
                                    </a-row>
                                  </div>
                                </div></a-col
                              >
                            </a-row>
                            <a-empty v-show="busiessList?.length == 0" :image="Empty.PRESENTED_IMAGE_SIMPLE" class="empty"></a-empty>
                          </div>
                          <a-pagination
                            :current="pageNo"
                            :page-size="pageSize"
                            :total="total"
                            v-if="total > 0"
                            size="small"
                            class="pagination"
                            show-size-changer
                            show-quick-jumper
                            @change="pageSizeChange"
                            @showSizeChange="showSizeChange"
                            :show-total="total => `共${total}条`"
                          />
                        </a-spin>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </template>
        </guns-split-layout>
      </div>
    </div>

    <!-- 新增编辑弹框 -->
    <ListAddEdit
      v-model:visible="showEdit"
      v-if="showEdit"
      :data="current"
      @done="reload"
      :businessCategoryId="where.businessCategoryId"
      :iconList="iconList"
    />
    <!-- 导出建表语句 -->
    <ExportSheet v-model:visible="showExportSheet" v-if="showExportSheet" :data="current" />
  </div>
</template>

<script setup name="MidAppList">
import { useGeneratorStore } from '@/store/modules/generator';
import { onMounted, computed, ref, createVNode } from 'vue';
import { BusinessApi } from './api/BusinessApi';
import { message, Modal, Empty } from 'ant-design-vue/es';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import ListTypeTree from './components/list-type/list-type-tree.vue';
import ListAddEdit from './components/list/list-add-edit.vue';
import ExportSheet from './components/list/export-sheet.vue';
import { useRouter } from 'vue-router';
import { API_BASE_PREFIX } from '@/config/setting';
import { getApiModularIcon } from '@/utils/common/util';

defineOptions({
  name: 'MidAppList'
});

const router = useRouter();

const generatorStore = useGeneratorStore();
// 当前选中应用数据
const buinessSelectAppData = computed(() => generatorStore.buinessSelectAppData ?? {});

// 文件预览接口
const filePreviewUrl = ref(`${API_BASE_PREFIX}/sysFileInfo/public/preview?fileId=`);

// 搜索条件
const where = ref({
  searchText: '',
  businessCategoryId: ''
});

// 当前行数据
const current = ref(null);
// 是否显示新增编辑弹框
const showEdit = ref(false);
// 导出建表语句
const showExportSheet = ref(false);

// 业务分类名称
const businessTypeName = ref('业务列表');

// 图片列表
const iconList = ref(getApiModularIcon());

// 业务列表
const busiessList = ref([]);

// 当前所在页数
const pageNo = ref(1);
// 当前分页条数
const pageSize = ref(24);
// 总数据
const total = ref(0);

const loading = ref(false);

/**
 * 图标
 */
const activeIconSrc = computed(() => {
  return item => {
    const icon = iconList.value.find(t => t.name_suffix == item.businessIcon);
    return icon ? icon.url : '';
  };
});

onMounted(() => {
  getBusiessList();
});

// 获取业务列表
const getBusiessList = () => {
  if (where.value.businessCategoryId) {
    loading.value = true;
    let params = {
      ...where.value,
      pageNo: pageNo.value,
      pageSize: pageSize.value
    };

    BusinessApi.findPage(params)
      .then(res => {
        if (res.code == '00000') {
          busiessList.value = res.data.rows ?? [];
          busiessList.value = busiessList.value.map(item => {
            return { ...item, showMore: false };
          });
          total.value = res.data.totalRows;
        }
      })
      .finally(() => (loading.value = false));
  }
};

// 分页的页数改变
const pageSizeChange = (page, pageSize) => {
  pageNo.value = page;
  getBusiessList();
};

// 条数改变
const showSizeChange = (current, size) => {
  pageSize.value = size;
  getBusiessList();
};

// 点击搜索
const reload = () => {
  pageNo.value = 1;
  getBusiessList();
};

const moreClick = item => {
  item.showMore = !item.shoeMore;
};

// 新增编辑点击
const openAddEdit = record => {
  if (!where.value.businessCategoryId) return message.warn('请选择一个分类');
  if (record) record.showMore = false;
  current.value = record;
  showEdit.value = true;
};

// 删除单个
const remove = record => {
  record.showMore = false;
  Modal.confirm({
    title: '提示',
    content: '确定要删除选中数据吗?',
    icon: createVNode(ExclamationCircleOutlined),
    maskClosable: true,
    wrapClassName: 'delete-modal',
    onOk: async () => {
      const res = await BusinessApi.delete({ businessId: record.businessId });
      message.success(res.message);
      if (buinessSelectAppData.value?.businessId == record.businessId) {
        generatorStore.setBuinessSelectAppData();
      }
      reload();
    }
  });
};

// 默认选中分类
const defaultSelect = data => {
  businessTypeName.value = data.categoryName;
  where.value.businessCategoryId = data.businessCategoryId;
  reload();
};

const selectNull = () => {
  businessTypeName.value = '业务列表';
  where.value.businessCategoryId = '';
  reload();
};

// 左侧树选中
const treeSelect = (selected, metadata) => {
  if (selected) {
    businessTypeName.value = metadata.node.categoryName;
    where.value.businessCategoryId = metadata.node.businessCategoryId;
  } else {
    businessTypeName.value = '业务列表';
    where.value.businessCategoryId = '';
  }
  reload();
};

// 点击设计
const businessDesign = (record, url) => {
  record.showMore = false;
  let obj = {
    businessCategoryId: where.value.businessCategoryId,
    businessId: record.businessId
  };
  generatorStore.setAppBackUrl('/mid/app/list');
  generatorStore.setBuinessSelectAppData(obj);
  router.push({
    path: '/mid/app/detail',
    query: {
      type: url
    }
  });
};

// 基于excel初始化
const initExcel = record => {
  record.showMore = false;
  let obj = {
    businessCategoryId: where.value.businessCategoryId,
    businessId: record.businessId
  };
  generatorStore.setAppBackUrl('/mid/app/list');
  generatorStore.setBuinessSelectAppData(obj);
  router.push({
    path: '/mid/app/excel/init',
    query: {
      type: 'identify'
    }
  });
};

// 导出建表语句
const exportSheetClick = record => {
  record.showMore = false;
  current.value = record;
  showExportSheet.value = true;
};

// 点击预览
const businessPreview = record => {
  record.showMore = false;
  const { href } = router.resolve({
    path: '/preview',
    query: { businessId: record.businessId }
  });
  window.open(href, '_blank');
};
</script>

<style scoped lang="less">
.pagination {
  text-align: right;
}
.empty {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-left: -32px;
  margin-top: -42px;
}
.modular-item {
  cursor: pointer;
  display: flex;
  padding: 12px 16px;
  flex-direction: column;
  align-items: flex-start;
  border-radius: 4px;
  border: 1px solid rgba(197, 207, 209, 0.6);

  &:hover {
    border-color: #3f78df;
  }

  .modular-item-header {
    width: 100%;
    height: 100%;
    overflow: hidden;

    .modular-item-header-top {
      margin-top: 8px;
      width: 100%;
      padding-bottom: 12px;
      display: flex;

      .modular-item-header-top-left {
        width: calc(100% - 20px);
        display: flex;
        align-items: center;

        .modular-item-header-top-left-img {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          margin-right: 8px;
        }
        .modular-item-header-top-left-content {
          width: calc(100% - 48px);
          height: 100%;
          display: flex;
          flex-direction: column;
          gap: 4px;

          .modular-item-header-top-left-content-title {
            height: 20px;
            width: 100%;
            color: #43505e;
            font-size: 16px;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            -o-text-overflow: ellipsis;
          }

          .modular-item-header-top-left-content-code {
            width: 100%;
            color: #898e91;
            font-size: 14px;
            height: 20px;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            -o-text-overflow: ellipsis;
          }
        }
      }
      .modular-item-header-top-right {
        text-align: right;
        width: 20px;

        .more-btn {
          width: 20px;
          height: 20px;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .more-btn:hover {
          background-color: #eee;
          border-radius: 50%;
          color: var(--primary-color);
        }
      }
    }

    .modular-item-center {
      padding-left: 48px;
      width: 100%;
      box-sizing: border-box;
      padding-bottom: 12px;

      .modular-item-center-col {
        width: 100%;
        display: flex;
        align-items: center;

        .modular-item-center-label {
          width: 70px;
          text-align: right;
          color: #898e91;
          font-size: 14px;
          font-style: normal;
          font-weight: 400;
        }
        .modular-item-center-value {
          width: calc(100% - 70px);
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          color: #60666b;
          font-size: 14px;
          font-style: normal;
          font-weight: 400;
        }
      }
    }

    .modular-item-header-bottom {
      padding-top: 12px;
      flex: auto;
      border-top: 1px solid #c5cfd166;
      display: flex;
      align-items: center;
      justify-content: space-between;

      span {
        color: #828b9a;
        font-size: 12px;
        font-style: normal;
        font-weight: 400;
        line-height: 100%; /* 12px */
      }
    }
  }
}
.btn-item {
  display: flex;
  padding: 8px 16px;
  align-items: center;
  gap: 4px;
  cursor: pointer;
  color: #60666b;

  &:hover {
    background-color: var(--primary-1);
  }

  .btn-item-label {
    color: #60666b;
  }
}
</style>

<style lang="less">
.modular-pop {
  .ant-popover-inner {
    border-radius: 4px;
  }
  .ant-popover-inner-content {
    padding: 8px 0;
  }
}
</style>
