<template>
  <div class="item-select-dlg dialog-box">
    <el-form
      ref="selectHouseAdvisorRef"
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshSelectHouseAdvisor()" @reset="resetSelectHouseAdvisor">
        <el-form-item label="姓名">
          <el-input
            class="filter-item"
            v-model="formFilter.nameFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
        <el-form-item label="是否金牌顾问">
          <el-select
            class="filter-item"
            v-model="formFilter.isGoldAdvisorFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="isGoldAdvisorFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in isGoldAdvisorFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <template #operation>
          <el-button type="primary" @click="onSubmit" :size="layoutStore.defaultFormItemSize">
            确定
          </el-button>
        </template>
      </filter-box>
    </el-form>
    <table-box
      ref="tourHouseAdvisorInfo"
      class="main-box"
      :data="tourHouseAdvisorInfoWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((tourHouseAdvisorInfoWidgetCurrentPage - 1) * tourHouseAdvisorInfoWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="false"
      @sort-change="tourHouseAdvisorInfoWidget.onSortChange"
      @refresh="tourHouseAdvisorInfoWidget.refreshTable()"
      @radio-select-change="onSelectChange"
    >
      <vxe-column title="" type="radio" align="center" :width="80" />
      <vxe-column title="头像url" min-width="100px">
        <template v-slot="scope">
          <el-image v-for="item in parseUploadData(scope.row.avatarUrl, { id: scope.row.id, fieldName: 'avatarUrl', asImage: true })"
            :preview-src-list="getPictureList(scope.row.avatarUrl, { id: scope.row.id, fieldName: 'avatarUrl', asImage: true })"
            class="table-cell-image" :key="item.url" :src="item.url" fit="fill">
            <template #error>
              <div class="table-cell-image">
                <i class="el-icon-picture-outline"></i>
              </div>
            </template>
          </el-image>
        </template>
      </vxe-column>
      <vxe-column title="姓名" field="name" />
      <vxe-column title="顾问类型" field="typeDictMap.name" />
      <vxe-column title="行业经验年限" field="experienceAge" />
      <vxe-column title="成功交房数量" field="successfulDeliveryCount" />
      <vxe-column title="是否金牌顾问" field="isGoldAdvisorDictMap.name" />
      <vxe-column title="二维码" min-width="100px">
        <template v-slot="scope">
          <el-image v-for="item in parseUploadData(scope.row.code, { id: scope.row.id, fieldName: 'code', asImage: true })"
            :preview-src-list="getPictureList(scope.row.code, { id: scope.row.id, fieldName: 'code', asImage: true })"
            class="table-cell-image" :key="item.url" :src="item.url" fit="fill">
            <template #error>
              <div class="table-cell-image">
                <i class="el-icon-picture-outline"></i>
              </div>
            </template>
          </el-image>
        </template>
      </vxe-column>
      <vxe-column title="手机号" field="mobile" />
      <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="tourHouseAdvisorInfoWidgetTotalCount"
            :current-page="tourHouseAdvisorInfoWidgetCurrentPage"
            :page-size="tourHouseAdvisorInfoWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="tourHouseAdvisorInfoWidget.onCurrentPageChange"
            @size-change="tourHouseAdvisorInfoWidget.onPageSizeChange">
          </el-pagination>
        </el-row>
      </template>
    </table-box>
  </div>
</template>

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

<script setup lang="ts">
import { DialogProp } from '@/components/Dialog/types';
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 { TourHouseAdvisorInfoData } from '@/api/generated/tourHouseAdvisorInfoController';
import { TourHouseAdvisorInfoController } from '@/api/generated';

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 pps = withDefaults(
  defineProps<{
    modelValue: TourHouseAdvisorInfoData[];
    subPage?: number | string | boolean;
    props: {
      label: string;
      value: string;
    };
    // 当使用Dialog.show弹出组件时，须定义该prop属性，以便对dialog进行回调
    dialog?: DialogProp<ANY_OBJECT[]>;
  }>(),
  {
    modelValue: () => [],
    props: () => {
      return {
        label: 'name',
        value: 'id',
      };
    },
    dialog: undefined,
  },
);
// 选中数据
const dialogSelectItems = ref<TourHouseAdvisorInfoData>();
const formFilter = reactive({
  // 姓名
  nameFilter: undefined,
  // 是否金牌顾问
  isGoldAdvisorFilter: undefined,
});
const formFilterCopy = reactive({
  // 姓名
  nameFilter: undefined,
  // 是否金牌顾问
  isGoldAdvisorFilter: undefined,
});

