<template>
  <div class="view-config">
    <div class="view-header">
      <div class="header-left">
        <a-space :size="8">
          <span class="back-btn" @click="backClick">
            <left-outlined />
            <span>返回</span>
          </span>
        </a-space>
      </div>
      <span class="form-name">{{ props.data?.viewName }}</span>
      <div class="header-right">
        <a-space :size="16">
          <a-button type="primary" ghost class="border-radius" @click="save('back')">
            <template #icon><unordered-list-outlined /></template>
            保存并退出</a-button
          >
          <a-button type="primary" class="border-radius" @click="save()"
            ><template #icon><unordered-list-outlined /></template>保存</a-button
          >
        </a-space>
      </div>
    </div>
    <div class="view-body">
      <a-row class="view-body-header">
        <a-col :span="12" class="header-content body-header-type">
          <div class="body-header-title">列表渲染类型</div>
          <div class="body-bottom-title">
            选择类型：
            <a-radio-group v-model:value="viewConfig.dataRenderType" @change="dataRenderTypeChange">
              <a-radio :value="1">自定义SQL</a-radio>
              <a-radio :value="2"> 基于接口 </a-radio>
              <a-radio :value="3"> 基于动态代码 </a-radio>
              <a-radio :value="4"> 基于表单 </a-radio>
            </a-radio-group>
          </div>
          <!-- 自定义SQL -->
          <div class="body-bottom-title format-list" v-if="viewConfig.dataRenderType == 1">
            <span>查询列表SQL配置：</span>
            <span class="format-btn" @click="formatSql">格式化sql</span>
          </div>
          <div class="body-bottom-content" v-if="viewConfig.dataRenderType == 1">
            <monaco-code-editor style="height: 100%" v-model="viewConfig.sqlTemplate" language="sql"></monaco-code-editor>
          </div>
          <!-- 基于接口 -->
          <div class="body-bottom-title" v-if="viewConfig.dataRenderType == 2">
            接口输入：
            <a-select
              v-model:value="viewConfig.springBeanClass"
              placeholder="请选择"
              style="width: 500px"
              allowClear
              show-search
              :filterOption="filterOption"
            >
              <a-select-option :value="cItem" v-for="(cItem, cIndex) in customRenderApiList" :key="cIndex" :label="cItem">{{
                cItem
              }}</a-select-option>
            </a-select>
          </div>
          <!-- 基于动态代码 -->
          <div class="body-bottom-content" style="height: calc(100% - 75px)" v-if="viewConfig.dataRenderType == 3">
            <monaco-code-editor style="height: 100%" v-model="viewConfig.javaCode" language="java"></monaco-code-editor>
          </div>
        </a-col>
        <a-col :span="12" class="body-header-right">
          <div class="header-content">
            <div class="body-header-title">
              <div>列表展示字段</div>
              <a-space :size="0">
                <plus-outlined class="icons" @click="addListComulm()" />
                <i
                  class="iconfont icon-opt-fabu icons"
                  style="font-size: 20px; font-weight: bold"
                  title="一键导入"
                  @click="exportField"
                ></i>
              </a-space>
            </div>
            <div class="body-content">
              <s-table
                :columns="listColumns"
                rowKey="fieldId"
                size="middle"
                bordered
                :rangeSelection="false"
                :pagination="false"
                :data-source="viewConfig.viewColumnFieldList"
                @rowDragEnd="rowDragEnd"
                :animate-rows="false"
                :key="tabKey"
              >
                <template #bodyCell="{ column, record, index }">
                  <template v-if="['picShowFlag', 'columnShowFlag'].includes(column.dataIndex)">
                    <vxe-checkbox
                      v-model="viewConfig.viewColumnFieldList[index][column.dataIndex]"
                      :checked-value="true"
                      :unchecked-value="false"
                      :disabled="disabled"
                    ></vxe-checkbox>
                  </template>
                  <template v-if="column.dataIndex == 'action'">
                    <a-space :size="16">
                      <icon-font
                        iconClass="icon-opt-bianji"
                        font-size="24px"
                        color="#60666b"
                        title="编辑"
                        @click="addListComulm(record)"
                      ></icon-font>
                      <icon-font
                        iconClass="icon-opt-shanchu"
                        font-size="24px"
                        color="#60666b"
                        title="删除"
                        @click="remove(index)"
                      ></icon-font>
                    </a-space>
                  </template>
                </template>
              </s-table>
            </div>
          </div>
        </a-col>
      </a-row>
      <a-row class="view-body-bottom">
        <a-col :span="12" class="body-header-center">
          <div class="header-content">
            <div class="body-header-title">
              <div>搜索条件配置</div>
              <a-space>
                <plus-outlined class="icons" @click="searchAdd()" />
              </a-space>
            </div>
            <div class="body-content">
              <s-table
                :columns="searchColumns"
                rowKey="fieldId"
                size="middle"
                bordered
                :rangeSelection="false"
                :pagination="false"
                :data-source="viewConfig.viewSearchFieldList"
                @rowDragEnd="rowDragEnd"
                :animate-rows="false"
                :key="searchTabKey"
              >
                <template #bodyCell="{ column, record, index }">
                  <template v-if="column.dataIndex == 'searchShowFlag'">
                    <vxe-checkbox
                      v-model="viewConfig.viewSearchFieldList[index][column.dataIndex]"
                      :checked-value="true"
                      :unchecked-value="false"
                    ></vxe-checkbox>
                  </template>
                  <template v-if="column.dataIndex == 'action'">
                    <a-space :size="16">
                      <icon-font
                        iconClass="icon-opt-bianji"
                        font-size="24px"
                        color="#60666b"
                        title="编辑"
                        @click="searchAdd(record)"
                      ></icon-font>
                      <icon-font
                        iconClass="icon-opt-shanchu"
                        font-size="24px"
                        color="#60666b"
                        title="删除"
                        @click="removeSearch(index)"
                      ></icon-font>
                    </a-space>
                  </template>
                </template>
              </s-table>
            </div>
          </div>
        </a-col>
        <a-col :span="12" class="body-header-left">
          <div class="header-content">
            <div class="body-header-title">
              <div>按钮配置</div>
              <a-space>
                <plus-outlined class="icons" @click="addButton()" />
              </a-space>
            </div>
            <div class="body-content">
              <s-table
                :columns="btnColumns"
                rowKey="buttonCode"
                size="middle"
                bordered
                :rangeSelection="false"
                :pagination="false"
                @rowDragEnd="rowDragEnd"
                :data-source="viewConfig.viewButtonList"
                :animate-rows="false"
                :key="btnTabKey"
              >
                <template #bodyCell="{ column, record, index }">
                  <template v-if="column.dataIndex == 'buttonVisible'">
                    <vxe-checkbox
                      v-model="viewConfig.viewButtonList[index][column.dataIndex]"
                      :checked-value="true"
                      :unchecked-value="false"
                      :disabled="disabled"
                    ></vxe-checkbox>
                  </template>
                  <template v-if="column.dataIndex == 'action'">
                    <a-space :size="16">
                      <icon-font
                        iconClass="icon-opt-bianji"
                        font-size="24px"
                        color="#60666b"
                        title="编辑"
                        @click="addButton(record, index)"
                      ></icon-font>
                      <icon-font
                        iconClass="icon-opt-shanchu"
                        font-size="24px"
                        color="#60666b"
                        title="删除"
                        v-if="!['add', 'edit', 'detail', 'delete', 'export'].includes(record.buttonCode)"
                        @click="removeBtn(index)"
                      ></icon-font>
                    </a-space>
                  </template>
                </template>
              </s-table>
            </div>
          </div>
        </a-col>
      </a-row>
    </div>

    <!-- 列表弹框 -->
    <ListAddEdit v-model:visible="showList" v-if="showList" :data="current" @done="closeList" :viewId="props.data.viewId" />
    <!-- 查询弹框 -->
    <SearchAddEdit v-model:visible="showSearch" v-if="showSearch" :data="current" @done="closeSearch" />
    <!-- 新增编辑按钮配置 -->
    <ButtonAddEdit
      v-model:visible="showBtn"
      v-if="showBtn"
      :data="current"
      @done="closeBtn"
      :list="viewConfig.viewButtonList"
      :currentIndex="currentIndex"
    />
  </div>
