<template>
  <div class="guns-layout">
    <div class="guns-layout-content" :style="{ padding: props.showLeft ? '12px' : '0px' }">
      <a-spin :spinning="loading" :delay="100">
        <div class="guns-layout">
          <div class="guns-layout-content-header p-t-12">
            <a-space :size="16" v-if="!props.showLeft">
              <span></span>
            </a-space>
            <a-space :size="16" v-if="props.showLeft">
              <a-space class="back" :size="4" v-if="props.businessId" @click="back">
                <left-outlined />
                返回
              </a-space>
              <a-divider type="vertical" class="divider" v-if="props.businessId" />
              <span>{{ tableConfig?.businessName }}</span>
            </a-space>
            <a-space :size="16">
              <a-button
                type="primary"
                class="border-radius"
                @click="openAddEdit()"
                v-if="showButton('add')"
                ><plus-outlined />
                <span v-if="baseButtonObj?.add?.buttonName">{{ baseButtonObj?.add?.buttonName }}</span>
                <span v-else>新建</span>
              </a-button>
              <a-dropdown>
                <template #overlay>
                  <a-menu>
                    <div v-for="cItem in moreCustomButtonList">
                      <a-menu-item :key="cItem.buttonCode" v-if="showCustomButton(cItem)" @click="cutsomButtonClilck(cItem)">
                        <div class="menu-item-display">
                          <icon-font
                            class="paddingRight5"
                            font-size="16px"
                            :iconClass="cItem.buttonIcon"
                            color="#60666b"
                            v-if="cItem.buttonIcon"
                          ></icon-font>
                          <icon-font
                            iconClass="icon-opt-shanchu"
                            color="#60666b"
                            class="paddingRight5"
                            v-if="cItem.buttonCode == 'delete'"
                          ></icon-font>
                          <icon-font
                            iconClass="icon-opt-daochu"
                            color="#60666b"
                            class="paddingRight5"
                            v-if="cItem.buttonCode == 'export'"
                          ></icon-font>
                          <span style="padding-left: 2px">{{ cItem.buttonName }}</span>
                        </div>
                      </a-menu-item>
                    </div>
                  </a-menu>
                </template>
                <a-button class="border-radius">
                  更多
                  <small-dash-outlined />
                </a-button>
              </a-dropdown>
            </a-space>
          </div>
          <div class="guns-layout-content-application p-t-12">
            <div class="content-mian">
              <div class="content-mian-header"></div>
              <div class="content-mian-body">
                <div class="table-content">
                  <common-table
                    :columns="columns"
                    :where="where"
                    size="middle"
                    methods="post"
                    :isInit="false"
                    showTableTool
                    :showToolTotal="viewSearchFieldList?.length > 0 ? false : true"
                    rowId="id"
                    ref="tableRef"
                    :url="apiUrl"
                    v-model:selection="selection"
                  >
                    <template #toolLeft>
                      <template v-for="(searchItem, searchIndex) in viewSearchFieldList" :key="searchIndex + 'search'">
                        <!-- input -->
                        <template v-if="searchItem.conditionInputType == 'text' && searchItem.searchShowFlag">
                          <a-input
                            v-model:value="where.businessSearchParams[searchItem.fieldName]"
                            :placeholder="searchItem.showName + '搜索'"
                            @pressEnter="reload"
                            allowClear
                            :bordered="false"
                            class="search-input"
                          >
                            <template #suffix>
                              <icon-font iconClass="icon-opt-search" @click="reload"></icon-font>
                            </template>
                          </a-input>
                        </template>
                        <!-- 字典 -->
                        <template v-if="searchItem.conditionInputType == 'dict' && searchItem.searchShowFlag">
                          <guns-dict-popover
                            :name="searchItem.showName"
                            :dictTypeId="searchItem.dictTypeId"
                            @change="reload"
                            style="width: 150px"
                            :fieldNames="{
                              children: 'children',
                              title: 'dictName',
                              key: searchItem.dictDataType == 'code' ? 'dictCode' : 'dictId'
                            }"
                            v-model:value="where.businessSearchParams[searchItem.fieldName]"
                          ></guns-dict-popover>
                        </template>
                      </template>
                      <a-divider type="vertical" class="divider" />
                      <a @click="changeSuperSearch" v-if="viewSearchFieldListBottom?.length">{{ superSearch ? '收起' : '高级筛选' }} </a>
                    </template>
                    <!-- 高级筛选 -->
                    <template #toolBottom>
                      <div class="super-search" style="margin-top: 8px" v-if="superSearch">
                        <a-form :model="where" :labelCol="labelCol" :wrapper-col="wrapperCol">
                          <a-row :gutter="16">
                            <a-col
                              v-bind="spanCol"
                              v-for="(superSearchItem, superSearchIndex) in viewSearchFieldListBottom"
                              :key="superSearchIndex + 'search'"
                            >
                              <a-form-item :label="superSearchItem.showName">
                                <!-- input -->
                                <template v-if="superSearchItem.conditionInputType == 'text' && superSearchItem.searchShowFlag">
                                  <a-input
                                    v-model:value="where.businessSearchParams[superSearchItem.fieldName]"
                                    :placeholder="superSearchItem.showName + '搜索'"
                                    @pressEnter="reload"
                                    allowClear
                                    class="search-input"
                                  >
                                    <template #suffix>
                                      <icon-font iconClass="icon-opt-search" @click="reload"></icon-font>
                                    </template>
                                  </a-input>
                                </template>
                                <!-- 字典 -->
                                <template v-if="superSearchItem.conditionInputType == 'dict' && superSearchItem.searchShowFlag">
                                  <guns-dict-popover
                                    :name="superSearchItem.showName"
                                    :dictTypeId="superSearchItem.dictTypeId"
                                    @change="reload"
                                    bordered
                                    style="background-color: #fff; width: 100%; height: 36px"
                                    :fieldNames="{
                                      children: 'children',
                                      title: 'dictName',
                                      key: superSearchItem.dictDataType == 'code' ? 'dictCode' : 'dictId'
                                    }"
                                    v-model:value="where.businessSearchParams[superSearchItem.fieldName]"
                                  ></guns-dict-popover>
                                </template>
                              </a-form-item>
                            </a-col>
                            <a-col v-bind="spanCol">
                              <a-form-item label=" " class="not-label">
                                <a-space :size="16">
                                  <a-button class="border-radius" @click="reload" type="primary">查询</a-button>
                                  <a-button class="border-radius" @click="clear">重置</a-button>
                                </a-space>
                              </a-form-item>
                            </a-col>
                          </a-row>
                        </a-form>
                      </div>
                    </template>
                    <template #bodyCell="{ column, record }">
                      <template v-if="column?.picShowFlag">
                        <span v-if="!record[column.dataIndex]"></span>
                        <span v-else>
                          <a-space>
                            <a-image width="40px" :src="item" v-for="(item, index) in getPicList(record[column.dataIndex])" :key="index" />
                          </a-space>
                        </span>
                      </template>
                      <!-- 详情 -->
                      <template v-else-if="column.dataIndex == detailColumnField">
                        <a v-if="showButton('detail')" @click="detailClick(record)">{{ record[column.dataIndex] }}</a>
                        <span v-else>{{ record[column.dataIndex] }}</span>
                      </template>
                      <!-- 操作 -->
                      <template v-else-if="column.key == 'action'">
                        <a-space :size="16">
                          <template v-for="aItem in actionCustomButtonList" :key="aItem">
                            <icon-font
                              iconClass="icon-opt-bianji"
                              font-size="24px"
                              color="#60666b"
                              v-if="aItem.buttonCode == 'edit' && showCustomButton(aItem)"
                              :title="aItem.buttonName || '编辑'"
                              @click="openAddEdit(record)"
                            ></icon-font>
                            <icon-font
                              iconClass="icon-opt-xiangqing"
                              font-size="24px"
                              color="#60666b"
                              v-else-if="aItem.buttonCode == 'detail' && showCustomButton(aItem)"
                              :title="aItem.buttonName || '详情'"
                              @click="detailClick(record)"
                            ></icon-font>
                            <icon-font
                              iconClass="icon-opt-shanchu"
                              font-size="24px"
                              color="#60666b"
                              v-else-if="aItem.buttonCode == 'delete' && showCustomButton(aItem)"
                              :title="aItem.buttonName || '删除'"
                              @click="remove(record)"
                            ></icon-font>
                            <icon-font
                              font-size="24px"
                              :iconClass="aItem.buttonIcon"
                              :title="aItem.buttonName"
                              @click="cutsomButtonClilck(aItem, record)"
                              color="#60666b"
                              v-else-if="aItem.buttonIcon && showCustomButton(aItem)"
                            ></icon-font>
                            <a v-else-if="aItem.buttonName && showCustomButton(aItem)" @click="cutsomButtonClilck(aItem, record)">{{
                              aItem.buttonName
                            }}</a>
                          </template>
                        </a-space>
                      </template>
                    </template>
                  </common-table>
                </div>
              </div>
            </div>
          </div>
        </div>
      </a-spin>
    </div>

    <!-- 新增编辑弹框 -->
    <PreviewAddEdit
      v-model:visible="showEdit"
      v-if="showEdit"
      :data="current"
      @done="reload"
      :businessId="where.businessId"
      :tableConfig="tableConfig"
    />
    <!-- 详情抽屉 -->
    <PreviewDetail
      v-model:visible="showDetail"
      v-if="showDetail"
      :data="current"
      @done="reload"
      :showCustomButton="showCustomButton"
      :actionCustomButtonList="actionCustomButtonList"
      :businessId="where.businessId"
      :tableConfig="tableConfig"
    />
  </div>
