<template>
  <ContentWrap>
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px"
      label-width="100px"
    >
      <el-form-item label="员工姓名" prop="employeeName">
        <el-input
          v-model="queryParams.employeeName"
          class="!w-220px"
          clearable
          placeholder="请输入员工姓名"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="预算年度" prop="budgetYear">
        <el-date-picker
          v-model="queryBudgetYearValue"
          class="!w-180px"
          clearable
          placeholder="请选择年度"
          type="year"
          value-format="YYYY"
        />
      </el-form-item>
      <el-form-item label="是否启用" prop="enabledFlag">
        <el-select v-model="queryParams.enabledFlag" class="!w-180px" clearable placeholder="请选择">
          <el-option :value="true" label="启用" />
          <el-option :value="false" label="停用" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
        <el-button
          v-hasPermi="['tjt:employee-year-cost-budget:create']"
          plain
          type="primary"
          @click="openDialog('create')"
        >
          <Icon class="mr-5px" icon="ep:plus" />
          新增
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>
    <el-table v-loading="loading" :data="list">
      <el-table-column align="center" label="ID" prop="id" width="88" />
      <el-table-column align="center" label="员工姓名" min-width="140" prop="employeeName" />
      <el-table-column align="center" label="预算年度" prop="budgetYear" width="120" />
      <el-table-column align="center" label="预计发生成本(元)" width="160">
        <template #default="scope">
          {{ formatAmountText(scope.row.expectedCostAmount) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="备注" min-width="240" prop="remark" show-overflow-tooltip />
      <el-table-column align="center" label="是否启用" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.enabledFlag ? 'success' : 'info'">
            {{ scope.row.enabledFlag ? '启用' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" prop="createTime" width="180" />
      <el-table-column align="center" fixed="right" label="操作" width="160">
        <template #default="scope">
          <el-button
            v-hasPermi="['tjt:employee-year-cost-budget:update']"
            link
            type="primary"
            @click="openDialog('update', scope.row.id)"
          >
            编辑
          </el-button>
          <el-button
            v-hasPermi="['tjt:employee-year-cost-budget:delete']"
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle" width="620">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="120px">
      <el-form-item label="员工姓名" prop="employeeId">
        <el-select
          :model-value="formData.employeeId"
          class="!w-1/1"
          clearable
          filterable
          remote
          reserve-keyword
          placeholder="请输入员工姓名搜索"
          :remote-method="searchEmployees"
          :loading="employeeLoading"
          @change="handleEmployeeChange"
        >
          <el-option
            v-for="item in employeeOptions"
            :key="item.id"
            :label="item.officeName ? `${item.employeeName} / ${item.officeName}` : item.employeeName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="预算年度" prop="budgetYear">
        <el-date-picker
          v-model="formBudgetYearValue"
          class="!w-1/1"
          placeholder="请选择年度"
          type="year"
          value-format="YYYY"
        />
      </el-form-item>
      <el-form-item label="预计发生成本" prop="expectedCostAmount">
        <el-input-number
          v-model="formData.expectedCostAmount"
          :min="0"
          :precision="2"
          :step="1000"
          class="!w-1/1"
          controls-position="right"
        />
      </el-form-item>
      <el-form-item label="排序号" prop="sortNo">
        <el-input-number v-model="formData.sortNo" :min="0" :precision="0" class="!w-1/1" controls-position="right" />
      </el-form-item>
      <el-form-item label="是否启用" prop="enabledFlag">
        <el-switch v-model="formData.enabledFlag" active-text="启用" inactive-text="停用" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          :rows="3"
          maxlength="255"
          placeholder="请输入备注"
          show-word-limit
          type="textarea"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button :loading="formLoading" type="primary" @click="submitForm">保存</el-button>
      <el-button @click="dialogVisible = false">取消</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import type { FormRules } from 'element-plus'
import * as EmployeeApi from '@/api/tjt/employee'
import * as EmployeeYearCostBudgetApi from '@/api/tjt/employeeYearCostBudget'
import { EMPLOYEE_STATUS, formatAmountText } from '@/views/tjt/shared/planning'

defineOptions({ name: 'TjtEmployeeYearCostBudget' })

const message = useMessage()
const { t } = useI18n()

const loading = ref(false)
const formLoading = ref(false)
const employeeLoading = ref(false)
const total = ref(0)
const list = ref<EmployeeYearCostBudgetApi.EmployeeYearCostBudgetVO[]>([])
const employeeOptions = ref<EmployeeApi.EmployeeSimpleVO[]>([])
const queryFormRef = ref()
const formRef = ref()
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formType = ref<'create' | 'update'>('create')

const queryParams = reactive<EmployeeYearCostBudgetApi.EmployeeYearCostBudgetPageReqVO>({
  pageNo: 1,
  pageSize: 10,
  employeeId: undefined,
  employeeName: undefined,
  budgetYear: undefined,
  enabledFlag: undefined
})

const createFormData = (): EmployeeYearCostBudgetApi.EmployeeYearCostBudgetVO => ({
  employeeId: undefined as never,
  employeeName: '',
  budgetYear: new Date().getFullYear(),
  expectedCostAmount: 0,
  remark: '',
  sortNo: 0,
  enabledFlag: true
})

const formData = ref<EmployeeYearCostBudgetApi.EmployeeYearCostBudgetVO>(createFormData())

const queryBudgetYearValue = computed({
  get: () => (queryParams.budgetYear ? String(queryParams.budgetYear) : undefined),
  set: (value?: string) => {
    queryParams.budgetYear = value ? Number(value) : undefined
  }
})

const formBudgetYearValue = computed({
  get: () => (formData.value.budgetYear ? String(formData.value.budgetYear) : undefined),
  set: (value?: string) => {
    formData.value.budgetYear = value ? Number(value) : new Date().getFullYear()
  }
})

const formRules = reactive<FormRules>({
  employeeId: [{ required: true, message: '员工不能为空', trigger: 'change' }],
  budgetYear: [{ required: true, message: '预算年度不能为空', trigger: 'change' }],
  expectedCostAmount: [{ required: true, message: '预计发生成本不能为空', trigger: 'blur' }]
})

const ensureEmployeeOption = () => {
  if (!formData.value.employeeId || !formData.value.employeeName) {
    return
  }
  if (employeeOptions.value.some((item) => item.id === formData.value.employeeId)) {
    return
  }
  employeeOptions.value.push({
    id: formData.value.employeeId,
    employeeName: formData.value.employeeName
  })
}

const searchEmployees = async (keyword: string) => {
  employeeLoading.value = true
  try {
    employeeOptions.value = await EmployeeApi.getEmployeeSimpleList({
      keyword,
      status: EMPLOYEE_STATUS.active,
      enabledFlag: true
    })
    ensureEmployeeOption()
  } finally {
    employeeLoading.value = false
  }
}

const handleEmployeeChange = (employeeId?: number) => {
  const employee = employeeOptions.value.find((item) => item.id === employeeId)
  formData.value.employeeId = employeeId as never
  formData.value.employeeName = employee?.employeeName || ''
}

const getList = async () => {
  loading.value = true
  try {
    const data = await EmployeeYearCostBudgetApi.getEmployeeYearCostBudgetPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

const resetForm = () => {
  formData.value = createFormData()
  employeeOptions.value = []
  formRef.value?.resetFields()
}

const openDialog = async (type: 'create' | 'update', id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'create' ? '新增员工年度成本预算' : '编辑员工年度成本预算'
  formType.value = type
  resetForm()
  if (!id) {
    await searchEmployees('')
    return
  }
  formLoading.value = true
  try {
    formData.value = await EmployeeYearCostBudgetApi.getEmployeeYearCostBudget(id)
    ensureEmployeeOption()
  } finally {
    formLoading.value = false
  }
}

const submitForm = async () => {
  if (!formRef.value) {
    return
  }
  const valid = await formRef.value.validate()
  if (!valid) {
    return
  }
  formLoading.value = true
  try {
    if (formType.value === 'create') {
      await EmployeeYearCostBudgetApi.createEmployeeYearCostBudget(formData.value)
      message.success(t('common.createSuccess'))
    } else {
      await EmployeeYearCostBudgetApi.updateEmployeeYearCostBudget(formData.value)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    await getList()
  } finally {
    formLoading.value = false
  }
}

const handleDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await EmployeeYearCostBudgetApi.deleteEmployeeYearCostBudget(id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

onMounted(() => {
  getList()
})

onActivated(() => {
  getList()
})
</script>