</template>

<script setup name="ViewConfig">
import { message } from 'ant-design-vue/es';
import { ref, onMounted, computed } from 'vue';
import { SheetViewApi } from '../api/SheetViewApi';
import ListAddEdit from './list-add-edit.vue';
import SearchAddEdit from './search-add-edit.vue';
import ButtonAddEdit from './button-add-edit.vue';
import { deepClone, getUUID } from '@/utils/common/util';
import { format } from 'sql-formatter';

const props = defineProps({
  data: Object
});

const emits = defineEmits(['back']);

// 列表列配置
const listColumns = ref([
  {
    title: '#',
    dataIndex: '#',
    key: '#',
    rowDrag: true,
    align: 'center',
    width: '50px'
  },
  {
    title: '字段名',
    minWidth: 100,
    autoHeight: true,
    dataIndex: 'fieldName'
  },
  {
    title: '列展示名',
    minWidth: 100,
    autoHeight: true,
    dataIndex: 'showName'
  },
  {
    title: '列展示',
    align: 'center',
    width: '90px',
    dataIndex: 'columnShowFlag'
  },
  {
    title: '是否图片',
    align: 'center',
    width: '90px',
    dataIndex: 'picShowFlag'
  },
  {
    title: '操作',
    align: 'center',
    width: '90px',
    dataIndex: 'action'
  }
]);

