<template>
  <div class="dialog-box" style="position: relative">
    <el-form
      class="filter-box"
      ref="formSetTourHouseAdvisorInfoRef"
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormSetTourHouseAdvisorInfo()" @reset="resetFormSetTourHouseAdvisorInfo">
        <el-form-item label="顾问类型 ">
          <el-select
            class="filter-item"
            v-model="formFilter.typeFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="typeFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in typeFilterWidgetDropdownList"
              :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.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>
        <el-form-item label="公司名称">
          <el-input
            class="filter-item"
            v-model="formFilter.companyNameFilter"
            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.enableFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="enableFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in enableFilterWidgetDropdownList"
              :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.mobileFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
        <template #operation>
          <el-button
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            :disabled="selectItemList.length <= 0"
            @click="onSubmit(true)"
          >
            添加
          </el-button>
        </template>
      </filter-box>
    </el-form>
    <table-box
      ref="formSetTourHouseAdvisorInfoTable"
      class="content-box"
      :data="formSetTourHouseAdvisorInfoTableWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((formSetTourHouseAdvisorInfoTableWidgetCurrentPage - 1) * formSetTourHouseAdvisorInfoTableWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="false"
      :checkedMethod="rowChecked"
      @sort-change="formSetTourHouseAdvisorInfoTableWidget.onSortChange"
      @refresh="formSetTourHouseAdvisorInfoTableWidget.refreshTable()"
      @change="onFormSetTourHouseAdvisorInfoTableSelectionChange"
    >
      <vxe-column type="checkbox" :width="40" />
      <vxe-column title="序号" type="seq" :index="formSetTourHouseAdvisorInfoTableWidget.getTableIndex" :width="80" />
      <vxe-column title="顾问类型 " field="typeDictMap.name" />
      <vxe-column title="所属开发商" field="developersIdDictMap.name" />
      <vxe-column title="姓名" field="name" />
      <vxe-column title="行业经验年限" field="experienceAge" />
      <vxe-column title="成功交房数量" field="successfulDeliveryCount" />
      <vxe-column title="是否金牌顾问" field="isGoldAdvisorDictMap.name" />
      <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="recordNumber" />
      <vxe-column title="公司名称" field="companyName" />
      <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="enableDictMap.name" />
      <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="formSetTourHouseAdvisorInfoTableWidgetTotalCount"
            :current-page="formSetTourHouseAdvisorInfoTableWidgetCurrentPage"
            :page-size="formSetTourHouseAdvisorInfoTableWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="formSetTourHouseAdvisorInfoTableWidget.onCurrentPageChange"
            @size-change="formSetTourHouseAdvisorInfoTableWidget.onPageSizeChange">
          </el-pagination>
        </el-row>
      </template>
    </table-box>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formSetTourHouseAdvisorInfo',
};
</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 { TourHouseDevelopersTypeData } from '@/api/generated/tourHouseDevelopersTypeController';
import { TourHouseSaleInfoData } from '@/api/generated/tourHouseSaleInfoController';
import { TourHouseAdvisorInfoData } from '@/api/generated/tourHouseAdvisorInfoController';
import { TourHouseFilesData } from '@/api/generated/tourHouseFilesController';
import { TourHouseDevelopersTypeController, TourHouseSaleInfoController, TourHouseAdvisorInfoController, TourHouseFilesController } 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 props = withDefaults(
  defineProps<{
    houseId?: ANY_OBJECT;
    saveOnSubmit?: boolean;
    selectIdList?: Array<string | number>;
    // 当使用Dialog.show弹出组件时，须定义该prop属性，以便对dialog进行回调
    dialog?: DialogProp<ANY_OBJECT[]>;
  }>(),
  {
    id: undefined,
    saveOnSubmit: true,
    selectIdList: undefined,
    dialog: undefined,
  },
);

const formSetTourHouseAdvisorInfoRef = ref();
const selectItemList = ref<TourHouseAdvisorInfoData[]>([]);
const formFilter = reactive({
  // 顾问类型 
  typeFilter: undefined,
  // 是否金牌顾问
  isGoldAdvisorFilter: undefined,
  // 公司名称
  companyNameFilter: undefined,
  // 是否启用
  enableFilter: undefined,
  // 手机号
  mobileFilter: undefined,
});
const formFilterCopy = reactive({
  // 顾问类型 
  typeFilter: undefined,
  // 是否金牌顾问
  isGoldAdvisorFilter: undefined,
  // 公司名称
  companyNameFilter: undefined,
  // 是否启用
  enableFilter: undefined,
  // 手机号
  mobileFilter: undefined,
});

const onCancel = () => {
  if (props.dialog) {
    props.dialog.cancel();
  }
};
const onSubmit = () => {
  if (!props.saveOnSubmit) {
    props.dialog?.submit(selectItemList.value);
    return;
  }
  let params: ANY_OBJECT = {
    houseId: props.houseId,
    tourHouseAdvisorRelationDtoList: selectItemList.value.map((item) => {
      return {
        advisorId: item.id
      };
    })
  };

  TourHouseSaleInfoController.addTourHouseAdvisorRelation(params).then(res => {
    ElMessage.success('添加成功');
    props.dialog?.submit(selectItemList.value);
  }).catch(e => {
    // 异常处理
    console.error(e);
  });
};
/**
 * 表格组件数据获取函数，返回Promise
 */
