<template>
  <!-- 移动端布局 -->
  <el-drawer v-if="isMobile" v-model="dialogVisible" :title="dialogTitle" direction="rtl" size="100%" :close-on-press-escape="true" :destroy-on-close="true" :append-to-body="true" class="mobile-form-drawer">
    <div class="mobile-form" v-loading="formLoading">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-position="top" :disabled="disabled">
        <div class="mobile-form__section">
          <div class="mobile-form__section-title">基本信息</div>
          <el-form-item label="退货单号" prop="no"><el-input disabled v-model="formData.no" placeholder="保存时自动生成" /></el-form-item>
          <el-form-item label="退货时间" prop="returnTime"><el-date-picker v-model="formData.returnTime" type="date" value-format="x" placeholder="选择退货时间" style="width:100%" /></el-form-item>
          <el-form-item label="关联订单" prop="orderNo"><el-input readonly><template #prefix><el-link v-if="formData.orderId" type="primary" :underline="false" @click.stop="openPurchaseOrderDetail">{{ formData.orderNo }}</el-link></template><template #append><el-button @click="openPurchaseOrderReturnEnableList"><Icon icon="ep:search" /></el-button></template></el-input></el-form-item>
          <el-form-item label="供应商" prop="supplierId"><el-select v-model="formData.supplierId" clearable filterable disabled placeholder="请选择供应商" style="width:100%"><el-option v-for="item in supplierList" :key="item.id" :label="item.name" :value="item.id" /></el-select></el-form-item>
          <el-form-item label="备注" prop="remark"><el-input type="textarea" v-model="formData.remark" :rows="3" placeholder="请输入备注" /></el-form-item>
          <el-form-item label="附件" prop="fileUrl"><UploadFile :is-show-tip="false" v-model="formData.fileUrl" :limit="1" /></el-form-item>
        </div>
        <div class="mobile-form__section">
          <div class="mobile-form__section-title">退货产品清单</div>
          <PurchaseReturnItemForm ref="itemFormRef" :items="formData.items" :disabled="disabled" />
        </div>
        <div class="mobile-form__section">
          <div class="mobile-form__section-title">费用信息</div>
          <el-form-item label="优惠率（%）" prop="discountPercent"><el-input-number v-model="formData.discountPercent" controls-position="right" :min="0" :precision="4" placeholder="请输入优惠率" style="width:100%" /></el-form-item>
          <el-form-item label="退款优惠" prop="discountPrice"><el-input disabled v-model="formData.discountPrice" :formatter="erpPriceInputFormatter" /></el-form-item>
          <el-form-item label="其它费用" prop="otherPrice"><el-input-number v-model="formData.otherPrice" controls-position="right" :min="0" :precision="4" placeholder="请输入其它费用" style="width:100%" /></el-form-item>
          <el-form-item label="优惠后金额"><el-input disabled v-model="formData.totalPrice" :formatter="erpPriceInputFormatter" /></el-form-item>
          <el-form-item label="结算账户" prop="accountId"><el-select v-model="formData.accountId" clearable filterable placeholder="请选择结算账户" style="width:100%"><el-option v-for="item in accountList" :key="item.id" :label="item.name" :value="item.id" /></el-select></el-form-item>
        </div>
      </el-form>
      <div class="mobile-form__footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button @click="submitForm" type="primary" :disabled="formLoading" v-if="!disabled">确 定</el-button>
      </div>
    </div>
  </el-drawer>

  <!-- PC端布局 -->
  <Dialog v-else :title="dialogTitle" v-model="dialogVisible" width="1440">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" v-loading="formLoading" :disabled="disabled">
      <el-row :gutter="20">
        <el-col :span="8"><el-form-item label="退货单号" prop="no"><el-input disabled v-model="formData.no" placeholder="保存时自动生成" /></el-form-item></el-col>
        <el-col :span="8"><el-form-item label="退货时间" prop="returnTime"><el-date-picker v-model="formData.returnTime" type="date" value-format="x" placeholder="选择退货时间" class="!w-1/1" /></el-form-item></el-col>
        <el-col :span="8"><el-form-item label="关联订单" prop="orderNo"><el-input readonly><template #prefix><el-link v-if="formData.orderId" type="primary" :underline="false" @click.stop="openPurchaseOrderDetail">{{ formData.orderNo }}</el-link></template><template #append><el-button @click="openPurchaseOrderReturnEnableList"><Icon icon="ep:search" /> 选择</el-button></template></el-input></el-form-item></el-col>
        <el-col :span="8"><el-form-item label="供应商" prop="supplierId"><el-select v-model="formData.supplierId" clearable filterable disabled placeholder="请选择供应商" class="!w-1/1"><el-option v-for="item in supplierList" :key="item.id" :label="item.name" :value="item.id" /></el-select></el-form-item></el-col>
        <el-col :span="16"><el-form-item label="备注" prop="remark"><el-input type="textarea" v-model="formData.remark" :rows="1" placeholder="请输入备注" /></el-form-item></el-col>
        <el-col :span="8"><el-form-item label="附件" prop="fileUrl"><UploadFile :is-show-tip="false" v-model="formData.fileUrl" :limit="1" /></el-form-item></el-col>
      </el-row>
      <ContentWrap>
        <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">
          <el-tab-pane label="退货产品清单" name="item"><PurchaseReturnItemForm ref="itemFormRef" :items="formData.items" :disabled="disabled" /></el-tab-pane>
        </el-tabs>
      </ContentWrap>
      <el-row :gutter="20">
        <el-col :span="8"><el-form-item label="优惠率（%）" prop="discountPercent"><el-input-number v-model="formData.discountPercent" controls-position="right" :min="0" :precision="4" placeholder="请输入优惠率" class="!w-1/1" /></el-form-item></el-col>
        <el-col :span="8"><el-form-item label="退款优惠" prop="discountPrice"><el-input disabled v-model="formData.discountPrice" :formatter="erpPriceInputFormatter" /></el-form-item></el-col>
        <el-col :span="8"><el-form-item label="其它费用" prop="otherPrice"><el-input-number v-model="formData.otherPrice" controls-position="right" :min="0" :precision="4" placeholder="请输入其它费用" class="!w-1/1" /></el-form-item></el-col>
        <el-col :span="8"><el-form-item label="优惠后金额"><el-input disabled v-model="formData.totalPrice" :formatter="erpPriceInputFormatter" /></el-form-item></el-col>
        <el-col :span="8"><el-form-item label="结算账户" prop="accountId"><el-select v-model="formData.accountId" clearable filterable placeholder="请选择结算账户" class="!w-1/1"><el-option v-for="item in accountList" :key="item.id" :label="item.name" :value="item.id" /></el-select></el-form-item></el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading" v-if="!disabled">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <!-- 可退货的订单列表 -->
  <PurchaseOrderReturnEnableList ref="purchaseOrderReturnEnableListRef" @success="handlePurchaseOrderChange" />
  <!-- 采购订单详情弹窗 -->
  <PurchaseOrderForm ref="purchaseOrderFormRef" />
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { PurchaseReturnApi, PurchaseReturnVO } from '@/api/erp/purchase/return'
import PurchaseReturnItemForm from './components/PurchaseReturnItemForm.vue'
import { SupplierApi, SupplierVO } from '@/api/erp/purchase/supplier'
import { AccountApi, AccountVO } from '@/api/erp/finance/account'
import { erpPriceInputFormatter, erpPriceMultiply } from '@/utils'
import PurchaseOrderReturnEnableList from '@/views/erp/purchase/order/components/PurchaseOrderReturnEnableList.vue'
import PurchaseOrderForm from '@/views/erp/purchase/order/PurchaseOrderForm.vue'
import { PurchaseOrderVO } from '@/api/erp/purchase/order'
import * as UserApi from '@/api/system/user'
import { useWindowSize } from '@vueuse/core'

