<template>
  <div class="dialog-box" style="position: relative">
    <el-scrollbar class="custom-scroll content-box">
      <el-form
        ref="editThirdCarCategoryRef"
        :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="TourCarCategory.title">
              <el-input
                class="input-item"
                v-model="formData.TourCarCategory.title"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="车型种类" prop="TourCarCategory.model">
              <el-select
                class="input-item"
                v-model="formData.TourCarCategory.model"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="modelWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in modelWidgetDropdownList"
                  :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="TourCarCategory.name">
              <el-input
                class="input-item"
                v-model="formData.TourCarCategory.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="TourCarCategory.seatNumber">
              <el-input-number
                class="input-item"
                v-model="formData.TourCarCategory.seatNumber"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="包车价格" prop="TourCarCategory.price">
              <el-input-number
                class="input-item"
                v-model="formData.TourCarCategory.price"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="TourCarCategory.unit">
              <el-input
                class="input-item"
                v-model="formData.TourCarCategory.unit"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图片" prop="TourCarCategory.image">
              <custom-upload
                v-model="imageWidgetFileList"
                name="uploadFile"
                :size="layoutStore.defaultFormItemSize"
                type="expand"
                :headers="getUploadHeaders"
                :action="getUploadActionUrl('/admin/app/tourCarCategory/upload')"
                :data="{fieldName: 'image', asImage: true}"
                :limit="imageWidgetMaxCount"
                @change="onImageChange"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="所属区域" prop="TourCarCategory.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-col :span="12">
            <el-form-item label="车型归属" prop="TourCarCategory.type">
              <el-select
                class="input-item"
                v-model="formData.TourCarCategory.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="TourCarCategory.label">
              <el-input
                class="input-item"
                v-model="formData.TourCarCategory.label"
                type="text"
                placeholder="以&隔开"
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="评分" prop="TourCarCategory.mark">
              <el-input-number
                class="input-item"
                v-model="formData.TourCarCategory.mark"
                placeholder=""
                :clearable="true"
                :min="1"
                :max="5"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="是否启用" prop="TourCarCategory.enable">
              <el-select
                class="input-item"
                v-model="formData.TourCarCategory.enable"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="enableWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in enableWidgetDropdownList"
                  :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="TourCarCategory.hotValue">
              <el-input-number
                class="input-item"
                v-model="formData.TourCarCategory.hotValue"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="行李数" prop="TourCarCategory.luggageNumber">
              <el-input-number
                class="input-item"
                v-model="formData.TourCarCategory.luggageNumber"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="绑定司机" prop="TourCarCategory.relationDriverId">
              <SelectCarDriver
                class="input-item"
                v-model="formData.TourCarCategory.relationDriverId"
                placeholder=""
                :required="false"
                :disabled="false"
                :props="{
                  label: 'name',
                  value: 'id'
                }"
              />
            </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: 'editThirdCarCategory',
};
</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 { TourCarCategoryData } from '@/api/generated/tourCarCategoryController';
import { TourCarDriverController, SysDeptController, TourCarCategoryController } from '@/api/generated';
import SelectCarDriver from '@/pages/tourContractCarInfo/selectCarDriver/index.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;
    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 editThirdCarCategoryRef = ref();