const loadFormSetTourHouseAdvisorInfoTableWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    id:props.houseId,
    tourHouseAdvisorInfoDtoFilter: {
      type: formFilter.typeFilter,
      isGoldAdvisor: formFilter.isGoldAdvisorFilter,
      companyName: formFilter.companyNameFilter,
      enable: formFilter.enableFilter,
      mobile: formFilter.mobileFilter,
    }
  };
  console.log(999999999999)
  console.log(props)
  return new Promise((resolve, reject) => {
    TourHouseSaleInfoController.listNotInTourHouseAdvisorRelation(params).then(res => {
      // 级联更新设置临时唯一id
      let tempTime = new Date().getTime();
      resolve({
        dataList: res.data.dataList.map((item, index) => {
          return {
            __cascade_add_temp_id__: tempTime + index,
            ...item
          }
        }),
        totalCount: res.data.totalCount
      });
      selectItemList.value = [];
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadFormSetTourHouseAdvisorInfoTableVerify = () => {
  formFilterCopy.typeFilter = formFilter.typeFilter;
  formFilterCopy.isGoldAdvisorFilter = formFilter.isGoldAdvisorFilter;
  formFilterCopy.companyNameFilter = formFilter.companyNameFilter;
  formFilterCopy.enableFilter = formFilter.enableFilter;
  formFilterCopy.mobileFilter = formFilter.mobileFilter;
  return true;
};
// 表格组件表格组件参数
const formSetTourHouseAdvisorInfoTableOptions: TableOptions<TourHouseAdvisorInfoData> = {
  loadTableData: loadFormSetTourHouseAdvisorInfoTableWidgetData,
  verifyTableParameter: loadFormSetTourHouseAdvisorInfoTableVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: undefined,
  ascending: true,
};
// 表格组件表格组件
const formSetTourHouseAdvisorInfoTable = ref();
const formSetTourHouseAdvisorInfoTableWidget = useTable(formSetTourHouseAdvisorInfoTableOptions);
const {
  dataList: formSetTourHouseAdvisorInfoTableWidgetDataList,
  currentPage: formSetTourHouseAdvisorInfoTableWidgetCurrentPage,
  pageSize: formSetTourHouseAdvisorInfoTableWidgetPageSize,
  totalCount: formSetTourHouseAdvisorInfoTableWidgetTotalCount,
} = formSetTourHouseAdvisorInfoTableWidget;
// 表格行数据选中事件
const onFormSetTourHouseAdvisorInfoTableSelectionChange = (val: TourHouseAdvisorInfoData[]) => {
  selectItemList.value = val;
};
// 表格行是否允许被选中
const rowChecked = ({ row }: { row: TourHouseAdvisorInfoData }) => {
  if (Array.isArray(props.selectIdList) && props.selectIdList.length > 0) {
    return props.selectIdList.indexOf(row.id) === -1;
  }
  return true;
};
/**
 * 顾问类型 下拉数据获取函数
 */
const loadTypeFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'AdvisorType', itemIdType: 'Integer' }).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 顾问类型 配置参数
const typeFilterOptions: DropdownOptions<DictData> = {
  loadData: loadTypeFilterDropdownList,
  isTree: false,
};
// 顾问类型 下拉组件
const typeFilterWidget = useDropdown(typeFilterOptions);
const { dropdownList: typeFilterWidgetDropdownList } = typeFilterWidget
/**
 * 是否金牌顾问下拉数据获取函数
 */
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 loadEnableFilterDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.Enable.getList(),
  });
};
// 是否启用配置参数
const enableFilterOptions: DropdownOptions<DictData> = {
  loadData: loadEnableFilterDropdownList,
  isTree: false,
};
// 是否启用下拉组件
const enableFilterWidget = useDropdown(enableFilterOptions);
const { dropdownList: enableFilterWidgetDropdownList } = enableFilterWidget
const refreshFormSetTourHouseAdvisorInfo = () => {
  // 刷新段落
  formSetTourHouseAdvisorInfoTableWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormSetTourHouseAdvisorInfo = () => {
  formFilter.typeFilter = undefined;
  formFilterCopy.typeFilter = undefined;
  formFilter.isGoldAdvisorFilter = undefined;
  formFilterCopy.isGoldAdvisorFilter = undefined;
  formFilter.companyNameFilter = undefined;
  formFilterCopy.companyNameFilter = undefined;
  formFilter.enableFilter = undefined;
  formFilterCopy.enableFilter = undefined;
  formFilter.mobileFilter = undefined;
  formFilterCopy.mobileFilter = undefined;
  refreshFormSetTourHouseAdvisorInfo();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormSetTourHouseAdvisorInfo();
};
const formInit = () => {
  typeFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  isGoldAdvisorFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  enableFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  refreshFormSetTourHouseAdvisorInfo();
};

onMounted(() => {
  formInit();
});
</script>