defineOptions({ name: 'PurchaseReturnForm' })

const { width } = useWindowSize()
const isMobile = computed(() => width.value < 768)
const { t } = useI18n()
const message = useMessage()

/** 弹窗显示 */
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')

/** 表单数据 */
const formData = ref({
  id: undefined,
  orderId: undefined,
  supplierId: undefined,
  accountId: undefined,
  returnTime: undefined,
  remark: undefined,
  fileUrl: '',
  discountPercent: 0,
  discountPrice: 0,
  totalPrice: 0,
  otherPrice: 0,
  orderNo: undefined,
  items: [],
  no: undefined
})

/** 表单验证 */
const formRules = reactive({
  supplierId: [{ required: true, message: '供应商不能为空', trigger: 'blur' }],
  returnTime: [{ required: true, message: '退货时间不能为空', trigger: 'blur' }]
})

/** 计算禁用状态 */
const disabled = computed(() => formType.value === 'detail')

/** ref */
const formRef = ref() // el-form
const itemFormRef = ref()
const supplierList = ref<SupplierVO[]>([])
const accountList = ref<AccountVO[]>([])
const userList = ref<UserApi.UserVO[]>([])
const subTabsName = ref('item')

/** 计算价格 */
watch(
  () => formData.value,
  (val) => {
    if (!val) return
    const totalItemPrice = (val.items || []).reduce((sum, item) => sum + (item.totalPrice || 0), 0)
    const discountPrice = erpPriceMultiply(totalItemPrice, (val.discountPercent || 0) / 100) || 0
    formData.value.discountPrice = discountPrice
    formData.value.totalPrice = totalItemPrice - discountPrice + (val.otherPrice || 0)
  },
  { deep: true }
)