// 查询列配置
const searchColumns = ref([
  {
    title: '#',
    dataIndex: '#',
    key: '#',
    rowDrag: true,
    align: 'center',
    width: '50px'
  },
  {
    title: '字段名',
    minWidth: 100,
    autoHeight: true,
    dataIndex: 'fieldName'
  },
  {
    title: '列展示名',
    minWidth: 100,
    autoHeight: true,
    dataIndex: 'showName'
  },
  {
    title: '条件展示',
    align: 'center',
    width: '90px',
    dataIndex: 'searchShowFlag'
  },
  {
    title: '操作',
    align: 'center',
    width: '90px',
    dataIndex: 'action'
  }
]);

// 按钮表格配置
const btnColumns = ref([
  {
    title: '#',
    dataIndex: '#',
    key: '#',
    rowDrag: true,
    align: 'center',
    width: '50px'
  },
  {
    title: '按钮名称',
    minWidth: 100,
    autoHeight: true,
    dataIndex: 'buttonName'
  },
  {
    title: '按钮编码',
    minWidth: 100,
    autoHeight: true,
    dataIndex: 'buttonCode'
  },
  {
    title: '权限编码',
    minWidth: 100,
    autoHeight: true,
    dataIndex: 'buttonPermissionCode'
  },
  {
    title: '是否展示',
    align: 'center',
    width: '90px',
    dataIndex: 'buttonVisible'
  },
  {
    title: '操作',
    align: 'center',
    width: '90px',
    dataIndex: 'action'
  }
]);
// 表格刷新
const tabKey = ref(0);
const btnTabKey = ref(0);
const searchTabKey = ref(0);
// 当前行数据
const current = ref(null);
// 当前行索引
const currentIndex = ref(0);
// 是否显示
const showList = ref(false);
const showSearch = ref(false);
const showBtn = ref(false);
// 默认按钮列表
const defaultButtonList = ref([
  {
    buttonCode: 'add',
    buttonIcon: '',
    buttonName: '新增',
    buttonPermissionCode: '',
    buttonVisible: true,
    customRouterUrl: ''
  },
  {
    buttonCode: 'edit',
    buttonIcon: '',
    buttonName: '编辑',
    buttonPermissionCode: '',
    buttonVisible: true,
    customRouterUrl: ''
  },
  {
    buttonCode: 'detail',
    buttonIcon: '',
    buttonName: '详情',
    buttonPermissionCode: '',
    buttonVisible: true,
    customRouterUrl: ''
  },
  {
    buttonCode: 'delete',
    buttonIcon: '',
    buttonName: '删除',
    buttonPermissionCode: '',
    buttonVisible: true,
    customRouterUrl: ''
  },
  {
    buttonCode: 'export',
    buttonIcon: '',
    buttonName: '导出',
    buttonPermissionCode: '',
    buttonVisible: true,
    customRouterUrl: ''
  }
]);