</template>

<script setup name="MidCodePreview">
import { ref, onMounted, createVNode, computed, watch } from 'vue';
import { PreviewApi } from './api/PreviewApi';
import { useRoute, useRouter } from 'vue-router';
import { useUserStore } from '@/store/modules/user';
import { message, Modal } from 'ant-design-vue/es';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import PreviewAddEdit from './components/preview-add-edit.vue';
import PreviewDetail from './components/preview-detail.vue';
import { isMobile } from '@/utils/common/util';

defineOptions({
  name: 'MidCodePreview'
});

const props = defineProps({
  businessId: String,
  backUrl: String,
  type: {
    type: String,
    default: 'preview'
  },
  showLeft: {
    type: Boolean,
    default: true
  }
});

const router = useRouter();

const route = useRoute();

// store
const userStore = useUserStore();

// 已有按钮权限
const authorities = computed(() => {
  return userStore.authorities ?? [];
});

// 表格的业务配置数据
const tableConfig = ref({});

// 搜索条件列表
const viewSearchFieldList = ref([]);
// 底部搜索条件
const viewSearchFieldListBottom = ref([]);

// 加载状态
const loading = ref(false);

// 查询条件
const where = ref({
  businessId: '',
  viewId: '',
  businessSearchParams: {}
});

// 表格列配置
const columns = ref([
  {
    key: 'index',
    title: '序号',
    width: 80,
    align: 'center',
    isShow: true,
    hideInSetting: true
  },
  {
    key: 'action',
    title: '操作',
    width: 80,
    ellipsis: true,
    fixed: 'right',
    isShow: true
  }
]);
// 旧表格列配置
const oldColumns = ref([
  {
    key: 'index',
    title: '序号',
    width: 80,
    align: 'center',
    isShow: true,
    hideInSetting: true
  },
  {
    key: 'action',
    title: '操作',
    width: 80,
    ellipsis: true,
    fixed: 'right',
    isShow: true
  }
]);