const onCancel = () => {
  if (pps.dialog) {
    pps.dialog.cancel();
  }
};

const onSubmit = () => {
  if (pps.dialog) {
    pps.dialog.submit(dialogSelectItems.value);
  }
};

/**
 * 重置过滤值
 */
const resetSelectHouseAdvisor = () => {
  formFilter.nameFilter = undefined;
  formFilterCopy.nameFilter = undefined;
  formFilter.isGoldAdvisorFilter = undefined;
  formFilterCopy.isGoldAdvisorFilter = undefined;
  refreshSelectHouseAdvisor();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetSelectHouseAdvisor();
};
/**
 * 表格组件数据获取函数，返回Promise
 */
const loadTourHouseAdvisorInfoWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    tourHouseAdvisorInfoDtoFilter: {
      name: formFilter.nameFilter,
      isGoldAdvisor: formFilter.isGoldAdvisorFilter,
    }
  };
  return new Promise((resolve, reject) => {
    TourHouseAdvisorInfoController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
      nextTick(() => {
        setTableSelectRow();
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadTourHouseAdvisorInfoVerify = () => {
  formFilterCopy.nameFilter = formFilter.nameFilter;
  formFilterCopy.isGoldAdvisorFilter = formFilter.isGoldAdvisorFilter;
  return true;
};
// 表格组件表格组件参数
const tourHouseAdvisorInfoOptions: TableOptions<TourHouseAdvisorInfoData> = {
  loadTableData: loadTourHouseAdvisorInfoWidgetData,
  verifyTableParameter: loadTourHouseAdvisorInfoVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: undefined,
  ascending: true,
};
// 表格组件表格组件
const tourHouseAdvisorInfo = ref();
const tourHouseAdvisorInfoWidget = useTable(tourHouseAdvisorInfoOptions);
const {
  dataList: tourHouseAdvisorInfoWidgetDataList,
  currentPage: tourHouseAdvisorInfoWidgetCurrentPage,
  pageSize: tourHouseAdvisorInfoWidgetPageSize,
  totalCount: tourHouseAdvisorInfoWidgetTotalCount,
} = tourHouseAdvisorInfoWidget;
/**
 * 是否金牌顾问下拉数据获取函数
 */
const loadIsGoldAdvisorFilterDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.IsGoldAdvisor.getList(),
  });
};
// 是否金牌顾问配置参数
const isGoldAdvisorFilterOptions: DropdownOptions<DictData> = {
  loadData: loadIsGoldAdvisorFilterDropdownList,
  isTree: false,
};
// 是否金牌顾问下拉组件
const isGoldAdvisorFilterWidget = useDropdown(isGoldAdvisorFilterOptions);
const { dropdownList: isGoldAdvisorFilterWidgetDropdownList } = isGoldAdvisorFilterWidget
const setTableSelectRow = () => {
  if (tourHouseAdvisorInfo.value == null || !Array.isArray(tourHouseAdvisorInfoWidget.dataList.value))
    return;
  setTimeout(() => {
    let selectRow = findItemFromList(
      tourHouseAdvisorInfoWidget.dataList.value,
      (dialogSelectItems.value || {})[pps.props.value],
      pps.props.value,
    );
    tourHouseAdvisorInfo.value.getTableImpl().setRadioRow(selectRow);
  }, 50);
};
const refreshSelectHouseAdvisor = () => {
  // 重新获取数据组件的数据
  tourHouseAdvisorInfoWidget.refreshTable();
};
const onSelectChange = (row?: TourHouseAdvisorInfoData) => {
  dialogSelectItems.value = row;
};

const formInit = () => {
  isGoldAdvisorFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  refreshSelectHouseAdvisor();
};

onMounted(() => {
  if (Array.isArray(pps.modelValue) && pps.modelValue.length > 0) {
    dialogSelectItems.value = {
      ...pps.modelValue[0],
    };
  }
  formInit();
});
</script>

<style scoped>
.main-box {
  flex-grow: 1;
}
</style>
