<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="name">
            <el-input v-model="formData.name" placeholder="请输入计划名称" />
          </el-form-item>
          <el-form-item label="客户" prop="customerId">
            <el-select v-model="formData.customerId" clearable filterable placeholder="请选择客户" style="width: 100%">
              <el-option v-for="item in customerList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="目标金额" prop="targetAmount">
            <el-input-number v-model="formData.targetAmount" controls-position="right" :min="0" :precision="4" placeholder="请输入目标金额" style="width: 100%" />
          </el-form-item>
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker v-model="formData.startTime" type="date" value-format="x" placeholder="选择开始时间" style="width: 100%" />
          </el-form-item>
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker v-model="formData.endTime" type="date" value-format="x" placeholder="选择结束时间" style="width: 100%" />
          </el-form-item>
          <el-form-item label="审批人" prop="approverId">
            <el-select v-model="formData.approverId" clearable filterable placeholder="请选择审批人" style="width: 100%">
              <el-option v-for="item in userList" :key="item.id" :label="item.nickname" :value="item.id" />
            </el-select>
          </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>
          <SalePlanItemForm ref="itemFormRef" :items="formData.items" :disabled="disabled" />
        </div>

        <!-- 合计 -->
        <div class="mobile-form__section">
          <div class="mobile-form__section-title">合计信息</div>
          <el-form-item label="合计金额">
            <el-input disabled v-model="formData.totalPrice" :formatter="erpPriceInputFormatter" />
          </el-form-item>
        </div>
      </el-form>
    </div>

    <!-- 底部按钮 -->
    <template #footer>
      <div class="mobile-form__footer">
        <el-button @click="dialogVisible = false" style="flex:1">取 消</el-button>
        <el-button type="primary" @click="submitForm" :disabled="formLoading" v-if="!disabled" style="flex:2">
          确 定
        </el-button>
      </div>
    </template>
  </el-drawer>

  <!-- PC端布局 -->
  <Dialog v-else :title="dialogTitle" v-model="dialogVisible" width="1080">
    <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="name"><el-input v-model="formData.name" placeholder="请输入计划名称" /></el-form-item></el-col>
        <el-col :span="8"><el-form-item label="客户" prop="customerId"><el-select v-model="formData.customerId" clearable filterable placeholder="请选择客户" class="!w-1/1"><el-option v-for="item in customerList" :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="targetAmount"><el-input-number v-model="formData.targetAmount" 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="startTime"><el-date-picker v-model="formData.startTime" type="date" value-format="x" placeholder="选择开始时间" class="!w-1/1" /></el-form-item></el-col>
        <el-col :span="8"><el-form-item label="结束时间" prop="endTime"><el-date-picker v-model="formData.endTime" type="date" value-format="x" placeholder="选择结束时间" class="!w-1/1" /></el-form-item></el-col>
        <el-col :span="8"><el-form-item label="审批人" prop="approverId"><el-select v-model="formData.approverId" clearable filterable placeholder="请选择审批人" class="!w-1/1"><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="16"><el-form-item label="备注" prop="remark"><el-input type="textarea" v-model="formData.remark" :rows="1" placeholder="请输入备注" /></el-form-item></el-col>
      </el-row>
      <ContentWrap>
        <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">
          <el-tab-pane label="计划产品明细" name="item"><SalePlanItemForm 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="合计金额"><el-input disabled v-model="formData.totalPrice" :formatter="erpPriceInputFormatter" /></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>
</template>
<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { SalePlanApi, SalePlanVO } from '@/api/erp/sale/plan'
import SalePlanItemForm from './components/SalePlanItemForm.vue'
import { CustomerApi, CustomerVO } from '@/api/erp/sale/customer'
import { erpPriceInputFormatter } from '@/utils'
import * as UserApi from '@/api/system/user'
import { useWindowSize } from '@vueuse/core'

/** ERP 销售计划表单 */
defineOptions({ name: 'SalePlanForm' })

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 - 修改；detail - 详情
const formData = ref({
  id: undefined,
  no: undefined,
  name: undefined,
  customerId: undefined,
  targetAmount: 0,
  startTime: undefined,
  endTime: undefined,
  status: 10, // 默认草稿状态
  approverId: undefined,
  remark: undefined,
  totalPrice: 0,
  items: []
})
const formRules = reactive({
  name: [{ required: true, message: '计划名称不能为空', trigger: 'blur' }],
  customerId: [{ required: true, message: '客户不能为空', trigger: 'blur' }],
  startTime: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
  endTime: [{ required: true, message: '结束时间不能为空', trigger: 'blur' }]
})
const disabled = computed(() => formType.value === 'detail')
const formRef = ref() // 表单 Ref
const customerList = ref<CustomerVO[]>([]) // 客户列表
const userList = ref<UserApi.UserVO[]>([]) // 用户列表

/** 子表的表单 */
const subTabsName = ref('item')
const itemFormRef = ref()

/** 计算 totalPrice 价格 */
watch(
  () => formData.value.items,
  (items) => {
    if (!items) {
      return
    }
    const totalPrice = items.reduce((prev, curr) => prev + (curr.totalPrice || 0), 0)
    formData.value.totalPrice = totalPrice
    // 如果目标金额为0或未设置，则自动填充合计金额
    if (!formData.value.targetAmount || formData.value.targetAmount === 0) {
      formData.value.targetAmount = totalPrice
    }
  },
  { 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 SalePlanApi.getSalePlan(id)
    } finally {
      formLoading.value = false
    }
  }
  // 加载客户列表
  customerList.value = await CustomerApi.getCustomerSimpleList()
  // 加载用户列表
  userList.value = await UserApi.getSimpleUserList()
}
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 SalePlanVO
    if (formType.value === 'create') {
      await SalePlanApi.createSalePlan(data)
      message.success(t('common.createSuccess'))
    } else {
      await SalePlanApi.updateSalePlan(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    no: undefined,
    name: undefined,
    customerId: undefined,
    targetAmount: 0,
    startTime: undefined,
    endTime: undefined,
    status: 10,
    approverId: undefined,
    remark: undefined,
    totalPrice: 0,
    items: []
  }
  formRef.value?.resetFields()
}
</script>

<style lang="scss" scoped>
.mobile-form {
  padding: 12px;
}

.mobile-form__section {
  background: #fff;
  border-radius: 8px;
  padding: 14px;
  margin-bottom: 12px;
}

.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__footer {
  display: flex;
  gap: 12px;
  padding: 0 12px;
}
</style>