// ref
const tableRef = ref();

// 是否显示新增编辑弹框
const showEdit = ref(false);
// 是否显示详情抽屉
const showDetail = ref(false);

// 当前行数据
const current = ref(null);

// 基础按钮列表
const baseButtonObj = ref({});
// 更多自定义按钮列表
const moreCustomButtonList = ref([]);
// 操作栏自定义按钮列表
const actionCustomButtonList = ref([]);
// 详情列展示字段
const detailColumnField = ref('');

const selection = ref([]);

// 是否显示高级查询
const superSearch = ref(false);

const labelCol = computed(() => {
  return { xxl: 7, xl: 7, lg: 5, md: 7, sm: 4 };
});

const wrapperCol = computed(() => {
  return { xxl: 17, xl: 17, lg: 19, md: 17, sm: 20 };
});

const spanCol = computed(() => {
  if (isMobile()) {
    return { xxl: 6, xl: 8, lg: 12, md: 24, sm: 24, xs: 24 };
  }
  return { xxl: 6, xl: 8, lg: 24, md: 24, sm: 24, xs: 24 };
});

// 接口地址
const apiUrl = computed(() => {
  return '/businessRender/getListData';
});

onMounted(() => {
  if (route.query?.businessId || props.businessId) {
    init();
  }
});

