<template>
  <div class="page-box" style="position: relative;">
    <el-form
      ref="formTourImComplaitRef"
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormTourImComplait()" @reset="resetFormTourImComplait">
        <el-form-item label="举报类型">
          <el-select
            class="filter-item"
            v-model="formFilter.typeIdFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="typeIdFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in typeIdFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="举报对象">
          <el-select
            class="filter-item"
            v-model="formFilter.objectTypeFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="objectTypeFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in objectTypeFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="举报描述">
          <el-input
            class="filter-item"
            v-model="formFilter.descriptionFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
      </filter-box>
    </el-form>
    <table-box
      ref="formTourImComplaitTable"
      class="page-table"
      :data="formTourImComplaitTableWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((formTourImComplaitTableWidgetCurrentPage - 1) * formTourImComplaitTableWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="true"
      @sort-change="formTourImComplaitTableWidget.onSortChange"
      @refresh="formTourImComplaitTableWidget.refreshTable()"
    >
      <template #operator>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          :disabled="!checkPermCodeExist('formTourImComplait:formTourImComplait:addTourImComplait')"
          @click="onAddTourImComplaitClick()"
          >
          新建
        </el-button>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          :disabled="!checkPermCodeExist('formTourImComplait:formTourImComplait:exportTourImComplait')"
          @click="onExportTourImComplaitClick()"
          >
          导出
        </el-button>
        <el-upload
          class="btn-import"
          :auto-upload="false"
          action=""
          :show-file-list="false"
          accept=".xls,.xlsx"
          style="display: inline-block;"
          :disabled="!checkPermCodeExist('formTourImComplait:formTourImComplait:importTourImComplait')"
          :on-change="onImportTourImComplaitClick"
        >
          <template #trigger>
            <el-button
              type="primary"
              :size="layoutStore.defaultFormItemSize"
              :disabled="!checkPermCodeExist('formTourImComplait:formTourImComplait:importTourImComplait')"
            >
              导入
            </el-button>
          </template>
        </el-upload>
      </template>
      <vxe-column title="序号" type="seq" :index="formTourImComplaitTableWidget.getTableIndex" :width="80" />
      <vxe-column title="举报类型" field="typeIdDictMap.name" />
      <vxe-column title="举报对象类型" field="objectTypeDictMap.name" />
      <vxe-column title="举报对象名称" field="objectTypeDictMap.name">
        <template v-slot="scope">
          <span v-if="scope.row.objectType == 2">
            <span v-if="scope.row.groupIdDictMap">{{ scope.row.groupIdDictMap.name }}</span>
          </span>
          <span v-if="scope.row.objectType == 1">
            <span v-if="scope.row.userIdDictMap">{{ scope.row.userIdDictMap.name }}</span>
          <span v-else>-</span>
        </span>
        </template>
      </vxe-column>

      <vxe-column title="举报对象id" field="userIdDictMap.name">
        <template v-slot="scope">
    <span v-if="scope.row.objectType == 1">
      {{ scope.row.userId }}
    </span>
          <span v-if="scope.row.objectType == 2">
      {{ scope.row.groupId }}
    </span>
        </template>
      </vxe-column>

      <vxe-column title="其他违规理由" field="elseTypeReason" />
      <vxe-column title="举报描述" field="description" />
      <vxe-column title="举报图片">
        <template v-slot="scope">
          <upload-file-list
            :file-list="
              parseUploadData(scope.row.image, {
                id: scope.row.id,
                fieldName: 'image',
                asImage: true
              })
            "
            type="card"
            direction="horizontal"
            :readonly="true"
          />
        </template>
      </vxe-column>
      <vxe-column title="操作" fixed="right">
        <template v-slot="scope">
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onEditTourImComplaitClick(scope.row)"
            :disabled="!checkPermCodeExist('formTourImComplait:formTourImComplait:editTourImComplait')"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onDeleteTourImComplaitClick(scope.row)"
            :disabled="!checkPermCodeExist('formTourImComplait:formTourImComplait:deleteTourImComplait')"
          >
            删除
          </el-button>
        </template>
      </vxe-column>
      <template slot="empty">
        <div class="table-empty unified-font">
          <img src="@/assets/img/empty.png">
          <span>暂无数据</span>
        </div>
      </template>
      <!-- 分页 -->
      <template #pagination>
        <el-row type="flex" justify="end" style="margin-top: 10px;">
          <el-pagination
            :total="formTourImComplaitTableWidgetTotalCount"
            :current-page="formTourImComplaitTableWidgetCurrentPage"
            :page-size="formTourImComplaitTableWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="formTourImComplaitTableWidget.onCurrentPageChange"
            @size-change="formTourImComplaitTableWidget.onPageSizeChange">
          </el-pagination>
        </el-row>
      </template>
    </table-box>
    <label v-if="subPage" class="page-close-box" @click="onCancel()">
      <img src="@/assets/img/back2.png" alt="">
    </label>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formTourImComplait',
};
</script>

