<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
            <el-form-item label="流程编号" prop="applyCode">
              <el-input v-model="queryParams.applyCode" placeholder="请输入流程编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="乘机人姓名" prop="passengerName">
              <!-- <el-input v-model="queryParams.passengerName" placeholder="请输入乘机人姓名" clearable @keyup.enter="handleQuery" /> -->
              <el-select v-model="queryParams.passengerName" placeholder="请选择乘机人" filterable>
                <el-option v-for="item in userInfoList" :key="item.userId" :label="item.nickName" :value="item.nickName" />
              </el-select>
            </el-form-item>
            <el-form-item label="出行日期" prop="travelDate">
              <el-date-picker clearable v-model="queryParams.travelDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择出行日期" />
            </el-form-item>
            <el-form-item label="出发地点" prop="departureLocation">
              <el-input v-model="queryParams.departureLocation" placeholder="请输入出发地点" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="到达地点" prop="arrivalLocation">
              <el-input v-model="queryParams.arrivalLocation" placeholder="请输入到达地点" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="机票折扣" prop="flightDiscount">
              <el-input v-model="queryParams.flightDiscount" placeholder="请输入机票折扣" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
            <el-form-item label="机票折扣" prop="flightDiscount">
              <el-select v-model="queryParams.flightDiscount" placeholder="请选择机票折扣" clearable>
                <el-option v-for="dict in flight_discount" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="机票金额" prop="flightAmount">
              <el-input v-model="queryParams.flightAmount" placeholder="请输入机票金额" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['oa/crm:flightBooking:add']">新增</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['oa/crm:flightBooking:edit']"
              >修改</el-button
            >
          </el-col> -->
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['oa/crm:flightBooking:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oa/crm:flightBooking:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" :search="true" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="flightBookingList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="机票预订ID" align="center" prop="bookingId" width="120" v-if="columns[0].visible" />
        <el-table-column label="流程编号" align="center" prop="applyCode" width="160" v-if="columns[2].visible" />
        <el-table-column label="乘机人ID" align="center" prop="passengerId" v-if="columns[3].visible" />
        <el-table-column label="乘机人姓名" align="center" prop="passengerName" width="120" v-if="columns[4].visible" />
        <el-table-column label="出行日期" align="center" prop="travelDate" width="120" v-if="columns[5].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.travelDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="出发地点" align="center" prop="departureLocation" v-if="columns[6].visible" />
        <el-table-column label="到达地点" align="center" prop="arrivalLocation" v-if="columns[7].visible" />
        <el-table-column label="机票折扣" align="center" prop="flightDiscount" v-if="columns[8].visible">
          <template #default="scope">
            <dict-tag :options="flight_discount" :value="scope.row.flightDiscount" />
          </template>
        </el-table-column>
        <el-table-column label="机票金额" align="center" prop="flightAmount" v-if="columns[9].visible" />
        <el-table-column label="附件ID" align="center" prop="ossId" width="100" v-if="columns[10].visible">
          <template #default="scope">
            <el-button v-if="scope.row.ossId" link type="primary" icon="Download" @click="downloadOss(scope.row.ossId)">下载 </el-button>
            <span v-else style="color: #999">未上传</span>
          </template>
        </el-table-column>
        <el-table-column label="申请状态" align="center" prop="bookingStatus" v-if="columns[11].visible">
          <template #default="scope">
            <dict-tag :options="booking_status" :value="scope.row.bookingStatus" />
          </template>
        </el-table-column>
        <el-table-column label="流程状态" align="center" prop="flowStatus" v-if="columns[12].visible" />
        <el-table-column label="备注" align="center" prop="remark" v-if="columns[13].visible" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="100" v-if="columns[17].visible" />
        <el-table-column label="更新时间" align="center" prop="updateTime" width="100" v-if="columns[19].visible" />
        <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top" v-if="scope.row.flowStatus === 'draft' || scope.row.flowStatus === 'back'">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['oa/crm:flightBooking:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="查看详情" placement="top" v-if="scope.row.flowStatus !== 'draft'">
              <el-button link type="info" icon="DocumentChecked" @click="handleView(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改机票预订对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="flightBookingFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="流程编号" prop="applyCode">
          <el-input v-model="form.applyCode" placeholder="请输入流程编号" />
        </el-form-item>
        <el-form-item label="乘机人ID" prop="passengerId">
          <el-input v-model="form.passengerId" placeholder="请输入乘机人ID" />
        </el-form-item>
        <el-form-item label="乘机人姓名" prop="passengerName">
          <el-input v-model="form.passengerName" placeholder="请输入乘机人姓名" />
        </el-form-item>
        <el-form-item label="出行日期" prop="travelDate">
          <el-date-picker clearable v-model="form.travelDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择出行日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="出发地点" prop="departureLocation">
          <el-input v-model="form.departureLocation" placeholder="请输入出发地点" />
        </el-form-item>
        <el-form-item label="到达地点" prop="arrivalLocation">
          <el-input v-model="form.arrivalLocation" placeholder="请输入到达地点" />
        </el-form-item>
        <!-- <el-form-item label="机票折扣" prop="flightDiscount">
          <el-input v-model="form.flightDiscount" placeholder="请输入机票折扣" />
        </el-form-item> -->
        <el-form-item label="机票折扣" prop="flightDiscount">
          <el-select v-model="form.flightDiscount" placeholder="请选择机票折扣">
            <el-option v-for="dict in flight_discount" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="机票金额" prop="flightAmount">
          <el-input v-model="form.flightAmount" placeholder="请输入机票金额" />
        </el-form-item>
        <el-form-item label="附件" prop="ossId">
          <!-- 使用封装的FileUpload组件替换原有的文本域输入 -->
          <FileUpload
            v-model="ossIdString"
            :limit="5"
            :fileSize="20"
            :fileType="['jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx', 'xls', 'xlsx']"
            :isShowTip="true"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="FlightBooking" lang="ts">
import { listFlightBooking, getFlightBooking, delFlightBooking, addFlightBooking, updateFlightBooking } from '@/api/oa/crm/flightBooking';
import { FlightBookingVO, FlightBookingQuery, FlightBookingForm } from '@/api/oa/crm/flightBooking/types';
import FileUpload from '@/components/FileUpload/index.vue';
import { getUserList } from '@/api/system/user';
import download from '@/plugins/download';
import ApprovalRecord from '@/components/Process/approvalRecord.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const route = useRoute();
const router = useRouter();
const { flight_discount, booking_status } = toRefs<any>(proxy?.useDict('flight_discount', 'booking_status'));

const flightBookingList = ref<FlightBookingVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const flightBookingFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `机票预订ID`, visible: false },
  { key: 1, label: `租户编号`, visible: true },
  { key: 2, label: `流程编号`, visible: true },
  { key: 3, label: `乘机人ID`, visible: false },
  { key: 4, label: `乘机人姓名`, visible: true },
  { key: 5, label: `出行日期`, visible: true },
  { key: 6, label: `出发地点`, visible: true },
  { key: 7, label: `到达地点`, visible: true },
  { key: 8, label: `机票折扣`, visible: true },
  { key: 9, label: `机票金额`, visible: true },
  { key: 10, label: `附件ID`, visible: false },
  { key: 11, label: `申请状态`, visible: true },
  { key: 12, label: `流程状态`, visible: false },
  { key: 13, label: `备注`, visible: true },
  { key: 14, label: `删除标志`, visible: false },
  { key: 15, label: `创建部门`, visible: false },
  { key: 16, label: `创建者`, visible: false },
  { key: 17, label: `创建时间`, visible: false },
  { key: 18, label: `更新者`, visible: false },
  { key: 19, label: `更新时间`, visible: false }
]);

