<template>
  <div class="page-box" style="position: relative;">
    <el-form
      ref="formThirdCarDriverRef"
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormThirdCarDriver()" @reset="resetFormThirdCarDriver">
        <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.sexFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="sexFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in sexFilterWidgetDropdownList"
              :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>
        <!-- <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-cascader
            class="filter-item"
            v-model="belongTabFilterPath"
            :options="belongTabFilterWidgetDropdownList"
            placeholder=""
            :clearable="true"
            :filterable="true"
            :show-all-levels="false"
            :props="{ value: 'id', label: 'name', children: 'children', checkStrictly: true }"
            @change="onBelongTabFilterValueChange"
          />
        </el-form-item>
      </filter-box>
    </el-form>
    <table-box
      ref="tourCarDriver"
      class="page-table"
      :data="tourCarDriverWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((tourCarDriverWidgetCurrentPage - 1) * tourCarDriverWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="true"
      @sort-change="tourCarDriverWidget.onSortChange"
      @refresh="tourCarDriverWidget.refreshTable()"
    >
      <template #operator>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          :disabled="!checkPermCodeExist('formThirdCarDriver:formThirdCarDriver:add')"
          @click="onAddClick()"
          >
          新建
        </el-button>
      </template>
      <vxe-column title="序号" type="seq" :index="tourCarDriverWidget.getTableIndex" :width="80" />
      <vxe-column title="司机名称" field="name" />
      <vxe-column title="性别" field="sexDictMap.name" />
      <vxe-column title="年龄" field="age" />
      <vxe-column title="驾龄" field="drivingYears" />
      <vxe-column title="司机照片" min-width="100px">
        <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="评分" field="mark" /> -->
      <vxe-column title="热度值" field="hotValue" />
      <vxe-column title="归属部门" field="deptId" />
      <vxe-column title="联系方式" field="mobile" />
      <vxe-column title="司机类型" field="typeDictMap.name" />
      <vxe-column title="所属区域" field="belongTabDictMap.name" />
      <vxe-column title="操作" fixed="right">
        <template v-slot="scope">
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onEditClick(scope.row)"
            :disabled="!checkPermCodeExist('formThirdCarDriver:formThirdCarDriver:edit')"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onDeleteClick(scope.row)"
            :disabled="!checkPermCodeExist('formThirdCarDriver:formThirdCarDriver:delete')"
          >
            删除
          </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="tourCarDriverWidgetTotalCount"
            :current-page="tourCarDriverWidgetCurrentPage"
            :page-size="tourCarDriverWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="tourCarDriverWidget.onCurrentPageChange"
            @size-change="tourCarDriverWidget.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: 'formThirdCarDriver',
};
</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 { TourCarDriverData } from '@/api/generated/tourCarDriverController';
import { SysDeptData } from '@/api/generated/sysDeptController';
import { TourCarDriverController, SysDeptController } from '@/api/generated';
import EditFormThirdCarDrive from '@/pages/tourContractCarInfo/editFormThirdCarDrive.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({
  // 司机名称
  nameFilter: undefined,
  // 性别
  sexFilter: undefined,
  // 联系方式
  mobileFilter: undefined,
  // 司机类型
  typeFilter: undefined,
  // 所属区域
  belongTabFilter: undefined,
});
const formFilterCopy = reactive({
  // 司机名称
  nameFilter: undefined,
  // 性别
  sexFilter: undefined,
  // 联系方式
  mobileFilter: undefined,
  // 司机类型
  typeFilter: undefined,
  // 所属区域
  belongTabFilter: undefined,
});

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

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

/**
 * 表格组件数据获取函数，返回Promise
 */
const loadTourCarDriverWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    tourCarDriverDtoFilter: {
      name: formFilter.nameFilter,
      sex: formFilter.sexFilter,
      mobile: formFilter.mobileFilter,
      //自营为1,第三方为2
      type: 2,
      belongTab: formFilter.belongTabFilter,
    }
  };
  return new Promise((resolve, reject) => {
    TourCarDriverController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadTourCarDriverVerify = () => {
  formFilterCopy.nameFilter = formFilter.nameFilter;
  formFilterCopy.sexFilter = formFilter.sexFilter;
  formFilterCopy.mobileFilter = formFilter.mobileFilter;
  formFilterCopy.typeFilter = formFilter.typeFilter;
  formFilterCopy.belongTabFilter = formFilter.belongTabFilter;
  return true;
};
/**
 * 新建
 */
const onAddClick = (row?: TourCarDriverData) => {
  let params: ANY_OBJECT = {
  };
  //判断是否为管理员，如果不是，则进行提示
TourCarDriverController.isAdmin(params).then(res => {
  TourCarDriverController.existDriver(params).then(res => {
    Dialog
      .show('新建', EditFormThirdCarDrive, { area: ['900px', '700px'] }, { ...params, subPage: true })
      .then(res => {
        tourCarDriverWidget.refreshTable();
      }).catch(e => {
        // TODO: 异常处理
        console.error(e);
      });
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });}).catch(e => {
// TODO: 异常处理
console.error(e);
});
};
/**
 * 编辑
 */
const onEditClick = (row?: TourCarDriverData) => {
  let params: ANY_OBJECT = {
    id: row?.id,
  };

  //判断是否为管理员，如果不是，则进行提示
  TourCarDriverController.isAdmin(params).then(res => {
  Dialog
    .show('编辑', EditFormThirdCarDrive, { area: ['900px', '700px'] }, { ...params, subPage: true })
    .then(res => {
      tourCarDriverWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });}).catch(e => {
  return;
 // TODO: 异常处理
 console.error(e);
});
};
/**
 * 删除
 */
const onDeleteClick = (row?: TourCarDriverData) => {
  let params: ANY_OBJECT = {
    id: row?.id,
  };

//判断是否为管理员，如果不是，则进行提示
TourCarDriverController.isAdmin(params).then(res => {
  TourCarDriverController.verifyDelCarInfo(params).then(res => {
    ElMessageBox.confirm('是否删除此条数据?').then(res => {
      TourCarDriverController.delete(params).then(res => {
        ElMessage.success('删除成功');
        tourCarDriverWidget.refreshTable(false, 1);
      }).catch(e => {
        // TODO: 异常处理
        console.error(e);
      });
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    })
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
// 表格组件表格组件参数
const tourCarDriverOptions: TableOptions<TourCarDriverData> = {
  loadTableData: loadTourCarDriverWidgetData,
  verifyTableParameter: loadTourCarDriverVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: undefined,
  ascending: true,
};
// 表格组件表格组件
const tourCarDriver = ref();
const tourCarDriverWidget = useTable(tourCarDriverOptions);
const {
  dataList: tourCarDriverWidgetDataList,
  currentPage: tourCarDriverWidgetCurrentPage,
  pageSize: tourCarDriverWidgetPageSize,
  totalCount: tourCarDriverWidgetTotalCount,
} = tourCarDriverWidget;
/**
 * 性别下拉数据获取函数
 */
const loadSexFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'UserSex', itemIdType: 'Integer' }).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 性别配置参数
const sexFilterOptions: DropdownOptions<DictData> = {
  loadData: loadSexFilterDropdownList,
  isTree: false,
};
// 性别下拉组件
const sexFilterWidget = useDropdown(sexFilterOptions);
const { dropdownList: sexFilterWidgetDropdownList } = sexFilterWidget
/**
 * 司机类型下拉数据获取函数
 */
const loadTypeFilterDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.TourCarType.getList(),
  });
};
// 司机类型配置参数
const typeFilterOptions: DropdownOptions<DictData> = {
  loadData: loadTypeFilterDropdownList,
  isTree: false,
};
// 司机类型下拉组件
const typeFilterWidget = useDropdown(typeFilterOptions);
const { dropdownList: typeFilterWidgetDropdownList } = typeFilterWidget
/**
 * 所属区域下拉数据获取函数
 */
const loadBelongTabFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictTourCarContractMenu(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 所属区域选中值改变
 */
const onBelongTabFilterValueChange = (value) => {
  formFilter.belongTabFilter = Array.isArray(value) ? value[value.length - 1] : value;
};
// 所属区域配置参数
const belongTabFilterOptions: DropdownOptions<DictData> = {
  loadData: loadBelongTabFilterDropdownList,
  isTree: true,
};
// 所属区域选中数据
const belongTabFilterPath = ref<Array<string | number>>([]);
// 所属区域下拉组件
const belongTabFilterWidget = useDropdown(belongTabFilterOptions);
const { dropdownList: belongTabFilterWidgetDropdownList } = belongTabFilterWidget
const refreshFormThirdCarDriver = () => {
  // 刷新段落
  tourCarDriverWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormThirdCarDriver = () => {
  formFilter.nameFilter = undefined;
  formFilterCopy.nameFilter = undefined;
  formFilter.sexFilter = undefined;
  formFilterCopy.sexFilter = undefined;
  formFilter.mobileFilter = undefined;
  formFilterCopy.mobileFilter = undefined;
  formFilter.typeFilter = undefined;
  formFilterCopy.typeFilter = undefined;
  formFilter.belongTabFilter = undefined;
  formFilterCopy.belongTabFilter = undefined;
  belongTabFilterPath.value = [];
  refreshFormThirdCarDriver();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormThirdCarDriver();
};
const formInit = () => {
  sexFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  typeFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  belongTabFilterWidget.onVisibleChange(true).then(res => {
    // TODO: 获取级联选中路径
    belongTabFilterPath.value = findTreeNodePath(res, formFilter.belongTabFilter);
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
  refreshFormThirdCarDriver();
};

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