<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>
          <div class="mobile-form__input-group">
            <el-form-item label="请购类型" prop="type">
              <el-select v-model="formData.type" placeholder="请选择" style="width: 100%">
                <el-option label="请购" :value="1" />
                <el-option label="补货" :value="2" />
                <el-option label="其他" :value="3" />
              </el-select>
            </el-form-item>
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="formData.priority" placeholder="请选择" style="width: 100%">
                <el-option label="低" :value="1" />
                <el-option label="中" :value="2" />
                <el-option label="高" :value="3" />
                <el-option label="紧急" :value="4" />
              </el-select>
            </el-form-item>
          </div>
          <el-form-item label="请购人" prop="requesterId">
            <el-select v-model="formData.requesterId" placeholder="请选择请购人" filterable clearable style="width: 100%" @change="onRequesterChange">
              <el-option v-for="item in userList" :key="item.id" :label="item.nickname" :value="item.id">
                <span style="float: left">{{ item.nickname }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.username }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="请购部门" prop="requesterDeptId">
            <el-select v-model="formData.requesterDeptId" placeholder="请选择部门" clearable style="width: 100%" @change="onDeptChange">
              <el-option v-for="item in deptList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="紧急程度" prop="emergencyDegree">
            <el-select v-model="formData.emergencyDegree" placeholder="请选择" style="width: 100%">
              <el-option label="普通" :value="1" />
              <el-option label="较急" :value="2" />
              <el-option label="紧急" :value="3" />
              <el-option label="特急" :value="4" />
            </el-select>
          </el-form-item>
          <div class="mobile-form__input-group">
            <el-form-item label="请购时间" prop="requestTime">
              <el-date-picker v-model="formData.requestTime" type="date" value-format="x" placeholder="选择时间" style="width: 100%" />
            </el-form-item>
            <el-form-item label="期望到货" prop="expectedTime">
              <el-date-picker v-model="formData.expectedTime" type="date" value-format="x" placeholder="选择时间" style="width: 100%" />
            </el-form-item>
          </div>
          <el-form-item label="供应商" prop="supplierId">
            <el-select v-model="formData.supplierId" placeholder="请选择供应商" filterable clearable style="width: 100%" @change="onSupplierChange">
              <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="fileUrl">
            <UploadFile :is-show-tip="false" v-model="formData.fileUrl" :limit="1" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model="formData.remark" :rows="2" placeholder="请输入备注" />
          </el-form-item>
        </div>

        <!-- 请购产品清单 -->
        <div class="mobile-form__section">
          <div class="mobile-form__section-title">请购产品清单</div>
          <PurchaseRequisitionItemForm ref="itemFormRef" :items="formData.items" :disabled="disabled" />
        </div>

        <!-- 汇总 -->
        <div class="mobile-form__section">
          <div class="mobile-form__section-title">汇总</div>
          <div class="mobile-form__info-row">
            <span class="mobile-form__info-label">合计数量</span>
            <span class="mobile-form__info-value">{{ formData.totalCount }}</span>
          </div>
          <div class="mobile-form__info-row">
            <span class="mobile-form__info-label">合计金额</span>
            <span class="mobile-form__info-value" style="color: #e6a23c">{{ erpPriceInputFormatter(formData.totalPrice) }}</span>
          </div>
        </div>

        <!-- 审核信息 -->
        <div class="mobile-form__section" v-if="formData.status === 2 || formData.status === 3">
          <div class="mobile-form__section-title">审核信息</div>
          <el-form-item label="审核意见">
            <el-input v-model="formData.approveRemark" type="textarea" :rows="2" placeholder="审核意见" :disabled="formType === 'create'" />
          </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="1200">
    <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="type"><el-select v-model="formData.type" placeholder="请选择" class="!w-1/1"><el-option label="请购" :value="1" /><el-option label="补货" :value="2" /><el-option label="其他" :value="3" /></el-select></el-form-item></el-col>
        <el-col :span="8"><el-form-item label="优先级" prop="priority"><el-select v-model="formData.priority" placeholder="请选择" class="!w-1/1"><el-option label="低" :value="1" /><el-option label="中" :value="2" /><el-option label="高" :value="3" /><el-option label="紧急" :value="4" /></el-select></el-form-item></el-col>
        <el-col :span="8"><el-form-item label="紧急程度" prop="emergencyDegree"><el-select v-model="formData.emergencyDegree" placeholder="请选择" class="!w-1/1"><el-option label="普通" :value="1" /><el-option label="较急" :value="2" /><el-option label="紧急" :value="3" /><el-option label="特急" :value="4" /></el-select></el-form-item></el-col>
        <el-col :span="8"><el-form-item label="请购人" prop="requesterId"><el-select v-model="formData.requesterId" placeholder="请选择请购人" filterable clearable class="!w-1/1" @change="onRequesterChange"><el-option v-for="item in userList" :key="item.id" :label="item.nickname" :value="item.id" /></el-select></el-form-item></el-col>
        <el-col :span="8"><el-form-item label="请购部门" prop="requesterDeptId"><el-select v-model="formData.requesterDeptId" placeholder="请选择部门" clearable class="!w-1/1" @change="onDeptChange"><el-option v-for="item in deptList" :key="item.id" :label="item.name" :value="item.id" /></el-select></el-form-item></el-col>
        <el-col :span="8"><el-form-item label="请购时间" prop="requestTime"><el-date-picker v-model="formData.requestTime" type="date" value-format="x" placeholder="选择时间" class="!w-1/1" /></el-form-item></el-col>
        <el-col :span="8"><el-form-item label="期望到货" prop="expectedTime"><el-date-picker v-model="formData.expectedTime" type="date" value-format="x" placeholder="选择时间" class="!w-1/1" /></el-form-item></el-col>
        <el-col :span="8"><el-form-item label="供应商" prop="supplierId"><el-select v-model="formData.supplierId" placeholder="请选择供应商" filterable clearable class="!w-1/1" @change="onSupplierChange"><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="3" 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"><PurchaseRequisitionItemForm 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="合计数量"><span style="font-weight:600">{{ formData.totalCount }}</span></el-form-item></el-col>
        <el-col :span="8"><el-form-item label="合计金额"><span style="color:#e6a23c;font-weight:600">{{ erpPriceInputFormatter(formData.totalPrice) }}</span></el-form-item></el-col>
      </el-row>
      <template v-if="formData.status === 2 || formData.status === 3">
        <el-divider content-position="left">审核信息</el-divider>
        <el-form-item label="审核意见"><el-input v-model="formData.approveRemark" type="textarea" :rows="2" placeholder="审核意见" :disabled="formType === 'create'" /></el-form-item>
      </template>
    </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>
