<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from 'vue';
import { useRoute } from 'vue-router';

import { Page } from '@vben/common-ui';
import { useUserStore } from '@vben/stores';

import { UploadFilled } from '@element-plus/icons-vue';
import {
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElSelect,
  ElSwitch,
  ElTreeSelect,
  ElUpload,
} from 'element-plus';

import { requestClient } from '#/api/request';
import { selectAllSysStation } from '#/api/system/infoEntry/stationInfo/stationInfo';
import { categoryTree } from '#/api/workflow/category/index';
import { getWorkOrderDetail } from '#/api/workflow/instance/index';
import { getSingleImageUploadConfig } from '#/components/upload/config';

// 接收props参数
const props = defineProps<{
  id?: string;
}>();

// 定义emit事件
const emit = defineEmits<{
  close: [];
}>();

// 路由相关
const route = useRoute();
const userStore = useUserStore();
// 表单数据
const formData = reactive({
  ticketType: '',
  stationId: '',
  contact: '',
  phone: '',
  content: '',
  attachments: '',
  isSubmit: false,
  urgency: '1',
});

// 表单规则
const formRules = reactive({
  ticketType: [
    { required: true, message: '请选择工单类型', trigger: 'change' },
  ],
  stationId: [{ required: true, message: '请选择场站', trigger: 'change' }],
  contact: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur',
    },
  ],
  content: [{ required: true, message: '请输入提报内容', trigger: 'blur' }],
});

// 工单类型选项
const ticketTypeOptions = ref<any[]>([]);
// 场站选项
const stationOptions = ref<any[]>([]);
// 上传文件列表
const fileList = ref([]);

// 表单引用
const formRef = ref();

// 获取工单类型
const getTicketTypes = async () => {
  try {
    const res = await categoryTree();
    ticketTypeOptions.value = res || [];
  } catch (error) {
    ElMessage.error('获取工单类型失败');
    console.error('获取工单类型失败:', error);
  }
};

// 获取场站列表
const getStations = async () => {
  try {
    const res = await selectAllSysStation();
    stationOptions.value = res || [];
  } catch (error) {
    ElMessage.error('获取场站列表失败');
    console.error('获取场站列表失败:', error);
  }
};

// 上传成功回调
const handleUploadSuccess = (response, file, fileList) => {
  if (response.code === 200) {
    // 将文件路径添加到attachments字段
    console.log(response, file, fileList);
    const paths = fileList.map((f) => f.response.data.fileName).join(',');
    formData.attachments = paths;
  } else {
    ElMessage.error('文件上传失败');
  }
};

// 上传失败回调
const handleUploadError = (error) => {
  ElMessage.error('文件上传失败');
  console.error('文件上传失败:', error);
};

// 移除文件回调
const handleRemove = (file, fileList) => {
  // 更新attachments字段（文件名）
  const fileNames = fileList.map((f) => f.response.data.fileName).join(',');
  formData.attachments = fileNames;
};

// 获取工单详情
const getOrderDetail = async (orderId?: string) => {
  const id = orderId || props.id || route.query.id;
  if (!id) return;

  try {
    const detail = await getWorkOrderDetail(id as string);
    console.log('工单详情:', detail);
    // 填充表单数据
    formData.ticketType = Number(detail.ticketType) || '';
    formData.stationId = Number(detail.stationId) || '';
    formData.contact = detail.contact || '';
    formData.phone = detail.phone || '';
    formData.content = detail.content || '';
    formData.attachments = detail.attachments || '';
    formData.isSubmit = detail.isSubmit || false;
    formData.urgency = detail.urgency.toString() || '1';

    // 处理附件文件列表
    if (detail.attachmentsUrl && Array.isArray(detail.attachmentsUrl)) {
      const fileNames = formData.attachments
        ? formData.attachments.split(',')
        : [];
      fileList.value = detail.attachmentsUrl.map((url, index) => ({
        name: fileNames[index] || `file-${index}`,
        url,
        response: {
          data: { url, fileName: fileNames[index] || `file-${index}` },
        },
      }));
    }
  } catch (error) {
    ElMessage.error('获取工单详情失败');
    console.error('获取工单详情失败:', error);
  }
};

// 监听props.id变化，获取工单详情
watch(
  () => props.id,
  (newId) => {
    if (newId) {
      getOrderDetail(newId);
    }
  },
  { immediate: true },
);