// 表单数据定义
type EditThirdCarCategoryData = {
  TourCarCategory: TourCarCategoryData;
};
// 表单数据
const formData = reactive<EditThirdCarCategoryData>({
  TourCarCategory: {
    // id
    id: undefined,
    // 车型种类
    model: undefined,
    // 标题
    title: undefined,
    // 车名
    name: undefined,
    // 包车价格
    price: undefined,
    // 单位
    unit: undefined,
    // 座位数
    seatNumber: undefined,
    // 图片
    image: undefined,
    // 车型归属(1.平台自营;2.三方个人)
    type: undefined,
    // 关联司机(若车型归属为2，则必填)
    relationDriverId: undefined,
    // 车型标签(以 ,隔开)
    label: undefined,
    // 创建用户
    createUserId: undefined,
    // 创建时间
    createTime: undefined,
    // 更新用户
    updateUserId: undefined,
    // 更新时间
    updateTime: undefined,
    // 删除标记(1: 正常 -1: 已删除)
    dataState: undefined,
    // 评分
    mark: undefined,
    // 组织id
    deptId: undefined,
    // 是否启用
    enable: undefined,
    // 热度值
    hotValue: undefined,
    // 所属区域
    belongTab: undefined,
    // 行李数
    luggageNumber: undefined,
    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({
  'TourCarCategory.image': [
    {required: true, message: '请输入图片', trigger: 'blur'}
  ],
  'TourCarCategory.seatNumber': [
    {required: true, message: '请输入乘客座位数', trigger: 'blur'}
  ],
  'TourCarCategory.unit': [
    {required: true, message: '请输入单位', trigger: 'blur'}
  ],
  // 'TourCarCategory.mark': [
  //   {required: true, message: '请输入评分', trigger: 'blur'}
  // ],
  'TourCarCategory.luggageNumber': [
    {required: true, message: '请输入行李数', trigger: 'blur'}
  ],
  'TourCarCategory.hotValue': [
    {required: true, message: '请输入热度值', trigger: 'blur'}
  ],
  // 'TourCarCategory.belongTab': [
  //   {required: true, message: '请输入所属区域', trigger: 'blur'}
  // ],
  'TourCarCategory.model': [
    {required: true, message: '请输入车型种类', trigger: 'blur'}
  ],
  'TourCarCategory.enable': [
    {required: true, message: '请输入是否启用', trigger: 'blur'}
  ],
  'TourCarCategory.label': [
    {required: true, message: '请输入车型标签', trigger: 'blur'}
  ],
  'TourCarCategory.relationDriverId': [
    {required: true, message: '请输入绑定司机', trigger: 'blur'}
  ],
  'TourCarCategory.type': [
    {required: true, message: '请输入车型归属', trigger: 'blur'}
  ],
  'TourCarCategory.price': [
    {required: true, message: '请输入包车价格', trigger: 'blur'}
  ],
  'TourCarCategory.name': [
    {required: true, message: '请输入车名', trigger: 'blur'}
  ],
  // 'TourCarCategory.title': [
  //   {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 loadTourCarCategoryData = () => {
  return new Promise<void>((resolve, reject) => {
    if (!isEdit.value) {
      resolve();
      return;
    }
    if (!props.saveOnSubmit && props.rowData != null) {
      formData.TourCarCategory = JSON.parse(JSON.stringify(props.rowData));
      resolve();
      return;
    }
    let params: ANY_OBJECT = {
      id: props.id
    };
    TourCarCategoryController.view(params).then(res => {
      formData.TourCarCategory = { ...res.data };
      if (formData.TourCarCategory.tourCarDriver == null) {
        formData.TourCarCategory.tourCarDriver = {
          id: undefined,
          name: undefined,
          sex: undefined,
          age: undefined,
          drivingYears: undefined,
          image: undefined,
          createUserId: undefined,
          createTime: undefined,
          updateUserId: undefined,
          updateTime: undefined,
          dataState: undefined,
          mark: undefined,
          hotValue: undefined,
          deptId: undefined,
          mobile: undefined,
          type: undefined,
          belongTab: undefined
        };
      }
      if (formData.TourCarCategory.sysDept == null) {
        formData.TourCarCategory.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 loadModelDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictTourCarModel(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 车型种类配置参数
const modelOptions: DropdownOptions<DictData> = {
  loadData: loadModelDropdownList,
  isTree: false,
};
// 车型种类下拉组件
const modelWidget = useDropdown(modelOptions);
const { dropdownList: modelWidgetDropdownList } = modelWidget
/**
 * 图片上传文件改变
 */
const onImageChange = val => {
  formData.TourCarCategory.image = fileListToJson(val);
};
// 图片上传文件组件
const imageWidget = useUploadWidget(1);
const { fileList: imageWidgetFileList, maxCount: imageWidgetMaxCount } = imageWidget;
// /**
//  * 所属区域下拉数据获取函数
//  */
// const loadBelongTabDropdownList = (): Promise<ListData<DictData>> => {
//   return new Promise((resolve, reject) => {
//     const params = {
//     };
//     DictionaryController.dictTourCarContractMenu(params).then(res => {
//       resolve({
//         dataList: res.getList(),
//       });
//     }).catch(e => {
//       reject(e);
//     });
//   });
// };
// /**
//  * 所属区域选中值改变
//  */
// const onBelongTabValueChange = (value) => {
//   formData.TourCarCategory.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 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 loadEnableDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.Enable.getList(),
  });
};
// 是否启用配置参数
const enableOptions: DropdownOptions<DictData> = {
  loadData: loadEnableDropdownList,
  isTree: false,
};
// 是否启用下拉组件
const enableWidget = useDropdown(enableOptions);
const { dropdownList: enableWidgetDropdownList } = enableWidget
const onUploadError = () => {
  ElMessage.error('文件上传失败');
};
const onUploadLimit = () => {
  ElMessage.error('已经超出最大上传个数限制');
};
const refreshEditThirdCarCategory = () => {
  // 刷新段落
};
/**
 * 重置过滤值
 */
const resetEditThirdCarCategory = () => {
  refreshEditThirdCarCategory();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetEditThirdCarCategory();
};
/**
 * 保存
 */
const onUpdateClick = () => {
  editThirdCarCategoryRef.value.validate((valid) => {
    if (!valid) return;
    // 级联操作
    if (!props.saveOnSubmit) {
      let retFormData = {
        ...formData.TourCarCategory
      };
    retFormData.modelDictMap = findItemFromList(modelWidgetDropdownList.value, retFormData.model, 'id');
    // retFormData.belongTabDictMap = findItemFromList(belongTabWidgetDropdownList.value, retFormData.belongTab, 'id');
    retFormData.typeDictMap = findItemFromList(typeWidgetDropdownList.value, retFormData.type, 'id');
    retFormData.enableDictMap = findItemFromList(enableWidgetDropdownList.value, retFormData.enable, 'id');
  props.dialog?.submit(retFormData);
      return;
    }
    let params: ANY_OBJECT = {
      tourCarCategoryDto: {
        id: formData.TourCarCategory.id,
        enable: formData.TourCarCategory.enable,
        hotValue: formData.TourCarCategory.hotValue,
        // belongTab: formData.TourCarCategory.belongTab,
        luggageNumber: formData.TourCarCategory.luggageNumber,
        model: formData.TourCarCategory.model,
        title: formData.TourCarCategory.title,
        name: formData.TourCarCategory.name,
        price: formData.TourCarCategory.price,
        unit: formData.TourCarCategory.unit,
        seatNumber: formData.TourCarCategory.seatNumber,
        image: formData.TourCarCategory.image,
        type: StaticDict.TourCarType.THIRD_PARTY_INDIVIDUAL,
        relationDriverId: formData.TourCarCategory.relationDriverId,
        label: formData.TourCarCategory.label,
        createUserId: formData.TourCarCategory.createUserId,
        createTime: formData.TourCarCategory.createTime,
        updateUserId: formData.TourCarCategory.updateUserId,
        updateTime: formData.TourCarCategory.updateTime,
        mark: formData.TourCarCategory.mark,
        deptId: formData.TourCarCategory.deptId,
      }
    };

    let httpCall = isEdit.value ? TourCarCategoryController.update : TourCarCategoryController.add;
    httpCall(params).then(res => {
      ElMessage.success('保存成功');
      props.dialog?.submit();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  });
};
const formInit = () => {
  loadTourCarCategoryData().then(res => {
    modelWidget.onVisibleChange(true).catch(e => {console.error(e)});
    let imageDownloadParams = {
      id: formData.TourCarCategory.id,
      fieldName: 'image',
      asImage: true
    };
    imageWidgetFileList.value = parseUploadData(formData.TourCarCategory.image, imageDownloadParams);
    // belongTabWidget.onVisibleChange(true).catch(e => {console.error(e)});
    typeWidget.onVisibleChange(true).catch(e => {console.error(e)});
    enableWidget.onVisibleChange(true).catch(e => {console.error(e)});
    if (isEdit.value) refreshEditThirdCarCategory();
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};

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