<template>
  <div class="dialog-box" style="position: relative">
    <el-scrollbar class="custom-scroll content-box">
      <el-form
        ref="formEditTourVisaOrderRef"
        :model="formData"
        :size="layoutStore.defaultFormItemSize"
        :rules="rulesPage"
        label-width="120px"
        label-position="right"
        @submit.prevent
      >
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="文件列表" prop="TourVisaOrder.file">
              <custom-upload
                v-model="fileWidgetFileList"
                name="uploadFile"
                :size="layoutStore.defaultFormItemSize"
                type="dropdown"
                :headers="getUploadHeaders"
                :action="getUploadActionUrl('/admin/app/tourVisaOrder/upload')"
                :data="{fieldName: 'file', asImage: false}"
                :limit="fileWidgetMaxCount"
                @change="onFileChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下单人姓名" prop="TourVisaOrder.orderName">
              <el-input
                class="input-item"
                v-model="formData.TourVisaOrder.orderName"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下单人电话" prop="TourVisaOrder.orderPhone">
              <el-input
                class="input-item"
                v-model="formData.TourVisaOrder.orderPhone"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下单身份证" prop="TourVisaOrder.orderIdCard">
              <el-input
                class="input-item"
                v-model="formData.TourVisaOrder.orderIdCard"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="签证商品" prop="TourVisaOrder.visaId">
              <el-select
                class="input-item"
                v-model="formData.TourVisaOrder.visaId"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="visaIdWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in visaIdWidgetDropdownList"
                  :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="TourVisaOrder.orderPrice">
              <el-input
                class="input-item"
                v-model="formData.TourVisaOrder.orderPrice"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责顾问" prop="TourVisaOrder.counselorId">
              <el-select
                class="input-item"
                v-model="formData.TourVisaOrder.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="TourVisaOrder.orderAddress">
              <el-input
                class="input-item"
                v-model="formData.TourVisaOrder.orderAddress"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务费" prop="TourVisaOrder.servicePrice">
              <el-input
                class="input-item"
                v-model="formData.TourVisaOrder.servicePrice"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="税费" prop="TourVisaOrder.price">
              <el-input
                class="input-item"
                v-model="formData.TourVisaOrder.price"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单状态" prop="TourVisaOrder.state">
              <el-select
                class="input-item"
                v-model="formData.TourVisaOrder.state"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="stateWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in stateWidgetDropdownList"
                  :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="TourVisaOrder.payState">
              <el-select
                class="input-item"
                v-model="formData.TourVisaOrder.payState"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="payStateWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in payStateWidgetDropdownList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </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="onSubmitTourVisaOrderClick()">保存</el-button>
    </el-row>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formEditTourVisaOrder',
};
</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 { TourVisaOrderData } from '@/api/generated/tourVisaOrderController';
import { TourVisaOrderController } from '@/api/generated';
import {pattern} from "@/common/utils/validate";

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 formEditTourVisaOrderRef = ref();
// 表单数据定义
type FormEditTourVisaOrderData = {
  TourVisaOrder: TourVisaOrderData;
};
// 表单数据
const formData = reactive<FormEditTourVisaOrderData>({
  TourVisaOrder: {
    // 签证类型id
    id: undefined,
    // 文件列表json
    file: undefined,
    // 下单人姓名
    orderName: undefined,
    // 下单人电话
    orderPhone: undefined,
    // 下单身份证
    orderIdCard: undefined,
    // 签证商品id
    visaId: undefined,
    // 订单状态 0待审核
    state: undefined,
    // 支付状态 0未支付 1已支付
    payState: undefined,
    // 逻辑删除 1正常 -1已删除
    deleteFlag: undefined,
    // 创建人id
    createUserId: undefined,
    // 创建时间
    createTime: undefined,
    // 更新人id
    updateUserId: undefined,
    // 更新时间
    updateTime: undefined,
    // 订单价格
    orderPrice: undefined,
    // 负责顾问
    counselorId: undefined,
    // 订单地址
    orderAddress: undefined,
    // 服务费
    servicePrice: undefined,
    // 税费
    price: undefined,
  },
},
);
// 表单验证规则
const rulesPage = reactive({
  'TourVisaOrder.state': [
    {required: true, message: '请输入订单状态', trigger: 'blur'},
  ],
  'TourVisaOrder.payState': [
    {required: true, message: '请输入支付状态', trigger: 'blur'}
  ],
  'TourVisaOrder.orderIdCard': [
    {required: true, message: '请输入下单身份证', trigger: 'blur'},
    {type: 'string', pattern: pattern.englishAndNumber, message: '下单身份证只允许输入数字和英文字符', trigger: 'blur'},
  ],
  'TourVisaOrder.visaId': [
    {required: true, message: '请输入签证商品', trigger: 'blur'},
  ],
  'TourVisaOrder.orderPrice': [
    {required: true, message: '请输入订单价格', trigger: 'blur'},
    {type: 'number', message: '订单价格只允许输入数字', trigger: 'blur', transform: (value) => Number(value)}
  ],
  'TourVisaOrder.servicePrice': [
    {required: true, message: '请输入服务费', trigger: 'blur'},
    {type: 'string', pattern: pattern.NumberCheck, message: '请输入正确的服务费', trigger: 'blur'},
  ],
  'TourVisaOrder.counselorId': [
    {required: true, message: '请输入负责顾问', trigger: 'blur'},
  ],
  'TourVisaOrder.orderName': [
    {required: true, message: '请输入下单人姓名', trigger: 'blur'},
  ],
  'TourVisaOrder.price': [
    {required: true, message: '请输入税费', trigger: 'blur'},
    {type: 'string', pattern: pattern.NumberCheck, message: '请输入正确的税费', trigger: 'blur'},
  ],
  'TourVisaOrder.orderPhone': [
    {required: true, message: '请输入下单人电话', trigger: 'blur'},
    {type: 'string', pattern: pattern.mobie, message: '请输入正确的手机号码', trigger: 'blur'},
  ],
  'TourVisaOrder.orderAddress': [
    {required: true, message: '请输入订单地址', trigger: 'blur'}
  ],
  'TourVisaOrder.file': [
    {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 loadTourVisaOrderData = () => {
  return new Promise<void>((resolve, reject) => {
    if (!isEdit.value) {
      resolve();
      return;
    }
    if (!props.saveOnSubmit && props.rowData != null) {
      formData.TourVisaOrder = JSON.parse(JSON.stringify(props.rowData));
      resolve();
      return;
    }
    let params: ANY_OBJECT = {
      id: props.id
    };
    TourVisaOrderController.view(params).then(res => {
      formData.TourVisaOrder = { ...res.data };
      resolve();
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 文件列表上传文件改变
 */
const onFileChange = val => {
  formData.TourVisaOrder.file = fileListToJson(val);
};
// 文件列表上传文件组件
const fileWidget = useUploadWidget(999);
const { fileList: fileWidgetFileList, maxCount: fileWidgetMaxCount } = fileWidget;
/**
 * 签证商品下拉数据获取函数
 */
const loadVisaIdDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictTourVisa(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 签证商品配置参数
const visaIdOptions: DropdownOptions<DictData> = {
  loadData: loadVisaIdDropdownList,
  isTree: false,
};
// 签证商品下拉组件
const visaIdWidget = useDropdown(visaIdOptions);
const { dropdownList: visaIdWidgetDropdownList } = visaIdWidget
/**
 * 负责顾问下拉数据获取函数
 */
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 loadStateDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.VisaOrderState.getList(),
  });
};
// 订单状态配置参数
const stateOptions: DropdownOptions<DictData> = {
  loadData: loadStateDropdownList,
  isTree: false,
};
// 订单状态下拉组件
const stateWidget = useDropdown(stateOptions);
const { dropdownList: stateWidgetDropdownList } = stateWidget
/**
 * 支付状态下拉数据获取函数
 */
const loadPayStateDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.VisaPayState.getList(),
  });
};
// 支付状态配置参数
const payStateOptions: DropdownOptions<DictData> = {
  loadData: loadPayStateDropdownList,
  isTree: false,
};
// 支付状态下拉组件
const payStateWidget = useDropdown(payStateOptions);
const { dropdownList: payStateWidgetDropdownList } = payStateWidget
const onUploadError = () => {
  ElMessage.error('文件上传失败');
};
const onUploadLimit = () => {
  ElMessage.error('已经超出最大上传个数限制');
};
const refreshFormEditTourVisaOrder = () => {
  // 刷新段落
};
/**
 * 重置过滤值
 */
const resetFormEditTourVisaOrder = () => {
  refreshFormEditTourVisaOrder();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormEditTourVisaOrder();
};
/**
 * 保存
 */
const onSubmitTourVisaOrderClick = () => {
  formEditTourVisaOrderRef.value.validate((valid) => {
    if (!valid) return;
    // 级联操作
    if (!props.saveOnSubmit) {
      let retFormData = {
        ...formData.TourVisaOrder
      };
    retFormData.visaIdDictMap = findItemFromList(visaIdWidgetDropdownList.value, retFormData.visaId, 'id');
    retFormData.counselorIdDictMap = findItemFromList(counselorIdWidgetDropdownList.value, retFormData.counselorId, 'id');
    retFormData.stateDictMap = findItemFromList(stateWidgetDropdownList.value, retFormData.state, 'id');
    retFormData.payStateDictMap = findItemFromList(payStateWidgetDropdownList.value, retFormData.payState, 'id');
  props.dialog?.submit(retFormData);
      return;
    }
    let params: ANY_OBJECT = {
      tourVisaOrderDto: {
        id: formData.TourVisaOrder.id,
        orderPrice: formData.TourVisaOrder.orderPrice,
        counselorId: formData.TourVisaOrder.counselorId,
        orderAddress: formData.TourVisaOrder.orderAddress,
        servicePrice: formData.TourVisaOrder.servicePrice,
        price: formData.TourVisaOrder.price,
        file: formData.TourVisaOrder.file,
        orderName: formData.TourVisaOrder.orderName,
        orderPhone: formData.TourVisaOrder.orderPhone,
        orderIdCard: formData.TourVisaOrder.orderIdCard,
        visaId: formData.TourVisaOrder.visaId,
        state: formData.TourVisaOrder.state,
        payState: formData.TourVisaOrder.payState,
        createUserId: formData.TourVisaOrder.createUserId,
        createTime: formData.TourVisaOrder.createTime,
        updateUserId: formData.TourVisaOrder.updateUserId,
        updateTime: formData.TourVisaOrder.updateTime,
      }
    };

    let httpCall = isEdit.value ? TourVisaOrderController.update : TourVisaOrderController.add;
    httpCall(params).then(res => {
      ElMessage.success('保存成功');
      props.dialog?.submit();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  });
};
const formInit = () => {
  loadTourVisaOrderData().then(res => {
    let fileDownloadParams = {
      id: formData.TourVisaOrder.id,
      fieldName: 'file',
      asImage: false
    };
    fileWidgetFileList.value = parseUploadData(formData.TourVisaOrder.file, fileDownloadParams);
    visaIdWidget.onVisibleChange(true).catch(e => {console.error(e)});
    counselorIdWidget.onVisibleChange(true).catch(e => {console.error(e)});
    stateWidget.onVisibleChange(true).catch(e => {console.error(e)});
    payStateWidget.onVisibleChange(true).catch(e => {console.error(e)});
    if (isEdit.value) refreshFormEditTourVisaOrder();
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};

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