// 表单提交
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    console.log(formData);
    const id = props.id || route.query.id;

    if (id) {
      // 更新工单
      await requestClient.put(`/workOrder/order/${id}`, formData);
      ElMessage.success('工单更新成功');

      // 如果是在drawer中打开的，需要关闭drawer
      if (props.id) {
        // 触发close事件通知drawer关闭
        emit('close');
      }
    } else {
      // 创建工单
      await requestClient.post('/workOrder/order', formData);
      ElMessage.success('工单创建成功');

      // 重置表单
      formRef.value.resetFields();
      fileList.value = [];
      formData.attachments = '';
    }
  } catch (error) {
    if (error.name === 'ValidationError') {
      // 表单验证失败，Element Plus会自动提示错误信息
      return;
    }

    ElMessage.error(id ? '工单更新失败' : '工单创建失败');
    console.error('工单操作失败:', error);
  }
};

// 初始化数据
const initData = () => {
  getTicketTypes();
  getStations();
  // 只有在非drawer模式下（没有props.id）才调用getOrderDetail
  // drawer模式下由watch监听props.id变化来获取数据
  if (!props.id) {
    getOrderDetail();
  }

  formData.phone = userStore.userInfo?.phoneNumber || '';
  formData.stationId = userStore.userInfo?.stations[0]?.id || '';
  formData.contact = userStore.userInfo?.realName || '';
};

// 页面加载时初始化数据
onMounted(() => {
  initData();
});

// 暴露方法给父组件
defineExpose({
  handleSubmit,
});
</script>

<template>
  <Page>
    <div class="wrap">
      <ElForm
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        class="create-order-form"
      >
        <!-- 工单类型 -->
        <ElFormItem label="工单类型" prop="ticketType">
          <ElTreeSelect
            v-model="formData.ticketType"
            :data="ticketTypeOptions"
            check-strictly
            placeholder="请选择工单类型"
            style="width: 100%"
            :props="{ label: 'label', value: 'id', children: 'children' }"
            filterable
          />
        </ElFormItem>

        <!-- 场站 -->
        <ElFormItem label="场站" prop="stationId">
          <ElSelect
            v-model="formData.stationId"
            placeholder="请选择场站"
            style="width: 100%"
          >
            <ElOption
              v-for="option in stationOptions"
              :key="option.id"
              :label="option.stationName"
              :value="option.id"
            />
          </ElSelect>
        </ElFormItem>

        <!-- 联系人 -->
        <ElFormItem label="联系人" prop="contact">
          <ElInput v-model="formData.contact" placeholder="请输入联系人" />
        </ElFormItem>

        <!-- 联系电话 -->
        <ElFormItem label="联系电话" prop="phone">
          <ElInput v-model="formData.phone" placeholder="请输入联系电话" />
        </ElFormItem>

        <!-- 紧急程度 -->
        <ElFormItem label="紧急程度" prop="urgency">
          <ElSelect v-model="formData.urgency" placeholder="请选择紧急程度" style="width: 100%;">
            <ElOption label="一般" value="1" />
            <ElOption label="紧急" value="2" />
          </ElSelect>
        </ElFormItem>

        <!-- 提报内容 -->
        <ElFormItem label="提报内容" prop="content">
          <ElInput
            v-model="formData.content"
            type="textarea"
            :rows="4"
            placeholder="请输入提报内容"
          />
        </ElFormItem>

        <!-- 提报附件 -->
        <ElFormItem label="提报附件">
          <ElUpload
            :file-list="fileList"
            :action="getSingleImageUploadConfig().action"
            :headers="getSingleImageUploadConfig().headers"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :on-remove="handleRemove"
            list-type="picture-card"
            multiple
            :limit="5"
          >
            <UploadFilled />
            <template #tip>
              <div class="el-upload__tip">
                支持上传图片格式文件，最多5个，多个文件用逗号分隔
              </div>
            </template>
          </ElUpload>
        </ElFormItem>

        <!-- 是否提交 -->
        <ElFormItem label="是否提交">
          <ElSwitch v-model="formData.isSubmit" />
        </ElFormItem>

        <!-- 提交按钮 - 仅在创建模式下显示 -->
        <ElFormItem v-if="!props.id">
          <ElButton type="primary" @click="handleSubmit">创建工单</ElButton>
        </ElFormItem>
      </ElForm>
    </div>
  </Page>
</template>

<style lang="scss" scoped>
.wrap {
  padding: 16px;
  background-color: #fff;
  border-radius: 6px;
}

.create-order-form {
  max-width: 600px;
}
</style>