// 试图配置
const viewConfig = ref({
  sqlTemplate: '',
  javaCode: '',
  dataRenderType: 1,
  springBeanClass: null,
  viewButtonList: deepClone(defaultButtonList.value),
  viewColumnFieldList: [],
  viewSearchFieldList: []
});

// 自定义下拉api列表
const customRenderApiList = ref([]);

const businessId = ref('');

const disabled = computed(() => {
  return viewConfig.value?.dataRenderType == 4 ? true : false;
});

onMounted(() => {
  getCustomRenderApiList();
  getViewConfigDetail();
});

// 获取详情
const getViewConfigDetail = async () => {
  const res = await SheetViewApi.getViewConfig({ viewId: props.data.viewId });
  businessId.value = res.businessId;
  if (res.viewConfig) {
    if (!res.viewConfig.viewButtonList || res.viewConfig.viewButtonList?.length == 0) {
      res.viewConfig.viewButtonList = deepClone(defaultButtonList.value);
    }
    viewConfig.value = res.viewConfig;
  }
};

// 获取自定义接口下拉列表
const getCustomRenderApiList = async () => {
  customRenderApiList.value = await SheetViewApi.getCustomRenderApiList();
};

// 返回
const backClick = () => {
  emits('back');
};

// 保存
const save = flag => {
  SheetViewApi.saveViewConfig({ viewConfig: viewConfig.value, viewId: props.data.viewId }).then(res => {
    message.success(res.message);
    if (flag) backClick();
    getViewConfigDetail();
  });
};

// 拖拽
const rowDragEnd = dragData => {};

// 新增编辑列
const addListComulm = record => {
  if (disabled.value) return;
  current.value = record;
  showList.value = true;
};

// 关闭列配置
const closeList = value => {
  if (current.value) {
    viewConfig.value.viewColumnFieldList.splice(
      viewConfig.value.viewColumnFieldList.findIndex(item => item.fieldId === value.fieldId),
      1,
      value
    );
  } else {
    viewConfig.value.viewColumnFieldList.push(value);
  }
  ++tabKey.value;
};

// 新增按钮配置
const addButton = (record, index) => {
  if (disabled.value) return;
  current.value = record;
  currentIndex.value = index;
  showBtn.value = true;
};

// 关闭按钮配置弹框
const closeBtn = data => {
  if (current.value) {
    viewConfig.value.viewButtonList.splice(currentIndex.value, 1, data);
  } else {
    viewConfig.value.viewButtonList.push(data);
  }
  ++btnTabKey.value;
};

// 删除按钮配置
const removeBtn = index => {
  if (disabled.value) return;
  ++btnTabKey.value;
  viewConfig.value.viewButtonList.splice(index, 1);
};

// 一键导入
const exportField = async () => {
  if (disabled.value) return;
  const res = await SheetViewApi.getImportFieldList({ viewId: props.data.viewId });
  if (!viewConfig.value.sqlTemplate) {
    viewConfig.value.sqlTemplate = res.defaultSql;
  }
  if (viewConfig.value.viewColumnFieldList?.length > 0) return message.warning('列表展示字段已存在数据，无法导入！');
  res?.metaFieldList.forEach(item => {
    item.fieldId = getUUID();
  });
  viewConfig.value.viewColumnFieldList = res.metaFieldList;
};

// 删除列
const remove = index => {
  if (disabled.value) return;
  ++tabKey.value;
  viewConfig.value.viewColumnFieldList.splice(index, 1);
};

// 新增编辑搜索配置
const searchAdd = record => {
  current.value = record;
  showSearch.value = true;
};