/** 打开弹窗 */
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 PurchaseReturnApi.getPurchaseReturn(id)
    } finally {
      formLoading.value = false
    }
  }
  supplierList.value = await SupplierApi.getSupplierSimpleList()
  accountList.value = await AccountApi.getAccountSimpleList()
  userList.value = await UserApi.getSimpleUserList()
  const defaultAccount = accountList.value.find((item) => item.defaultStatus)
  if (defaultAccount) formData.value.accountId = defaultAccount.id
}
defineExpose({ open })

/** 打开可退货订单列表 */
const purchaseOrderReturnEnableListRef = ref()
const openPurchaseOrderReturnEnableList = () => {
  purchaseOrderReturnEnableListRef.value?.open()
}

/** 打开采购订单详情 */
const purchaseOrderFormRef = ref()
const openPurchaseOrderDetail = () => {
  if (formData.value.orderId) purchaseOrderFormRef.value?.open('detail', formData.value.orderId)
}

/** 订单选择回调 */
const handlePurchaseOrderChange = (order: PurchaseOrderVO) => {
  formData.value.orderId = order.id
  formData.value.orderNo = order.no
  formData.value.supplierId = order.supplierId
  formData.value.accountId = order.accountId
  formData.value.discountPercent = order.discountPercent
  formData.value.remark = order.remark
  formData.value.fileUrl = order.fileUrl

  // 处理订单明细
  order.items.forEach(item => {
    item.count = item.inCount - item.returnCount
    item.orderItemId = item.id
    item.id = undefined
  })
  formData.value.items = order.items.filter(item => item.count > 0)
}

/** 提交表单 */
const emit = defineEmits(['success'])
const submitForm = async () => {
  await formRef.value.validate()
  await itemFormRef.value.validate()
  formLoading.value = true
  try {
    const data = formData.value as unknown as PurchaseReturnVO
    if (formType.value === 'create') {
      await PurchaseReturnApi.createPurchaseReturn(data)
      message.success(t('common.createSuccess'))
    } else {
      await PurchaseReturnApi.updatePurchaseReturn(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    orderId: undefined,
    supplierId: undefined,
    accountId: undefined,
    returnTime: undefined,
    remark: undefined,
    fileUrl: '',
    discountPercent: 0,
    discountPrice: 0,
    totalPrice: 0,
    otherPrice: 0,
    orderNo: undefined,
    items: [],
    no: undefined
  }
  formRef.value?.resetFields()
}
</script>

<style lang="scss" scoped>
.mobile-form {
  padding: 12px;
}
.mobile-form__section {
  background: #fff;
  border-radius: 10px;
  padding: 14px;
  margin-bottom: 12px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
}
.mobile-form__section-title {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}
.mobile-form__requisition {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}
.mobile-form__footer {
  position: sticky;
  bottom: 0;
  background: #fff;
  padding: 12px 16px;
  padding-bottom: calc(12px + env(safe-area-inset-bottom));
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  z-index: 10;
  margin: 0 -12px -12px;

  .el-button {
    flex: 1;
    height: 40px;
    font-size: 15px;
  }
}
</style>
