<template>
  <div class="dialog-box" style="position: relative">
    <el-scrollbar class="custom-scroll content-box">
      <el-form
        ref="editPlatformFormCarDriverRef"
        :model="formData"
        :size="layoutStore.defaultFormItemSize"
        :rules="rules"
        label-width="120px"
        label-position="right"
        @submit.prevent
      >
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="司机名称" prop="TourCarDriver.name">
              <el-input
                class="input-item"
                v-model="formData.TourCarDriver.name"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="TourCarDriver.sex">
              <el-select
                class="input-item"
                v-model="formData.TourCarDriver.sex"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="sexWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in sexWidgetDropdownList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄" prop="TourCarDriver.age">
              <el-input-number
                class="input-item"
                v-model="formData.TourCarDriver.age"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="驾龄" prop="TourCarDriver.drivingYears">
              <el-input-number
                class="input-item"
                v-model="formData.TourCarDriver.drivingYears"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="司机照片" prop="TourCarDriver.image">
              <custom-upload
                v-model="imageWidgetFileList"
                name="uploadFile"
                :size="layoutStore.defaultFormItemSize"
                type="expand"
                :headers="getUploadHeaders"
                :action="getUploadActionUrl('/admin/app/tourCarDriver/upload')"
                :data="{fieldName: 'image', asImage: true}"
                :limit="imageWidgetMaxCount"
                @change="onImageChange"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="评分" prop="TourCarDriver.mark">
              <el-input-number
                class="input-item"
                v-model="formData.TourCarDriver.mark"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="热度值" prop="TourCarDriver.hotValue">
              <el-input-number
                class="input-item"
                v-model="formData.TourCarDriver.hotValue"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选择归属部门" prop="TourCarDriver.deptId">
              <el-cascader
                class="input-item"
                v-model="deptIdPath"
                :options="deptIdWidgetDropdownList"
                placeholder=""
                :clearable="true"
                :filterable="true"
                :show-all-levels="false"
                :props="{ value: 'id', label: 'name', children: 'children', checkStrictly: true }"
                @change="onDeptIdValueChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="TourCarDriver.mobile">
              <el-input
                class="input-item"
                v-model="formData.TourCarDriver.mobile"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="司机类型" prop="TourCarDriver.type">
              <el-select
                class="input-item"
                v-model="formData.TourCarDriver.type"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="typeWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in typeWidgetDropdownList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="所属区域" prop="TourCarDriver.belongTab">
              <el-cascader
                class="input-item"
                v-model="belongTabPath"
                :options="belongTabWidgetDropdownList"
                placeholder=""
                :clearable="true"
                :filterable="true"
                :show-all-levels="false"
                :props="{ value: 'id', label: 'name', children: 'children', checkStrictly: true }"
                @change="onBelongTabValueChange"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-scrollbar>
    <el-row class="footer-box" type="flex" justify="end" align="middle">
      <el-button :size="layoutStore.defaultFormItemSize" @click="onCancel()">取消</el-button>
      <el-button :size="layoutStore.defaultFormItemSize" type="primary" @click="onUpdateClick()">保存</el-button>
    </el-row>
  </div>
</template>

<script lang="ts">
export default {
  name: 'editPlatformFormCarDriver',
};
</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 { TourCarDriverData } from '@/api/generated/tourCarDriverController';
import { SysDeptData } from '@/api/generated/sysDeptController';
import { TourCarDriverController, SysDeptController } 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<{
    subPage?: number | string | boolean;
    id?: ANY_OBJECT;
    saveOnSubmit?: boolean;
    rowData?: ANY_OBJECT;
    // 当使用Dialog.show弹出组件时，须定义该prop属性，以便对dialog进行回调
    dialog?: DialogProp<ANY_OBJECT[]>;
  }>(),
  {
    subPage: 0,
    id: undefined,
    saveOnSubmit: true,
    rowData: undefined,
    dialog: undefined,
  },
);