// 删除列
const removeSearch = index => {
  ++searchTabKey.value;
  viewConfig.value.viewSearchFieldList.splice(index, 1);
};

// 关闭搜索配置
const closeSearch = value => {
  if (current.value) {
    viewConfig.value.viewSearchFieldList.splice(
      viewConfig.value.viewSearchFieldList.findIndex(item => item.fieldId === value.fieldId),
      1,
      value
    );
  } else {
    viewConfig.value.viewSearchFieldList.push(value);
  }
  ++searchTabKey.value;
};

// 格式化sql
const formatSql = () => {
  try {
    viewConfig.value.sqlTemplate = format(viewConfig.value.sqlTemplate);
  } catch (error) {
    message.warning('存在不正确的sql，无法格式化!');
  }
};

// 列表选择类型改变
const dataRenderTypeChange = ({ target }) => {
  viewConfig.value.springBeanClass = null;
  viewConfig.value.sqlTemplate = '';
  viewConfig.value.javaCode = '';
  if (target.value == 4) {
    getFormBasedFieldList();
  }
};

const getFormBasedFieldList = () => {
  SheetViewApi.getFormBasedFieldList({ businessId: businessId.value }).then(res => {
    viewConfig.value.viewColumnFieldList = res.data.viewColumnFieldList;
    viewConfig.value.viewSearchFieldList = res.data.viewSearchFieldList;
  });
};

// 接口输入过滤
const filterOption = (input, option) => {
  if ((option?.label ?? '').includes(input)) {
    return option;
  }
  return false;
};
</script>

<style scoped lang="less">
.view-config {
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.view-header {
  width: 100%;
  height: 48px;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  border-bottom: 1px solid #eee;
  box-shadow: 0 0 4px #ccc;
  margin-bottom: 0%;

  .form-name {
    color: #505050;
    font-size: 20px;
  }

  .back-btn {
    cursor: pointer;
    font-size: 16px;
    color: #60666b;

    .anticon {
      font-size: 14px;
      margin-right: 4px;
      color: #60666b;
    }
  }
}

.view-body {
  width: 100%;
  height: calc(100% - 48px);
  background-color: #fff;
  display: flex;
  flex-direction: column;
}

.view-body-header,
.view-body-bottom {
  height: 50%;
  width: 100%;
}

.view-body-header {
  border-bottom: 1.5px solid #c5cfd166;
}

.view-body-bottom {
  width: 100%;
  height: 50%;
  background: #fff;
  border-radius: 5px;
}

.body-bottom-title {
  margin-bottom: 10px;
  color: #60666b;
  font-size: 16px;
}

.format-list {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .format-btn {
    cursor: pointer;
    display: flex;
    padding: 4px 8px;
    justify-content: center;
    align-items: center;
    gap: 6px;
    color: #fff;
    font-size: 14px;
    border-radius: 4px;
    background: #3f78df;
  }
}

.body-bottom-content {
  height: calc(100% - 115px);
  border: 1px solid #c5cfd166;
  border-radius: 4px;
}

.header-content {
  padding: 24px 32px;
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  background: #fff;
  border-radius: 5px;
}

.body-header-type,
.body-header-center {
  height: 100%;
  border-right: 1.5px solid #c5cfd166;
}

.body-header-right,
.body-header-left {
  height: 100%;
}

.body-header-title {
  height: 20px;
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  color: #43505e;
  font-size: 16px;
  font-weight: 700;
}

.icons {
  color: #898e91;
  font-size: 16px;
  cursor: pointer;
  padding: 5px;
  border-radius: 2px;

  &:hover {
    background: #e9f3f8;
  }
}

.body-content {
  height: calc(100% - 40px);
  width: 100%;
  overflow: hidden;
}

:deep(.surely-table-wrapper) {
  height: 100%;
}

:deep(.surely-table) {
  height: 100%;
}

:deep(.surely-table-body) {
  height: calc(100% - 55px) !important;
  overflow-y: auto;
}
:deep(.surely-table-bordered) {
  border-right: 1px solid var(--surely-table-border-color) !important;
}
</style>
