<template>
  <div class="guns-layout">
    <guns-split-layout v-show="!showField" width="0px" :resizable="false" :allowCollapse="false">
      <div class="guns-layout-sidebar width-100 p-t-12" v-if="false">
        <div class="sidebar-content">
          <BuinessTree @treeSelect="treeSelect" />
        </div>
      </div>
      <template #content>
        <div class="guns-layout-content" v-show="!showField">
          <div class="guns-layout">
            <div class="guns-layout-content-application">
              <div class="content-mian">
                <div class="content-mian-body">
                  <div class="table-content">
                    <common-table
                      :columns="columns"
                      :where="where"
                      size="middle"
                      :isInit="false"
                      rowId="metaModelId"
                      ref="tableRef"
                      url="/metaModel/page"
                      :showToolTotal="false"
                    >
                      <template #toolLeft>
                        <a-input
                          v-model:value="where.searchText"
                          allowClear
                          placeholder="中文名称、编码"
                          @pressEnter="reload"
                          :bordered="false"
                          style="width: 300px"
                          class="search-input"
                        >
                          <template #prefix>
                            <icon-font iconClass="icon-opt-search"></icon-font>
                          </template>
                        </a-input>
                      </template>
                      <template #toolRight>
                        <a @click="openAddEdit()">新建</a>
                        <a @click="sqlImport">导入SQL</a>
                        <a-dropdown>
                          <template #overlay>
                            <a-menu @click="moreClick">
                              <a-menu-item key="1">
                                <icon-font iconClass="icon-opt-zidingyilie" color="#60666b"></icon-font>
                                <span>自定义列</span>
                              </a-menu-item>
                              <div>
                                <a-menu-item key="2">
                                  <icon-font iconClass="icon-opt-shanchu" color="#60666b"></icon-font>
                                  <span>批量删除</span>
                                </a-menu-item>
                              </div>
                            </a-menu>
                          </template>
                          <a>更多</a>
                        </a-dropdown>
                      </template>
                      <template #bodyCell="{ column, record }">
                        <template v-if="column.dataIndex == 'metaModelName'">
                          <a @click="sheetField(record)">{{ record.metaModelName }}</a>
                        </template>
                        <template v-if="column.dataIndex == 'metaModelType'">
                          <a-tag v-if="record.metaModelType == 1" class="blue-tag">新建表</a-tag>
                          <a-tag v-if="record.metaModelType == 2" class="orange-tag">外部表</a-tag>
                        </template>
                        <template v-if="column.dataIndex == 'tableCreateFlag'">
                          <a-tag v-if="record.tableCreateFlag" class="blue-tag">是</a-tag>
                          <a-tag v-else class="grey-tag">否</a-tag>
                        </template>
                        <template v-if="column.dataIndex == 'mainFlag'">
                          <a-tag v-if="record.mainFlag == 'Y'" class="blue-tag">是</a-tag>
                          <a-tag v-else class="grey-tag">否</a-tag>
                        </template>
                        <!-- 操作 -->
                        <template v-if="column.key == 'action'">
                          <a-space :size="16">
                            <icon-font
                              iconClass="icon-opt-bianji"
                              font-size="24px"
                              title="编辑"
                              color="#60666b"
                              @click="openAddEdit(record)"
                            ></icon-font>
                            <icon-font
                              iconClass="icon-opt-zidingyilie"
                              font-size="24px"
                              title="字段"
                              color="#60666b"
                              v-if="record.metaModelType == 1"
                              @click="sheetField(record)"
                            ></icon-font>
                            <icon-font
                              iconClass="icon-opt-shangchuandaoshujuku"
                              font-size="24px"
                              color="#60666b"
                              title="导出sql"
                              @click="exportSql(record)"
                            ></icon-font>
                            <icon-font
                              iconClass="icon-opt-shanchu"
                              font-size="24px"
                              color="#60666b"
                              title="删除"
                              @click="remove(record)"
                            ></icon-font>
                          </a-space>
                        </template>
                      </template>
                    </common-table>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>
    </guns-split-layout>

    <!-- 表字段 -->
    <SheetField v-if="showField" :data="current" @back="changeShowField" :where="where" :type="props.type" />

    <!-- 自定义列 -->
    <Custom
      v-model:visible="isShowCustom"
      v-if="isShowCustom"
      :data="columns"
      @done="val => (columns = val)"
      :fieldBusinessCode="fieldBusinessCode"
    />

    <!-- 新增编辑弹框 -->
    <SheetAddEdit
      v-model:visible="showEdit"
      v-if="showEdit"
      :data="current"
      @done="refresh"
      :businessCategoryId="where.businessCategoryId"
      :businessId="where.businessId"
    />

    <!-- 从SQL导入 -->
    <SheetSqlImport
      v-model:visible="showSql"
      v-if="showSql"
      @done="refresh"
      :businessCategoryId="where.businessCategoryId"
      :businessId="where.businessId"
    />

    <!-- 导出sql -->
    <SheetExportSql v-model:visible="showExportSql" v-if="showExportSql" :data="current" />
  </div>
</template>

<script setup name="BuinessSheet">
import { useGeneratorStore } from '@/store/modules/generator';
import { onMounted, computed, ref, createVNode } from 'vue';
import { useRouter } from 'vue-router';
import { ModelApi } from './api/ModelApi';
import { message, Modal } from 'ant-design-vue/es';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { CustomApi } from '@/components/common/Custom/api/CustomApi';
import BuinessTree from '../list/components/list-type/buiness-tree.vue';
import SheetAddEdit from './components/sheet/sheet-add-edit.vue';
import SheetField from './components/sheet-field/index.vue';
import SheetSqlImport from './components/sheet/sheet-sql-import.vue';
import SheetExportSql from './components/sheet/sheet-export-sql.vue';

