<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="销售订单" prop="orderId">
        <el-input
          v-model="selectedOrderNo"
          placeholder="请选择销售订单"
          readonly
          @click="openOrderSelector"
          style="cursor: pointer"
        >
          <template #append>
            <el-button :icon="Search" @click="openOrderSelector" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="售后类型" prop="afterSaleType">
        <el-select v-model="formData.afterSaleType" placeholder="请选择售后类型" filterable>
          <el-option
            v-for="item in afterSaleTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="申请原因" prop="applyReason">
        <el-input v-model="formData.applyReason" placeholder="请输入申请原因" />
      </el-form-item>
      <el-form-item label="联系人" prop="contactName">
        <el-input v-model="formData.contactName" placeholder="请输入联系人" />
      </el-form-item>
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input v-model="formData.contactPhone" placeholder="请输入联系电话" maxlength="20" />
      </el-form-item>
      <el-form-item label="申请人" prop="applicant">
        <el-input v-model="formData.applicant" placeholder="请输入申请人" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <!-- 销售订单选择弹窗 -->
  <Dialog v-model="orderSelectorVisible" title="选择销售订单" width="70%" :appendToBody="true">
    <ContentWrap>
      <el-form
        ref="orderQueryFormRef"
        :inline="true"
        :model="orderQueryParams"
        class="-mb-15px"
        label-width="100px"
      >
        <el-form-item label="订单单号" prop="no">
          <el-input
            v-model="orderQueryParams.no"
            class="!w-200px"
            clearable
            placeholder="请输入订单单号"
            @keyup.enter="handleOrderQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleOrderQuery">
            <Icon class="mr-5px" icon="ep:search" />
            搜索
          </el-button>
          <el-button @click="resetOrderQuery">
            <Icon class="mr-5px" icon="ep:refresh" />
            重置
          </el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="orderLoading" :data="orderList" show-overflow-tooltip>
        <el-table-column label="#" width="55">
          <template #default="{ row }">
            <el-radio :value="row.id" v-model="selectedOrderId" @change="handleOrderSelected(row)">
              &nbsp;
            </el-radio>
          </template>
        </el-table-column>
        <el-table-column label="订单单号" align="center" prop="no" min-width="140" />
        <el-table-column label="客户" align="center" prop="customerName" min-width="120" />
        <el-table-column
          label="订单时间"
          align="center"
          prop="orderTime"
          :formatter="dateFormatter"
          width="160px"
        />
      </el-table>
      <Pagination
        v-model:limit="orderQueryParams.pageSize"
        v-model:page="orderQueryParams.pageNo"
        :total="orderTotal"
        @pagination="getOrderList"
      />
    </ContentWrap>
  </Dialog>
</template>
<script setup lang="ts">
import { Search } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { dateFormatter } from '@/utils/formatTime'
import { AfterSaleRegisterApi, AfterSaleRegister } from '@/api/erp/aftersale/aftersaleregister'
import { SaleOrderApi, SaleOrderVO } from '@/api/erp/sale/order'
import { useUserStoreWithOut } from '@/store/modules/user'

/** ERP 售后登记 表单 */
defineOptions({ name: 'AfterSaleRegisterForm' })

const afterSaleTypeOptions = [
  { label: '退货', value: 1 },
  { label: '换货', value: 2 },
  { label: '维修', value: 3 },
  { label: '退款', value: 4 }
]

const applyStatusOptions = [
  { label: '待审核', value: 1 },
  { label: '审核通过', value: 2 },
  { label: '审核驳回', value: 3 },
  { label: '已取消', value: 4 }
]

// 销售订单选择器相关
const orderSelectorVisible = ref(false)
const selectedOrderId = ref<number>()
const selectedOrderNo = ref<string>('')
const orderLoading = ref(false)
const orderList = ref<SaleOrderVO[]>([])
const orderTotal = ref(0)
const orderQueryParams = ref({
  pageNo: 1,
  pageSize: 10,
  no: ''
})
const orderQueryFormRef = ref()

/** 打开订单选择器 */
const openOrderSelector = () => {
  orderSelectorVisible.value = true
  orderQueryParams.value = {
    pageNo: 1,
    pageSize: 10,
    no: ''
  }
  getOrderList()
}

/** 查询订单列表 */
const getOrderList = async () => {
  orderLoading.value = true
  try {
    const data = await SaleOrderApi.getSaleOrderPage(orderQueryParams.value)
    orderList.value = data.list
    orderTotal.value = data.total
  } finally {
    orderLoading.value = false
  }
}

/** 搜索订单 */
const handleOrderQuery = () => {
  orderQueryParams.value.pageNo = 1
  getOrderList()
}

/** 重置订单查询 */
const resetOrderQuery = () => {
  orderQueryParams.value = {
    pageNo: 1,
    pageSize: 10,
    no: ''
  }
  getOrderList()
}

/** 选中订单 */
const handleOrderSelected = (row: SaleOrderVO) => {
  formData.value.orderId = row.id
  selectedOrderNo.value = row.no || ''
  selectedOrderId.value = row.id
  orderSelectorVisible.value = false
}

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const userStore = useUserStoreWithOut()
const currentUserNickname = computed(() => userStore.getUser?.nickname || '')
const nowString = () => dayjs().format('YYYY-MM-DD HH:mm:ss')

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref<Partial<AfterSaleRegister>>({
  id: undefined,
  orderId: undefined,
  orderItemId: undefined,
  afterSaleType: undefined,
  applyReason: undefined,
  contactName: undefined,
  contactPhone: undefined,
  applyStatus: undefined,
  rejectReason: undefined,
  applicant: undefined,
  auditUser: undefined,
  auditTime: undefined
})
const formRules = reactive({
  afterSaleType: [{ required: true, message: '售后类型不能为空', trigger: 'change' }],
  applyReason: [{ required: true, message: '申请原因不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await AfterSaleRegisterApi.getAfterSaleRegister(id)
      // 如果有订单ID，获取订单号显示
      if (formData.value.orderId) {
        const order = await SaleOrderApi.getSaleOrder(formData.value.orderId)
        selectedOrderNo.value = order.no || ''
        selectedOrderId.value = order.id
      }
      ensureDefaultsForExisting()
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单（当前无必填规则，直接通过）
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as AfterSaleRegister
    if (formType.value === 'create') {
      await AfterSaleRegisterApi.createAfterSaleRegister(data)
      message.success(t('common.createSuccess'))
    } else {
      await AfterSaleRegisterApi.updateAfterSaleRegister(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    orderId: undefined,
    orderItemId: undefined,
    afterSaleType: undefined,
    applyReason: undefined,
    contactName: undefined,
    contactPhone: undefined,
    applyStatus: 1, // 新增时默认为待审核状态
    rejectReason: undefined,
    applicant: currentUserNickname.value || undefined,
    auditUser: undefined,
    auditTime: undefined
  }
  selectedOrderNo.value = ''
  selectedOrderId.value = undefined
  formRef.value?.resetFields()
}

const ensureDefaultsForExisting = () => {
  if (!formData.value.applicant) {
    formData.value.applicant = currentUserNickname.value || undefined
  }
  if (formData.value.applyStatus === 2) {
    if (!formData.value.auditUser) {
      formData.value.auditUser = currentUserNickname.value || undefined
    }
    if (!formData.value.auditTime) {
      formData.value.auditTime = nowString()
    }
  }
}
</script>