const editPlatformFormCarDriverRef = ref();
// 表单数据定义
type EditPlatformFormCarDriverData = {
  TourCarDriver: TourCarDriverData;
};
// 表单数据
const formData = reactive<EditPlatformFormCarDriverData>({
  TourCarDriver: {
    // id
    id: undefined,
    // 司机名称
    name: undefined,
    // 性别
    sex: undefined,
    // 年龄
    age: undefined,
    // 驾龄
    drivingYears: undefined,
    // 司机照片
    image: undefined,
    // 创建用户
    createUserId: undefined,
    // 创建时间
    createTime: undefined,
    // 更新用户
    updateUserId: undefined,
    // 更新时间
    updateTime: undefined,
    // 删除标记(1: 正常 -1: 已删除)
    dataState: undefined,
    // 评分
    mark: undefined,
    // 热度值
    hotValue: undefined,
    // 组织id
    deptId: undefined,
    // 联系方式
    mobile: undefined,
    // 司机类型(1.自营;2.第三方)
    type: undefined,
    // 所属区域
    belongTab: undefined,
    sysDept: {
      // 部门Id
      deptId: undefined,
      // 部门名称
      deptName: undefined,
      // 显示顺序
      showOrder: undefined,
      // 父部门Id
      parentId: undefined,
      // 删除标记(1: 正常 -1: 已删除)
      deletedFlag: undefined,
      // 创建者Id
      createUserId: undefined,
      // 更新者Id
      updateUserId: undefined,
      // 创建时间
      createTime: undefined,
      // 更新时间
      updateTime: undefined,
    },
  },
},
);
// 表单验证规则
const rules = reactive({
  // 'TourCarDriver.type': [
  //   {required: true, message: '请输入司机类型', trigger: 'blur'}
  // ],
  'TourCarDriver.age': [
    {required: true, message: '请输入年龄', trigger: 'blur'}
  ],
  'TourCarDriver.drivingYears': [
    {required: true, message: '请输入驾龄', trigger: 'blur'}
  ],
  'TourCarDriver.belongTab': [
    {required: true, message: '请输入所属区域', trigger: 'blur'}
  ],
  'TourCarDriver.mobile': [
    {required: true, message: '请输入联系方式', trigger: 'blur'}
  ],
  'TourCarDriver.image': [
    {required: true, message: '请输入司机照片', trigger: 'blur'}
  ],
  'TourCarDriver.deptId': [
    {required: true, message: '请输入选择归属部门', trigger: 'blur'}
  ],
  'TourCarDriver.name': [
    {required: true, message: '请输入司机名称', trigger: 'blur'}
  ],
  'TourCarDriver.hotValue': [
    {required: true, message: '请输入热度值', trigger: 'blur'}
  ],
  'TourCarDriver.sex': [
    {required: true, message: '请输入性别', trigger: 'blur'}
  ],
  // 'TourCarDriver.mark': [
  //   {required: true, message: '请输入评分', trigger: 'blur'}
  // ],
});

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

const isEdit = computed(() => {
  return props.saveOnSubmit ? props.id != null : props.rowData != null;
});