const init = () => {
  moreCustomButtonList.value = [];
  moreCustomButtonList.value = [];
  where.value.businessId = route.query?.businessId || props.businessId;
  where.value.viewId = route.query?.viewId;
  getTableConfig();
};

watch(
  () => route.query?.businessId,
  val => {
    if (val) {
      init();
    }
  },
  { deep: true }
);

// 获取表格业务配置
const getTableConfig = () => {
  loading.value = true;
  columns.value = [...oldColumns.value];
  detailColumnField.value = '';
  PreviewApi.getConfig({ businessId: where.value.businessId, viewId: where.value.viewId })
    .then(res => {
      if (res.data) {
        tableConfig.value = res.data;
        if (res.data?.viewConfig?.viewButtonList) {
          let baseList = ['add', 'detail'];
          let baseButtonList = [];
          // 更多按钮列表
          let moreList = [];
          // 操作栏按钮列表
          let actionList = [];
          baseButtonList = res.data.viewConfig?.viewButtonList.filter(item => baseList.includes(item.buttonCode));
          // 基础按钮列表
          baseButtonList.forEach(item => {
            baseButtonObj.value[item.buttonCode] = item;
          });
          res.data.viewConfig?.viewButtonList.forEach(item => {
            if (['add'].includes(item.buttonCode)) return;
            if (item.buttonCode == 'edit') {
              actionList.push(item);
            } else if (item.buttonCode == 'export') {
              moreList.push(item);
            } else if (item.buttonCode == 'delete') {
              moreList.push(item);
              actionList.push(item);
            } else if (item.buttonCode == 'detail') {
              actionList.push(item);
            } else if (item.buttonPlace == 1) {
              moreList.push(item);
            } else if (item.buttonPlace == 2) {
              actionList.push(item);
            }
          });
          // 更多自定义按钮列表
          moreCustomButtonList.value = moreList;
          // 操作栏自定义按钮列表
          actionCustomButtonList.value = actionList;
        }
        let viewColumnFieldList = res.data?.viewConfig?.viewColumnFieldList;
        // 获取表格配置展示
        if (viewColumnFieldList) {
          let showColumn = viewColumnFieldList.filter(item => item.columnShowFlag);
          const cloumnData = showColumn.map(item => {
            return {
              title: item.showName,
              dataIndex: item.fieldName,
              isShow: true,
              width: 150,
              ellipsis: true,
              picShowFlag: item?.picShowFlag
            };
          });
          columns.value = columns.value.slice(0, 1).concat(cloumnData, columns.value.slice(1));
          // 获取详情列展示字段
          if (columns.value[1]?.key != 'action') {
            detailColumnField.value = columns.value[1].dataIndex;
          }
        }
        // 查询列表
        if (res.data?.viewConfig?.viewSearchFieldList?.length > 0) {
          let searchList = res.data.viewConfig.viewSearchFieldList;
          viewSearchFieldList.value = [searchList.shift()];
          viewSearchFieldListBottom.value = searchList;
        }

        reload();
        loading.value = false;
      }
    })
    .catch(e => (loading.value = false));
};