const initFormData: FlightBookingForm = {
  bookingId: undefined,
  applyCode: undefined,
  passengerId: undefined,
  passengerName: undefined,
  travelDate: undefined,
  departureLocation: undefined,
  arrivalLocation: undefined,
  flightDiscount: undefined,
  flightAmount: undefined,
  ossId: undefined,
  bookingStatus: undefined,
  flowStatus: undefined,
  remark: undefined
};
const data = reactive<PageData<FlightBookingForm, FlightBookingQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    applyCode: undefined,
    passengerId: undefined,
    passengerName: undefined,
    travelDate: undefined,
    departureLocation: undefined,
    arrivalLocation: undefined,
    flightDiscount: undefined,
    flightAmount: undefined,
    ossId: undefined,
    bookingStatus: undefined,
    flowStatus: undefined,
    params: {}
  },
  rules: {
    bookingId: [{ required: true, message: '机票预订ID不能为空', trigger: 'blur' }],
    passengerId: [{ required: true, message: '乘机人ID不能为空', trigger: 'blur' }],
    travelDate: [{ required: true, message: '出行日期不能为空', trigger: 'blur' }],
    departureLocation: [{ required: true, message: '出发地点不能为空', trigger: 'blur' }],
    arrivalLocation: [{ required: true, message: '到达地点不能为空', trigger: 'blur' }],
    flightDiscount: [{ required: true, message: '机票折扣不能为空', trigger: 'blur' }],
    flightAmount: [{ required: true, message: '机票金额不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

// 附件ID字符串转换（用于FileUpload组件双向绑定）
const ossIdString = computed({
  get() {
    const v = form.value.ossId as any;
    return v === undefined || v === null ? '' : String(v);
  },
  set(val: string) {
    form.value.ossId = val || (undefined as any);
  }
});
// 下载附件
const downloadOss = (ossId: string | number) => {
  download.oss(ossId);
};
/** 查询用户信息下拉框结构 */
const userInfoList = ref([]);
const getUserInfoListSelect = async () => {
  const res = await getUserList({ pageNum: 1, pageSize: 1000 });
  userInfoList.value = res.data;
};
/** 查询机票预订列表 */
const getList = async () => {
  loading.value = true;
  const res = await listFlightBooking(queryParams.value);
  flightBookingList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  flightBookingFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: FlightBookingVO[]) => {
  ids.value = selection.map((item) => item.bookingId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  proxy.$tab.closePage(route);
  router.push({
    path: '/flight/flightBooking/edit',
    query: {
      type: 'add'
    }
  });
};
/** 查看按钮操作 */
const handleView = (row?: FlightBookingVO) => {
  const _bookingId = row?.bookingId || ids.value[0];
  proxy.$tab.closePage(route);
  router.push({
    path: '/flight/flightBooking/edit',
    query: {
      id: _bookingId,
      type: 'view'
    }
  });
};

/** 修改按钮操作 */
const handleUpdate = async (row?: FlightBookingVO) => {
  const _bookingId = row?.bookingId || ids.value[0];
  proxy.$tab.closePage(route);
  router.push({
    path: '/flight/flightBooking/edit',
    query: {
      id: _bookingId,
      type: 'update'
    }
  });
};
const approvalRecordRef = ref<InstanceType<typeof ApprovalRecord>>();
// 审批记录
const handleApprovalRecord = (row?: FlightBookingVO) => {
  if (row) {
    approvalRecordRef.value.init(row?.bookingId);
  }
};

/** 提交按钮 */
const submitForm = () => {
  flightBookingFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.bookingId) {
        await updateFlightBooking(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addFlightBooking(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: FlightBookingVO) => {
  const _bookingIds = row?.bookingId || ids.value;
  await proxy?.$modal.confirm('是否确认删除流程编号为"' + _bookingIds + '"的数据项？').finally(() => (loading.value = false));
  await delFlightBooking(_bookingIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'oa/crm/flightBooking/export',
    {
      ...queryParams.value
    },
    `flightBooking_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
  getUserInfoListSelect();
});
</script>