// 初始化页面数据
const loadTourCarDriverData = () => {
  return new Promise<void>((resolve, reject) => {
    if (!isEdit.value) {
      resolve();
      return;
    }
    if (!props.saveOnSubmit && props.rowData != null) {
      formData.TourCarDriver = JSON.parse(JSON.stringify(props.rowData));
      resolve();
      return;
    }
    let params: ANY_OBJECT = {
      id: props.id
    };
    TourCarDriverController.view(params).then(res => {
      formData.TourCarDriver = { ...res.data };
      if (formData.TourCarDriver.sysDept == null) {
        formData.TourCarDriver.sysDept = {
          deptId: undefined,
          deptName: undefined,
          showOrder: undefined,
          parentId: undefined,
          deletedFlag: undefined,
          createUserId: undefined,
          updateUserId: undefined,
          createTime: undefined,
          updateTime: undefined
        };
      }
      resolve();
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 性别下拉数据获取函数
 */
const loadSexDropdownList = (): 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 sexOptions: DropdownOptions<DictData> = {
  loadData: loadSexDropdownList,
  isTree: false,
};
// 性别下拉组件
const sexWidget = useDropdown(sexOptions);
const { dropdownList: sexWidgetDropdownList } = sexWidget
/**
 * 司机照片上传文件改变
 */
const onImageChange = val => {
  formData.TourCarDriver.image = fileListToJson(val);
};
// 司机照片上传文件组件
const imageWidget = useUploadWidget(1);
const { fileList: imageWidgetFileList, maxCount: imageWidgetMaxCount } = imageWidget;
/**
 * 选择归属部门下拉数据获取函数
 */
const loadDeptIdDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictSysDept(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 选择归属部门选中值改变
 */
const onDeptIdValueChange = (value) => {
  formData.TourCarDriver.deptId = Array.isArray(value) ? value[value.length - 1] : value;
};
// 选择归属部门配置参数
const deptIdOptions: DropdownOptions<DictData> = {
  loadData: loadDeptIdDropdownList,
  isTree: true,
};
// 选择归属部门选中数据
const deptIdPath = ref<Array<string | number>>([]);
// 选择归属部门下拉组件
const deptIdWidget = useDropdown(deptIdOptions);
const { dropdownList: deptIdWidgetDropdownList } = deptIdWidget
// /**
//  * 司机类型下拉数据获取函数
//  */
// const loadTypeDropdownList = (): Promise<ListData<DictData>> => {
//   return Promise.resolve({
//     dataList: StaticDict.TourCarType.getList(),
//   });
// };
// // 司机类型配置参数
// const typeOptions: DropdownOptions<DictData> = {
//   loadData: loadTypeDropdownList,
//   isTree: false,
// };
// // 司机类型下拉组件
// const typeWidget = useDropdown(typeOptions);
// const { dropdownList: typeWidgetDropdownList } = typeWidget
/**
 * 所属区域下拉数据获取函数
 */
const loadBelongTabDropdownList = (): Promise<ListData<DictData>> => {
  console.log(888888888888889);
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictTourCarContractMenu(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 所属区域选中值改变
 */
const onBelongTabValueChange = (value) => {
  formData.TourCarDriver.belongTab = Array.isArray(value) ? value[value.length - 1] : value;
};
// 所属区域配置参数
const belongTabOptions: DropdownOptions<DictData> = {
  loadData: loadBelongTabDropdownList,
  isTree: true,
};
// 所属区域选中数据
const belongTabPath = ref<Array<string | number>>([]);
// 所属区域下拉组件
const belongTabWidget = useDropdown(belongTabOptions);
const { dropdownList: belongTabWidgetDropdownList } = belongTabWidget
const onUploadError = () => {
  ElMessage.error('文件上传失败');
};
const onUploadLimit = () => {
  ElMessage.error('已经超出最大上传个数限制');
};
const refreshEditPlatformFormCarDriver = () => {
  // 刷新段落
};
/**
 * 重置过滤值
 */
const resetEditPlatformFormCarDriver = () => {
  refreshEditPlatformFormCarDriver();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetEditPlatformFormCarDriver();
};
/**
 * 保存
 */
const onUpdateClick = () => {
  editPlatformFormCarDriverRef.value.validate((valid) => {
    if (!valid) return;
    // 级联操作
    if (!props.saveOnSubmit) {
      let retFormData = {
        ...formData.TourCarDriver
      };
    retFormData.sexDictMap = findItemFromList(sexWidgetDropdownList.value, retFormData.sex, 'id');
    retFormData.deptIdDictMap = findTreeNode(deptIdWidgetDropdownList.value, retFormData.deptId, 'id');
    // retFormData.typeDictMap = findItemFromList(typeWidgetDropdownList.value, retFormData.type, 'id');
    retFormData.belongTabDictMap = findTreeNode(belongTabWidgetDropdownList.value, retFormData.belongTab, 'id');
  props.dialog?.submit(retFormData);
      return;
    }
    let params: ANY_OBJECT = {
      tourCarDriverDto: {
        id: formData.TourCarDriver.id,
        hotValue: formData.TourCarDriver.hotValue,
        deptId: formData.TourCarDriver.deptId,
        mobile: formData.TourCarDriver.mobile,
        type: StaticDict.TourCarType.PLATFORM_SELF_SUPPORT,
        belongTab: formData.TourCarDriver.belongTab,
        name: formData.TourCarDriver.name,
        sex: formData.TourCarDriver.sex,
        age: formData.TourCarDriver.age,
        drivingYears: formData.TourCarDriver.drivingYears,
        image: formData.TourCarDriver.image,
        createUserId: formData.TourCarDriver.createUserId,
        createTime: formData.TourCarDriver.createTime,
        updateUserId: formData.TourCarDriver.updateUserId,
        updateTime: formData.TourCarDriver.updateTime,
        mark: formData.TourCarDriver.mark,
      }
    };

    let httpCall = isEdit.value ? TourCarDriverController.update : TourCarDriverController.add;
    httpCall(params).then(res => {
      ElMessage.success('保存成功');
      props.dialog?.submit();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  });
};
const formInit = () => {
  loadTourCarDriverData().then(res => {
    sexWidget.onVisibleChange(true).catch(e => {console.error(e)});
    let imageDownloadParams = {
      id: formData.TourCarDriver.id,
      fieldName: 'image',
      asImage: true
    };
    imageWidgetFileList.value = parseUploadData(formData.TourCarDriver.image, imageDownloadParams);
    deptIdWidget.onVisibleChange(true).then(res => {
      // TODO: 获取级联选中路径
      deptIdPath.value = findTreeNodePath(res, formData.TourCarDriver.deptId);
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
    // typeWidget.onVisibleChange(true).catch(e => {console.error(e)});
    belongTabWidget.onVisibleChange(true).then(res => {
      // TODO: 获取级联选中路径
      belongTabPath.value = findTreeNodePath(res, formData.TourCarDriver.belongTab);
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
    if (isEdit.value) refreshEditPlatformFormCarDriver();
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};

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