</template>
<script setup lang="ts">
import { nextTick, computed } from 'vue'
import { PurchaseRequisitionApi, PurchaseRequisition } from '@/api/erp/purchaserequisition'
import { getSimpleUserList } from '@/api/system/user'
import { getSimpleDeptList } from '@/api/system/dept'
import { SupplierApi } from '@/api/erp/purchase/supplier'
import PurchaseRequisitionItemForm from './components/PurchaseRequisitionItemForm.vue'
import { erpPriceInputFormatter } from '@/utils'
import { useWindowSize } from '@vueuse/core'

/** 请购单 表单 */
defineOptions({ name: 'PurchaseRequisitionForm' })

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) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const userList = ref([]) // 用户列表
const deptList = ref([]) // 部门列表
const supplierList = ref([]) // 供应商列表

const formData = ref({
  id: undefined,
  no: undefined,
  type: undefined,
  priority: undefined,
  status: 1, // 默认待审核
  requesterId: undefined,
  requesterName: undefined,
  requesterDeptId: undefined,
  requesterDeptName: undefined,
  requestTime: Date.now(),
  expectedTime: undefined,
  approverId: undefined,
  approveTime: undefined,
  approveRemark: undefined,
  totalCount: 0,
  totalPrice: 0,
  emergencyDegree: 1, // 默认普通
  fileUrl: '',
  remark: undefined,
  supplierId: undefined,
  supplierName: undefined,
  items: [] // 明细项
})

const formRules = reactive({
  type: [{ required: true, message: '请购类型不能为空', trigger: 'change' }],
  priority: [{ required: true, message: '优先级不能为空', trigger: 'change' }],
  requesterId: [{ required: true, message: '请购人不能为空', trigger: 'change' }],
  // requesterDeptId: [{ required: true, message: '请购部门不能为空', trigger: 'change' }],
  requestTime: [{ required: true, message: '请购时间不能为空', trigger: 'change' }],
  expectedTime: [{ required: true, message: '期望到货时间不能为空', trigger: 'change' }],
  emergencyDegree: [{ required: true, message: '紧急程度不能为空', trigger: 'change' }]
})
const disabled = computed(() => formType.value === 'detail')
const formRef = ref() // 表单 Ref
const subTabsName = ref('item')
const itemFormRef = ref()