<script setup lang="ts">
import { VxeColumn, VxeTable } from 'vxe-table';
import { ANY_OBJECT } from '@/types/generic';
import { DictData, DictionaryBase } from '@/common/staticDict/types';
import { ElMessage, ElMessageBox, UploadFile } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { useCommon } from '@/common/hooks/useCommon';
import { useLayoutStore, useStaticDictStore } from '@/store';
import { useDownload } from '@/common/hooks/useDownload';
import { useDropdown } from '@/common/hooks/useDropdown';
import { DropdownOptions, ListData } from '@/common/types/list';
import { useTable } from '@/common/hooks/useTable';
import { TableOptions } from '@/common/types/pagination';
import { useUpload } from '@/common/hooks/useUpload';
import { useUploadWidget } from '@/common/hooks/useUploadWidget';
import { DictionaryController } from '@/api/system';
import { treeDataTranslate, findItemFromList, findTreeNodePath, findTreeNode, stringCase } from '@/common/utils';
import { TourImComplaitData } from '@/api/generated/tourImComplaitController';
import { TourImComplaitController } from '@/api/generated';
import FormEditTourImComplait from '@/pages/ImComplaint/formEditTourImComplait.vue';
import "./formTourImComplait.vue";

const router = useRouter();
const route = useRoute();
const layoutStore = useLayoutStore();
const { downloadFile } = useDownload();
const { getUploadHeaders, getUploadActionUrl, fileListToJson, parseUploadData, getPictureList } = useUpload();
const {
  Delete,
  Search,
  Edit,
  Plus,
  Refresh,
  Picture,
  Dialog,
  mainContextHeight,
  clientHeight,
  checkPermCodeExist,
  parseParams,
  parseArrayParams,
  formatDateByStatsType,
  getDateRangeFilter,
} = useCommon();
// 静态字典
const { staticDict: StaticDict } = useStaticDictStore();

const props = withDefaults(
  defineProps<{
    subPage?: number | string | boolean;
  }>(),
  {
    subPage: 0,
  },
);

const formFilter = reactive({
  // 举报类型
  typeIdFilter: undefined,
  // 举报对象
  objectTypeFilter: undefined,
  // 举报描述
  descriptionFilter: undefined,
});
const formFilterCopy = reactive({
  // 举报类型
  typeIdFilter: undefined,
  // 举报对象
  objectTypeFilter: undefined,
  // 举报描述
  descriptionFilter: undefined,
});

const onCancel = () => {
  router.go(-1);
  layoutStore.removeCachePage(route.fullPath as string);
  route.meta.refreshParentCachedPage = true;
};

const onResume = () => {
  refreshFormTourImComplait();
};

/**
 * 表格组件数据获取函数，返回Promise
 */
const loadFormTourImComplaitTableWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    tourImComplaitDtoFilter: {
      typeId: formFilter.typeIdFilter,
      objectType: formFilter.objectTypeFilter,
      description: formFilter.descriptionFilter,
    }
  };
  return new Promise((resolve, reject) => {
    TourImComplaitController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadFormTourImComplaitTableVerify = () => {
  formFilterCopy.typeIdFilter = formFilter.typeIdFilter;
  formFilterCopy.objectTypeFilter = formFilter.objectTypeFilter;
  formFilterCopy.descriptionFilter = formFilter.descriptionFilter;
  return true;
};
/**
 * 新建
 */
const onAddTourImComplaitClick = (row?: TourImComplaitData) => {
  let params: ANY_OBJECT = {
  };

  Dialog
    .show('新建', FormEditTourImComplait, { area: '900px' }, { ...params, subPage: true })
    .then(res => {
      formTourImComplaitTableWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 编辑
 */
const onEditTourImComplaitClick = (row?: TourImComplaitData) => {
  let params: ANY_OBJECT = {
    id: row?.id,
  };

  Dialog
    .show('编辑', FormEditTourImComplait, { area: '900px' }, { ...params, subPage: true })
    .then(res => {
      formTourImComplaitTableWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 导出
 */
const onExportTourImComplaitClick = (row?: TourImComplaitData) => {
  let params: ANY_OBJECT = {
  };

  TourImComplaitController.export(params, '表格组件.xlsx').then(res => {
    ElMessage.success('导出成功');
  }).catch(e => {
    ElMessage.error(e.errorMessage);
  });
};
/**
 * 导入
 */
const onImportTourImComplaitClick = (file) => {
  let params: ANY_OBJECT = {
    importFile: file.raw,
    // 是否忽略表头
    skipHeader: false
  };

  TourImComplaitController.import(params).then(res => {
    ElMessage.success('导入成功');
    formTourImComplaitTableWidget.refreshTable();
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
/**
 * 删除
 */
const onDeleteTourImComplaitClick = (row?: TourImComplaitData) => {
  let params: ANY_OBJECT = {
    id: row?.id,
  };

  ElMessageBox.confirm('是否删除此记录？').then(res => {
    TourImComplaitController.delete(params).then(res => {
      ElMessage.success('删除成功');
      formTourImComplaitTableWidget.refreshTable(false, 1);
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
// 表格组件表格组件参数
const formTourImComplaitTableOptions: TableOptions<TourImComplaitData> = {
  loadTableData: loadFormTourImComplaitTableWidgetData,
  verifyTableParameter: loadFormTourImComplaitTableVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: undefined,
  ascending: true,
};
// 表格组件表格组件
const formTourImComplaitTable = ref();
const formTourImComplaitTableWidget = useTable(formTourImComplaitTableOptions);
const {
  dataList: formTourImComplaitTableWidgetDataList,
  currentPage: formTourImComplaitTableWidgetCurrentPage,
  pageSize: formTourImComplaitTableWidgetPageSize,
  totalCount: formTourImComplaitTableWidgetTotalCount,
} = formTourImComplaitTableWidget;
/**
 * 举报类型下拉数据获取函数
 */
const loadTypeIdFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictTourImComplaintType(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 举报类型配置参数
const typeIdFilterOptions: DropdownOptions<DictData> = {
  loadData: loadTypeIdFilterDropdownList,
  isTree: false,
};
// 举报类型下拉组件
const typeIdFilterWidget = useDropdown(typeIdFilterOptions);
const { dropdownList: typeIdFilterWidgetDropdownList } = typeIdFilterWidget
/**
 * 举报对象下拉数据获取函数
 */
const loadObjectTypeFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'ComplaintObjectType', itemIdType: 'Integer' }).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 举报对象配置参数
const objectTypeFilterOptions: DropdownOptions<DictData> = {
  loadData: loadObjectTypeFilterDropdownList,
  isTree: false,
};
// 举报对象下拉组件
const objectTypeFilterWidget = useDropdown(objectTypeFilterOptions);
const { dropdownList: objectTypeFilterWidgetDropdownList } = objectTypeFilterWidget
const refreshFormTourImComplait = () => {
  // 刷新段落
  formTourImComplaitTableWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormTourImComplait = () => {
  formFilter.typeIdFilter = undefined;
  formFilterCopy.typeIdFilter = undefined;
  formFilter.objectTypeFilter = undefined;
  formFilterCopy.objectTypeFilter = undefined;
  formFilter.descriptionFilter = undefined;
  formFilterCopy.descriptionFilter = undefined;
  refreshFormTourImComplait();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormTourImComplait();
};
const formInit = () => {
  typeIdFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  objectTypeFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  refreshFormTourImComplait();
};

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

onActivated(() => {
  onResume();
});
</script>