defineOptions({
  name: 'BuinessSheet'
});

const props = defineProps({
  type: {
    type: String,
    default: 'app'
  },
  getBusinessStatCount: Function
});

const router = useRouter();

const generatorStore = useGeneratorStore();

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

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

// ref
const tableRef = ref();

// 表格配置
const columns = ref([
  {
    key: 'index',
    title: '序号',
    width: 60,
    align: 'center',
    isShow: true,
    hideInSetting: true
  },
  {
    dataIndex: 'metaModelName',
    title: '中文名称',
    ellipsis: true,
    width: 150,
    isShow: true
  },
  {
    dataIndex: 'metaModelCode',
    title: '表名',
    width: 100,
    isShow: true
  },
  {
    dataIndex: 'mainFlag',
    title: '是否是主表',
    ellipsis: true,
    width: 100,
    isShow: true
  },
  {
    dataIndex: 'metaModelType',
    title: '外部类型',
    ellipsis: true,
    width: 100,
    isShow: true
  },
  {
    dataIndex: 'tableCreateFlag',
    title: '已创建真实表',
    ellipsis: true,
    width: 150,
    isShow: true
  },
  {
    dataIndex: 'systemCodeShow',
    title: '系统编码',
    ellipsis: true,
    width: 100,
    isShow: true
  },
  {
    dataIndex: 'fldSort',
    title: '排序',
    ellipsis: true,
    width: 100,
    isShow: true
  },
  {
    dataIndex: 'createTime',
    title: '创建时间',
    ellipsis: true,
    width: 150,
    isShow: true
  },
  {
    key: 'action',
    title: '操作',
    width: 100,
    isShow: true
  }
]);
// 当前行数据
const current = ref(null);
// 是否显示新增编辑弹框
const showEdit = ref(false);
// 是否显示自定义列
const isShowCustom = ref(false);
// 业务标识的编码
const fieldBusinessCode = ref('BASE_SHEET_BUSINESS');

// 是否显示模型字段
const showField = ref(false);

// 是否显示 SQL导入弹框
const showSql = ref(false);

// 导出sql弹框
const showExportSql = ref(false);

onMounted(() => {
  if (!buinessSelectAppData.value?.businessId) {
    return goHome();
  }
  getColumnData();
});

// 获取表格配置
const getColumnData = () => {
  CustomApi.getUserConfig({ fieldBusinessCode: fieldBusinessCode.value }).then(res => {
    if (res.tableWidthJson) {
      columns.value = JSON.parse(res.tableWidthJson);
    }
    treeSelect(buinessSelectAppData.value);
  });
};

// 返回应用列表页
const goHome = () => {
  router.push(generatorStore.appBackUrl);
};

// 树选中
const treeSelect = node => {
  where.value.businessId = node.businessId;
  where.value.businessCategoryId = node.businessCategoryId;
  reload();
};

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

const refresh = () => {
  reload();
  if (props.getBusinessStatCount) props.getBusinessStatCount();
};

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

// 删除单个
const remove = record => {
  Modal.confirm({
    title: '提示',
    content: '确定要删除选中数据吗?',
    icon: createVNode(ExclamationCircleOutlined),
    maskClosable: true,
    onOk: async () => {
      const res = await ModelApi.delete({ metaModelId: record.metaModelId });
      message.success(res.message);
      refresh();
    }
  });
};

// 批量删除
const batchDelete = () => {
  if (tableRef.value.selectedRowList && tableRef.value.selectedRowList.length == 0) {
    return message.warning('请选择需要删除的数据');
  }
  Modal.confirm({
    title: '提示',
    content: '确定要删除选中的数据吗?',
    icon: createVNode(ExclamationCircleOutlined),
    maskClosable: true,
    onOk: async () => {
      const res = await ModelApi.batchDelete({ batchDeleteIdList: tableRef.value.selectedRowList });
      message.success(res.message);
      reload();
    }
  });
};

// 更多点击
const moreClick = ({ key }) => {
  if (key == '1') {
    isShowCustom.value = true;
  } else if (key == '2') {
    batchDelete();
  }
};

// 显示字段
const sheetField = record => {
  if (record.metaModelType == 1) {
    current.value = record;
    showField.value = true;
  } else {
    message.warning('外部表不能编辑');
  }
};

// SQL导入
const sqlImport = () => {
  if (!where.value.businessId) return message.warn('请选择一个业务');
  showSql.value = true;
};

// 导出sql
const exportSql = record => {
  current.value = record;
  showExportSql.value = true;
};

const changeShowField = () => {
  showField.value = false;
  reload();
};
</script>

<style scoped lang="less">
.table-tool-top-right a {
  font-size: 16px;
}
.ant-tag {
  padding: 4px 8px;
  border-radius: 4px;
  background: rgba(207, 221, 247, 0.35);
  color: #1983ff;
  font-size: 14px;
  font-style: normal;
  font-weight: 400;
  line-height: normal;
}
.grey-tag {
  background: #f3f3f5;
  color: #60666b;
}
.orange-tag {
  background: #fff7e9;
  color: #f67800;
}
</style>