// 是否显示按钮
const showButton = type => {
  if (JSON.stringify(baseButtonObj.value) == '{}') return false;
  if (baseButtonObj.value[type]?.buttonVisible && !baseButtonObj.value[type].buttonPermissionCode) {
    return true;
  } else if (
    baseButtonObj.value[type]?.buttonVisible &&
    baseButtonObj.value[type].buttonPermissionCode &&
    authorities.value.find(item => item == baseButtonObj.value[type].buttonPermissionCode)
  ) {
    return true;
  }
  return false;
};

// 是否显示自定义按钮
const showCustomButton = item => {
  if (item.buttonVisible && !item.buttonPermissionCode) {
    return true;
  } else if (item.buttonVisible && item.buttonPermissionCode && authorities.value.find(aItem => aItem == item.buttonPermissionCode)) {
    return true;
  }
  return false;
};

// 点击查询
const reload = () => {
  selection.value = [];
  tableRef.value.reload();
};

const clear = () => {
  where.value.businessSearchParams = {};
  reload();
};

// 点击新增编辑弹框
const openAddEdit = record => {
  if (!record && props.type == 'fill') {
    router.push({
      path: '/mid/fill/submit',
      query: {
        businessId: props.businessId,
        type: 'add',
        backUrl: encodeURIComponent('/mid/fill/detail')
      }
    });
  } else {
    current.value = record;
    showEdit.value = true;
  }
};

// 删除
const remove = record => {
  selection.value = [record];
  batchDelete();
};

// 批量删除
const batchDelete = () => {
  if (selection.value.length == 0) {
    return message.warning('请选择需要删除的数据');
  }

  Modal.confirm({
    title: '提示',
    content: '确定要删除选中的数据吗?',
    icon: createVNode(ExclamationCircleOutlined),
    maskClosable: true,
    wrapClassName: 'delete-modal',
    onOk: async () => {
      let params = {
        batchDeleteIdList: selection.value.map(item => item.id),
        businessId: where.value.businessId
      };
      let res;
        res = await PreviewApi.batchDelete(params);
      message.success(res?.message);
      reload();
    }
  });
};

// 导出
const exportClick = async () => {
  if (where.value.businessId) {
      await PreviewApi.exportData({ businessId: where.value.businessId, viewId: where.value.viewId });
  }
};

// 自定义按钮点击
const cutsomButtonClilck = (item, record) => {
  const { buttonCode } = item;
  if (buttonCode == 'delete') {
    batchDelete();
  } else if (buttonCode == 'export') {
    exportClick();
  } else {
    const { href } = router.resolve({
      path: item.customRouterUrl,
      query: {
        businessId: where.value.businessId,
        id: record?.id
      }
    });
    window.open(href, '_blank');
  }
};

// 详情点击
const detailClick = record => {
  current.value = record;
  showDetail.value = true;
};

// 获取图片列表
const getPicList = data => {
  let list = [];
  if (data) {
    list = data.split(',');
  }
  return list;
};

const back = () => {
  router.push(props.backUrl);
};

// 切换高级查询
const changeSuperSearch = () => {
  superSearch.value = !superSearch.value;
};
</script>

<style scoped lang="less">
.guns-layout-content {
  width: 100% !important;
}
.appIconWrapper {
  width: 22px;
  height: 22px;
}
.menu-item-display {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
}
.paddingRight5 {
  padding-right: 5px;
}
:deep(.ant-image-mask) {
  display: none;
}
:deep(.ant-image-img) {
  cursor: pointer;
}
.back {
  color: #898e91;
  font-size: 16px;
  cursor: pointer;
  font-weight: normal;
}
.divider {
  border-width: 1.5px;
  border-color: #c5cfd1;
  height: 16px;
}
</style>
