<template>
  <div class="dialog-box" style="position: relative">
    <el-scrollbar class="custom-scroll content-box">
      <el-form
        ref="formEditTourVisaRef"
        :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="TourVisa.img">
              <custom-upload
                v-model="imgWidgetFileList"
                name="uploadFile"
                :size="layoutStore.defaultFormItemSize"
                type="expand"
                :headers="getUploadHeaders"
                :action="getUploadActionUrl('/admin/app/tourVisa/upload')"
                :data="{fieldName: 'img', asImage: true}"
                :limit="imgWidgetMaxCount"
                @change="onImgChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名称" prop="TourVisa.visaTitle">
              <el-input
                class="input-item"
                v-model="formData.TourVisa.visaTitle"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="签证类型" prop="TourVisa.visaTypeId">
              <el-select
                class="input-item"
                v-model="formData.TourVisa.visaTypeId"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="visaTypeIdWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in visaTypeIdWidgetDropdownList"
                  :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="TourVisa.countryCodeId">
              <el-select
                class="input-item"
                v-model="formData.TourVisa.countryCodeId"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="countryCodeIdWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in countryCodeIdWidgetDropdownList"
                  :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="TourVisa.embassyName">
              <el-input
                class="input-item"
                v-model="formData.TourVisa.embassyName"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="使馆地址" prop="TourVisa.embassyAddress">
              <el-input
                class="input-item"
                v-model="formData.TourVisa.embassyAddress"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否面签" prop="TourVisa.interviewFlag">
              <el-select
                class="input-item"
                v-model="formData.TourVisa.interviewFlag"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="interviewFlagWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in interviewFlagWidgetDropdownList"
                  :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="TourVisa.validity">
              <el-input-number
                class="input-item"
                v-model="formData.TourVisa.validity"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="停留天数" prop="TourVisa.idleDays">
              <el-input-number
                class="input-item"
                v-model="formData.TourVisa.idleDays"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计办理天数" prop="TourVisa.processingDays">
              <el-input-number
                class="input-item"
                v-model="formData.TourVisa.processingDays"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计价格" prop="TourVisa.floorPrice">
              <el-input-number
                class="input-item"
                v-model="formData.TourVisa.floorPrice"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="受理范围" prop="TourVisa.acceptanceRange">
              <el-input
                class="input-item"
                v-model="formData.TourVisa.acceptanceRange"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入境次数" prop="TourVisa.entriesNum">
              <el-input-number
                class="input-item"
                v-model="formData.TourVisa.entriesNum"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出签地" prop="TourVisa.issueVisaCode">
              <el-select
                class="input-item"
                v-model="formData.TourVisa.issueVisaCode"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="issueVisaCodeWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in issueVisaCodeWidgetDropdownList"
                  :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="TourVisa.counselorId">
              <el-select
                class="input-item"
                v-model="formData.TourVisa.counselorId"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="counselorIdWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in counselorIdWidgetDropdownList"
                  :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="TourVisa.hotValue">
              <el-select
                class="input-item"
                v-model="formData.TourVisa.hotValue"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="hotValueWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in hotValueWidgetDropdownList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="签证介绍" class="rich-input" prop="TourVisa.dataText">
              <rich-editor
                ref="dataText"
                class="input-item"
                v-model="formData.TourVisa.dataText"
              />
            </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="onSubmitTourVisaClick()">保存</el-button>
    </el-row>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formEditTourVisa',
};
</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 { VisaMetarialsListData } from '@/api/generated/visaMetarialsListController';
import { TourVisaData } from '@/api/generated/tourVisaController';
import { VisaMetarialsListController, TourVisaController } 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 formEditTourVisaRef = ref();
// 表单数据定义
type FormEditTourVisaData = {
  TourVisa: TourVisaData;
};
// 表单数据
const formData = reactive<FormEditTourVisaData>({
  TourVisa: {
    // 签证id
    id: undefined,
    // 图片地址
    img: undefined,
    // 名称
    visaTitle: undefined,
    // 类型id
    visaTypeId: undefined,
    // 国家编码
    countryCodeId: undefined,
    // 使馆名称
    embassyName: undefined,
    // 使馆地址
    embassyAddress: undefined,
    // 是否面签 0 是 1否
    interviewFlag: undefined,
    // 有效期（日）
    validity: undefined,
    // 停留天数
    idleDays: undefined,
    // 预计办理天数
    processingDays: undefined,
    // 预计价格
    floorPrice: undefined,
    // 受理范围
    acceptanceRange: undefined,
    // 入境次数
    entriesNum: undefined,
    // 预定须知
    dataText: undefined,
    // 出签地编码
    issueVisaCode: undefined,
    // 逻辑删除 1正常 -1已删除
    deleteFlag: undefined,
    // 创建人id
    createUserId: undefined,
    // 创建时间
    createTime: undefined,
    // 更新人id
    updateUserId: undefined,
    // 更新时间
    updateTime: undefined,
    // 负责顾问
    counselorId: undefined,
    // 热门数据
    hotValue: undefined,
    // 签证基础资料管理数据
    visaMetarialsListList: [],
  },
},
);
// 表单验证规则
const rules = reactive({
  'TourVisa.floorPrice': [
    {required: true, message: '请输入预计价格', trigger: 'blur'}
  ],
  'TourVisa.countryCodeId': [
    {required: true, message: '请输入签证国家', trigger: 'blur'}
  ],
  'TourVisa.issueVisaCode': [
    {required: true, message: '请输入出签地', trigger: 'blur'}
  ],
  'TourVisa.visaTypeId': [
    {required: true, message: '请输入签证类型', trigger: 'blur'}
  ],
  'TourVisa.dataText': [
    {required: true, message: '请输入签证介绍', trigger: 'blur'}
  ],
  'TourVisa.visaTitle': [
    {required: true, message: '请输入名称', trigger: 'blur'}
  ],
  'TourVisa.img': [
    {required: true, message: '请输入图片', trigger: 'blur'}
  ],
  'TourVisa.acceptanceRange': [
    {required: true, message: '请输入受理范围', trigger: 'blur'}
  ],
  'TourVisa.counselorId': [
    {required: true, message: '请输入负责顾问', trigger: 'blur'},
  ],
  'TourVisa.validity': [
    {required: true, message: '请输入有效期（日）', trigger: 'blur'}
  ],
  'TourVisa.embassyAddress': [
    {required: true, message: '请输入使馆地址', trigger: 'blur'}
  ],
  'TourVisa.embassyName': [
    {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 loadTourVisaData = () => {
  return new Promise<void>((resolve, reject) => {
    if (!isEdit.value) {
      resolve();
      return;
    }
    if (!props.saveOnSubmit && props.rowData != null) {
      formData.TourVisa = JSON.parse(JSON.stringify(props.rowData));
      resolve();
      return;
    }
    let params: ANY_OBJECT = {
      id: props.id
    };
    TourVisaController.view(params).then(res => {
      formData.TourVisa = { ...res.data };
      resolve();
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 图片上传文件改变
 */
const onImgChange = val => {
  formData.TourVisa.img = fileListToJson(val);
};
// 图片上传文件组件
const imgWidget = useUploadWidget(1);
const { fileList: imgWidgetFileList, maxCount: imgWidgetMaxCount } = imgWidget;
/**
 * 签证类型下拉数据获取函数
 */
const loadVisaTypeIdDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictTourVisaType(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 签证类型配置参数
const visaTypeIdOptions: DropdownOptions<DictData> = {
  loadData: loadVisaTypeIdDropdownList,
  isTree: false,
};
// 签证类型下拉组件
const visaTypeIdWidget = useDropdown(visaTypeIdOptions);
const { dropdownList: visaTypeIdWidgetDropdownList } = visaTypeIdWidget
/**
 * 签证国家下拉数据获取函数
 */
const loadCountryCodeIdDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictTourCountryCode(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 签证国家配置参数
const countryCodeIdOptions: DropdownOptions<DictData> = {
  loadData: loadCountryCodeIdDropdownList,
  isTree: false,
};
// 签证国家下拉组件
const countryCodeIdWidget = useDropdown(countryCodeIdOptions);
const { dropdownList: countryCodeIdWidgetDropdownList } = countryCodeIdWidget
/**
 * 是否面签下拉数据获取函数
 */
const loadInterviewFlagDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.InterviewFlag.getList(),
  });
};
// 是否面签配置参数
const interviewFlagOptions: DropdownOptions<DictData> = {
  loadData: loadInterviewFlagDropdownList,
  isTree: false,
};
// 是否面签下拉组件
const interviewFlagWidget = useDropdown(interviewFlagOptions);
const { dropdownList: interviewFlagWidgetDropdownList } = interviewFlagWidget
/**
 * 出签地下拉数据获取函数
 */
const loadIssueVisaCodeDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictChinaAreaByParentId(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 出签地配置参数
const issueVisaCodeOptions: DropdownOptions<DictData> = {
  loadData: loadIssueVisaCodeDropdownList,
  isTree: false,
};
// 出签地下拉组件
const issueVisaCodeWidget = useDropdown(issueVisaCodeOptions);
const { dropdownList: issueVisaCodeWidgetDropdownList } = issueVisaCodeWidget
/**
 * 负责顾问下拉数据获取函数
 */
const loadCounselorIdDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictTourVisaCounselor(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 负责顾问配置参数
const counselorIdOptions: DropdownOptions<DictData> = {
  loadData: loadCounselorIdDropdownList,
  isTree: false,
};
// 负责顾问下拉组件
const counselorIdWidget = useDropdown(counselorIdOptions);
const { dropdownList: counselorIdWidgetDropdownList } = counselorIdWidget
/**
 * 热门数据下拉数据获取函数
 */
const loadHotValueDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.Hotspot.getList(),
  });
};
// 热门数据配置参数
const hotValueOptions: DropdownOptions<DictData> = {
  loadData: loadHotValueDropdownList,
  isTree: false,
};
// 热门数据下拉组件
const hotValueWidget = useDropdown(hotValueOptions);
const { dropdownList: hotValueWidgetDropdownList } = hotValueWidget
const dataText = ref();
const onUploadError = () => {
  ElMessage.error('文件上传失败');
};
const onUploadLimit = () => {
  ElMessage.error('已经超出最大上传个数限制');
};
const refreshFormEditTourVisa = () => {
  // 刷新段落
};
/**
 * 重置过滤值
 */
const resetFormEditTourVisa = () => {
  refreshFormEditTourVisa();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormEditTourVisa();
};
/**
 * 保存
 */
const onSubmitTourVisaClick = () => {
  // 更新富文本字段值
  formData.TourVisa.dataText = dataText.value?.getHtml();
  formEditTourVisaRef.value.validate((valid) => {
    if (!valid) return;
    // 级联操作
    if (!props.saveOnSubmit) {
      let retFormData = {
        ...formData.TourVisa
      };
    retFormData.visaTypeIdDictMap = findItemFromList(visaTypeIdWidgetDropdownList.value, retFormData.visaTypeId, 'id');
    retFormData.countryCodeIdDictMap = findItemFromList(countryCodeIdWidgetDropdownList.value, retFormData.countryCodeId, 'id');
    retFormData.interviewFlagDictMap = findItemFromList(interviewFlagWidgetDropdownList.value, retFormData.interviewFlag, 'id');
    retFormData.issueVisaCodeDictMap = findItemFromList(issueVisaCodeWidgetDropdownList.value, retFormData.issueVisaCode, 'id');
    retFormData.counselorIdDictMap = findItemFromList(counselorIdWidgetDropdownList.value, retFormData.counselorId, 'id');
    retFormData.hotValueDictMap = findItemFromList(hotValueWidgetDropdownList.value, retFormData.hotValue, 'id');
  props.dialog?.submit(retFormData);
      return;
    }
    let params: ANY_OBJECT = {
      tourVisaDto: {
        id: formData.TourVisa.id,
        counselorId: formData.TourVisa.counselorId,
        hotValue: formData.TourVisa.hotValue,
        img: formData.TourVisa.img,
        visaTitle: formData.TourVisa.visaTitle,
        visaTypeId: formData.TourVisa.visaTypeId,
        countryCodeId: formData.TourVisa.countryCodeId,
        embassyName: formData.TourVisa.embassyName,
        embassyAddress: formData.TourVisa.embassyAddress,
        interviewFlag: formData.TourVisa.interviewFlag,
        validity: formData.TourVisa.validity,
        idleDays: formData.TourVisa.idleDays,
        processingDays: formData.TourVisa.processingDays,
        floorPrice: formData.TourVisa.floorPrice,
        acceptanceRange: formData.TourVisa.acceptanceRange,
        entriesNum: formData.TourVisa.entriesNum,
        dataText: formData.TourVisa.dataText,
        issueVisaCode: formData.TourVisa.issueVisaCode,
        createUserId: formData.TourVisa.createUserId,
        createTime: formData.TourVisa.createTime,
        updateUserId: formData.TourVisa.updateUserId,
        updateTime: formData.TourVisa.updateTime,
      }
    };

    let httpCall = isEdit.value ? TourVisaController.update : TourVisaController.add;
    httpCall(params).then(res => {
      ElMessage.success('保存成功');
      props.dialog?.submit();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  });
};
const formInit = () => {
  loadTourVisaData().then(res => {
    let imgDownloadParams = {
      id: formData.TourVisa.id,
      fieldName: 'img',
      asImage: true
    };
    imgWidgetFileList.value = parseUploadData(formData.TourVisa.img, imgDownloadParams);
    visaTypeIdWidget.onVisibleChange(true).catch(e => {console.error(e)});
    countryCodeIdWidget.onVisibleChange(true).catch(e => {console.error(e)});
    interviewFlagWidget.onVisibleChange(true).catch(e => {console.error(e)});
    issueVisaCodeWidget.onVisibleChange(true).catch(e => {console.error(e)});
    counselorIdWidget.onVisibleChange(true).catch(e => {console.error(e)});
    hotValueWidget.onVisibleChange(true).catch(e => {console.error(e)});
    if (isEdit.value) refreshFormEditTourVisa();
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};

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