/** 计算 totalCount、totalPrice */
watch(
  () => formData.value,
  (val) => {
    if (!val) {
      return
    }
    const totalCount = (val.items || []).reduce(
      (prev: number, curr: any) => prev + (curr.count || 0),
      0
    )
    const totalPrice = (val.items || []).reduce(
      (prev: number, curr: any) => prev + (curr.totalPrice || 0),
      0
    )
    formData.value.totalCount = totalCount
    formData.value.totalPrice = totalPrice
  },
  { deep: true }
)

/** 获取用户列表 */
const getUserList = async () => {
  try {
    const data = await getSimpleUserList()
    userList.value = data || []
  } catch (error) {
    console.error('获取用户列表失败', error)
  }
}

/** 获取部门列表 */
const getDeptList = async () => {
  try {
    const data = await getSimpleDeptList()
    deptList.value = data || []
  } catch (error) {
    console.error('获取部门列表失败', error)
  }
}

/** 获取供应商列表 */
const getSupplierList = async () => {
  try {
    const data = await SupplierApi.getSupplierSimpleList()
    supplierList.value = data || []
  } catch (error) {
    console.error('获取供应商列表失败', error)
  }
}

/** 请购人变化 */
const onRequesterChange = (userId: number) => {
  const user = userList.value.find(item => item.id === userId)
  if (user) {
    formData.value.requesterId = user.id
    formData.value.requesterName = user.nickname
  }
}

/** 部门变化 */
const onDeptChange = (deptId: number) => {
  const dept = deptList.value.find(item => item.id === deptId)
  if (dept) {
    formData.value.requesterDeptId = dept.id
    formData.value.requesterDeptName = dept.name
  }
}

/** 供应商变化 */
const onSupplierChange = (supplierId: number) => {
  const supplier = supplierList.value.find(item => item.id === supplierId)
  if (supplier) {
    formData.value.supplierId = supplier.id
    formData.value.supplierName = supplier.name
  } else {
    formData.value.supplierId = undefined
    formData.value.supplierName = undefined
  }
}

/** 审核通过 */
const handleApprove = async () => {
  try {
    await formRef.value.validate()
    formData.value.status = 2
    formData.value.approveRemark = '审核通过'
    await submitForm()
  } catch (error) {
    console.error(error)
  }
}

/** 审核驳回 */
const handleReject = async () => {
  const remark = await message.prompt('请输入驳回理由', '驳回')
  if (remark) {
    formData.value.status = 3
    formData.value.approveRemark = remark
    await submitForm()
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  await nextTick()
  resetForm()

  // 加载基础数据
  await getUserList()
  await getDeptList()
  await getSupplierList()

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await PurchaseRequisitionApi.getPurchaseRequisition(id)
      formData.value = { ...data }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  await itemFormRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as PurchaseRequisition
    if (formType.value === 'create') {
      await PurchaseRequisitionApi.createPurchaseRequisition(data)
      message.success(t('common.createSuccess'))
    } else {
      await PurchaseRequisitionApi.updatePurchaseRequisition(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    no: undefined,
    type: undefined,
    priority: undefined,
    status: 1,
    requesterId: undefined,
    requesterName: undefined,
    requesterDeptId: undefined,
    requesterDeptName: undefined,
    requestTime: Date.now(),
    expectedTime: undefined,
    approverId: undefined,
    approveTime: undefined,
    approveRemark: undefined,
    totalCount: 0,
    totalPrice: 0,
    emergencyDegree: 1,
    fileUrl: '',
    remark: undefined,
    supplierId: undefined,
    supplierName: undefined,
    items: []
  }
  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__input-group {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
}
.mobile-form__info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 0;
  font-size: 14px;
}
.mobile-form__info-label {
  color: #909399;
}
.mobile-form__info-value {
  font-weight: 600;
  color: #303133;
}
.mobile-form__tip {
  margin-top: 4px;
  font-size: 12px;
  color: var(--el-color-danger);
}
.mobile-form__footer {
  position: sticky;
  bottom: 0;
  background: #fff;
  padding: 12px 16px;
  padding-bottom: calc(12px + constant(safe-area-inset-bottom));
  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>
