<template>
  <el-dialog :title="dialogTitle" v-model="dialogVisible" width="1000px" style="height: 90vh">
    <el-tabs v-model="currentTab">
      <el-tab-pane label="基础信息" name="base">
        <el-form
          ref="formRef"
          v-loading="formLoading"
          :model="formData"
          :rules="formRules"
          label-width="80px"
        >
          <el-row :gutter="20">
            <el-col :span="12" :offset="0">
              <el-form-item label="驾校">
                <el-input v-model="formData.schoolName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item label="场地">
                <el-input v-model="formData.placeName" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12" :offset="0">
              <el-form-item label="班型名称" prop="typeName">
                <el-input v-model="formData.typeName" placeholder="请输入班型" />
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item label="驾照类型" prop="licenseType">
                <el-select v-model="formData.licenseType" placeholder="选择驾照类型">
                  <el-option
                    v-for="item in licenseTypeOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12" :offset="0">
              <el-form-item label="排序" prop="orderNum">
                <el-input-number v-model="formData.orderNum" />
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item label="状态" prop="currentPrice">
                <el-radio-group v-model="formData.status">
                  <el-radio :label="1">启用</el-radio>
                  <el-radio :label="0">停用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-form-item label="备注" prop="remark">
              <Editor v-model:modelValue="formData.remark" />
            </el-form-item>
          </el-row>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="报价信息" name="price">
        <el-button type="primary" @click="handleAddPrice" class="mb-10px">新增报价</el-button>
        <el-table :data="formData.priceList">
          <el-table-column width="160px">
            <template #header> <Tooltip message="市场价，给客户的报价" />指导价 </template>
            <template #default="{ row }">
              <el-input v-if="row.edit" v-model="row.markerPrice" type="number" :min="0" />
              <span v-else>{{ row.markerPrice }}</span>
            </template>
          </el-table-column>
          <el-table-column width="160px">
            <template #header> <Tooltip message="员工底价，用于核算毛利及提成" />底价 </template>
            <template #default="{ row }">
              <el-input v-if="row.edit" v-model="row.employeePrice" type="number" :min="0" />
              <span v-else>{{ row.employeePrice }}</span>
            </template>
          </el-table-column>
          <el-table-column width="160px">
            <template #header> <Tooltip message="公司采购价，用于计算公司利润" />成本价 </template>
            <template #default="{ row }">
              <el-input v-if="row.edit" v-model="row.costPrice" type="number" :min="0" />
              <span v-else>{{ row.costPrice }}</span>
            </template>
          </el-table-column>
          <el-table-column label="生效日期">
            <template #default="{ row }">
              <el-date-picker
                v-if="row.edit"
                v-model="row.startDate"
                type="date"
                placeholder="选择日期时间"
              />
              <span v-else>{{ row.startDate }}</span>
            </template>
          </el-table-column>
          <el-table-column label="报价日期" width="180px" prop="createTime" />
          <el-table-column label="操作" width="80px">
            <template #default="{ row, $index }">
              <el-button
                type="danger"
                text
                style="padding: 0"
                @click="handleDeletePrice(row, $index)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="提成结算" name="comission">
        <el-button v-if="!comissionShow" type="primary" @click="handleAddComission">
          新增提成结算规则
        </el-button>
        <el-form
          v-if="comissionShow"
          :model="comissionForm"
          ref="FormComission"
          class="mt-10px"
          label-width="80px"
          inline
        >
          <el-row :gutter="20">
            <el-col :span="12" :offset="0">
              <el-form-item label="生效日期" prop="startDate">
                <el-date-picker
                  v-model="comissionForm.startDate"
                  type="date"
                  placeholder="选择日期时间"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item label="结算方式">
                <el-radio-group v-model="comissionForm.type">
                  <el-radio :label="1">
                    <Tooltip message="可配置多级，命中某档位后，按照档位分级结算" />阶梯结算
                  </el-radio>
                  <el-radio :label="2">
                    <Tooltip message="可配置多级，命中某档位后所有金额全部按照该档位结算" />常规结算
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-button type="primary" class="mb-10px" plain @click="handleAddRules"
            >添加提成档位</el-button
          >
          <el-row :gutter="20" class="mb-10px">
            <el-col
              :span="24"
              :offset="0"
              class="flex"
              v-for="(item, index) in comissionForm.rules"
              :key="index"
            >
              <el-select v-model="item.type1" style="width: 100px">
                <el-option label="单笔" :value="1" />
                <el-option label="月总" :value="2" />
              </el-select>
              <el-select class="ml-5px" v-model="item.type2" style="width: 100px">
                <el-option label="成交额" :value="1" />
                <el-option label="毛利" :value="2" />
              </el-select>
              <span class="ml-5px">满</span>
              <el-input
                class="ml-5px"
                v-model="item.type3"
                placeholder="金额"
                type="number"
                :min="0"
                style="width: 100px"
              />
              <span class="ml-5px">元，</span>
              <el-select class="ml-5px" v-model="item.type4" style="width: 120px">
                <el-option label="按比例" :value="1" />
                <el-option label="按固定金额" :value="2" />
              </el-select>
              <div v-if="item.type4 == 2" class="inline-flex items-center">
                <el-input
                  class="ml-5px"
                  v-model="item.type7"
                  placeholder="金额"
                  type="number"
                  :min="0"
                  style="width: 100px"
                />
                <span class="ml-5px">元结算</span>
              </div>
              <div v-else class="inline-flex items-center">
                <span class="ml-5px">取</span>
                <el-select class="ml-5px" v-model="item.type5" style="width: 100px">
                  <el-option label="按成交额" :value="1" />
                  <el-option label="按底价" :value="2" />
                  <el-option label="按毛利" :value="3" />
                </el-select>
                <span class="ml-5px">结算</span>
                <el-input
                  class="ml-5px"
                  v-model="item.type6"
                  placeholder="比例"
                  type="number"
                  :min="1"
                  style="width: 100px"
                >
                  <template #suffix> % </template>
                </el-input>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20" class="mb-10px">
            <el-col :span="24" :offset="0">
              <el-button type="primary" @click="sureAddComission">确认新增</el-button>
              <el-button @click="comissionShow = false">取消</el-button>
            </el-col>
          </el-row>
        </el-form>
        <el-divider>历史结算规则</el-divider>
        <el-table :data="formData.comissionList" border>
          <el-table-column prop="startDate" label="生效时间" width="200px" />
          <el-table-column prop="typeName" label="结算方式" width="120px" />
          <el-table-column prop="ruleDesc" label="结算规则" />
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </el-dialog>
</template>
<script name="DialogClass" setup>
import { formatDate } from '@/utils/formatTime'
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 formData = ref({
  name: '',
  leader: '',
  phone: '',
  status: 1,
  remark: ''
})
const formRules = reactive({
  name: [{ required: true, message: '驾校名称不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const currentTab = ref('base')
const licenseTypeOption = ref([])

/** 打开弹窗 */
const open = async (type, id) => {
  dialogVisible.value = true
  dialogTitle.value = type == 'create' ? '新增班型' : '修改班型'
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      // formData.value = await UserApi.getUser(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

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

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    name: '',
    leader: '',
    phone: '',
    status: 1,
    remark: '',
    priceList: [],
    comissionList: [
      {
        startDate: '2024-01-01',
        typeName: '阶梯结算',
        ruleDesc: '月总成交额满0元，按比例取成交额1%'
      }
    ]
  }
  formRef.value?.resetFields()
}

function handleAddPrice() {
  formData.value.priceList.push({
    edit: true,
    markerPrice: undefined,
    employeePrice: undefined,
    costPrice: undefined,
    startDate: undefined,
    createTime: '2024-05-12'
  })
}

function handleDeletePrice(row, index) {
  if (row.edit) {
    formData.value.priceList.splice(index, 1)
  }
  message.success('删除成功')
}

const comissionForm = ref({
  rules: []
})
const comissionShow = ref(false)

function handleAddComission() {
  comissionShow.value = true
  comissionForm.value = {
    startDate: formatDate(new Date(), 'YYYY-MM-DD'),
    type: 1,
    rules: [
      {
        type1: 1,
        type2: 1,
        type3: 0,
        type4: 1,
        type5: 1,
        type6: 10
      }
    ]
  }
}

function handleAddRules() {
  comissionForm.value.rules.push({
    type1: 1,
    type2: 1,
    type3: 0,
    type4: 1,
    type5: 1,
    type6: 1
  })
}

function sureAddComission() {
  message.success('新增成功')
}
</script>
