<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="outputYear">
        <el-date-picker
          v-model="queryOutputYearValue"
          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-leader-output:create']"
          plain
          type="primary"
          @click="openDialog('create')"
        >
          <Icon class="mr-5px" icon="ep:plus" />
          新增
        </el-button>
        <el-button
          v-hasPermi="['tjt:employee-year-leader-output:create']"
          plain
          type="success"
          @click="openGenerateDialog"
        >
          <Icon class="mr-5px" icon="ep:document-add" />
          按年度生成
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>
    <el-table v-loading="loading" :data="list">
      <el-table-column :index="getRowIndex" align="center" label="序号" type="index" width="88" />
      <el-table-column align="center" label="员工姓名" min-width="140" prop="employeeName" />
      <el-table-column align="center" label="产值年度" prop="outputYear" width="120" />
      <el-table-column align="center" label="所长考核产值(元)" width="170">
        <template #default="scope">
          {{ formatAmountText(scope.row.leaderOutputAmount) }}
        </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"
        :formatter="dateFormatter"
      />
      <el-table-column align="center" fixed="right" label="操作" width="160">
        <template #default="scope">
          <el-button
            v-hasPermi="['tjt:employee-year-leader-output:update']"
            link
            type="primary"
            @click="openDialog('update', scope.row.id)"
          >
            编辑
          </el-button>
          <el-button
            v-hasPermi="['tjt:employee-year-leader-output: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="outputYear">
        <el-date-picker
          v-model="formOutputYearValue"
          class="!w-1/1"
          placeholder="请选择年度"
          type="year"
          value-format="YYYY"
        />
      </el-form-item>
      <el-form-item label="所长考核产值" prop="leaderOutputAmount">
        <el-input-number
          v-model="formData.leaderOutputAmount"
          :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>

  <Dialog v-model="generateDialogVisible" title="按年度生成所长考核产值记录" width="560">
    <el-form
      ref="generateFormRef"
      v-loading="generateLoading"
      :model="generateFormData"
      :rules="generateFormRules"
      label-width="140px"
    >
      <el-form-item label="产值年度" prop="outputYear">
        <el-date-picker
          v-model="generateOutputYearValue"
          class="!w-1/1"
          placeholder="请选择年度"
          type="year"
          value-format="YYYY"
        />
      </el-form-item>
      <el-form-item label="默认所长考核产值" prop="leaderOutputAmount">
        <el-input-number
          v-model="generateFormData.leaderOutputAmount"
          :min="0"
          :precision="2"
          :step="1000"
          class="!w-1/1"
          controls-position="right"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button :loading="generateLoading" type="primary" @click="submitGenerateForm">确认生成</el-button>
      <el-button @click="generateDialogVisible = 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 EmployeeYearLeaderOutputApi from '@/api/tjt/employeeYearLeaderOutput'
import { dateFormatter } from '@/utils/formatTime'
import { formatAmountText } from '@/views/tjt/shared/planning'

defineOptions({ name: 'TjtEmployeeYearLeaderOutput' })

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

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

const queryParams = reactive<EmployeeYearLeaderOutputApi.EmployeeYearLeaderOutputPageReqVO>({
  pageNo: 1,
  pageSize: 10,
  employeeId: undefined,
  employeeName: undefined,
  outputYear: undefined,
  enabledFlag: undefined
})

const getRowIndex = (index: number) =>
  (queryParams.pageNo - 1) * queryParams.pageSize + index + 1

const createFormData = (): EmployeeYearLeaderOutputApi.EmployeeYearLeaderOutputVO => ({
  employeeId: undefined as never,
  employeeName: '',
  outputYear: new Date().getFullYear(),
  leaderOutputAmount: 0,
  remark: '',
  sortNo: 0,
  enabledFlag: true
})

const formData = ref<EmployeeYearLeaderOutputApi.EmployeeYearLeaderOutputVO>(createFormData())
const generateFormData = reactive<EmployeeYearLeaderOutputApi.EmployeeYearLeaderOutputGenerateReqVO>({
  outputYear: new Date().getFullYear(),
  leaderOutputAmount: 0
})

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

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

const generateOutputYearValue = computed({
  get: () => (generateFormData.outputYear ? String(generateFormData.outputYear) : undefined),
  set: (value?: string) => {
    generateFormData.outputYear = value ? Number(value) : new Date().getFullYear()
  }
})

const formRules = reactive<FormRules>({
  employeeId: [{ required: true, message: '所长不能为空', trigger: 'change' }],
  outputYear: [{ required: true, message: '产值年度不能为空', trigger: 'change' }],
  leaderOutputAmount: [{ required: true, message: '所长考核产值不能为空', trigger: 'blur' }]
})

const generateFormRules = reactive<FormRules>({
  outputYear: [{ required: true, message: '产值年度不能为空', trigger: 'change' }],
  leaderOutputAmount: [{ 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,
      enabledFlag: true,
      officeLeaderFlag: 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 EmployeeYearLeaderOutputApi.getEmployeeYearLeaderOutputPage(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 EmployeeYearLeaderOutputApi.getEmployeeYearLeaderOutput(id)
    ensureEmployeeOption()
  } finally {
    formLoading.value = false
  }
}

const openGenerateDialog = () => {
  generateFormData.outputYear = queryParams.outputYear || new Date().getFullYear()
  generateFormData.leaderOutputAmount = 0
  generateDialogVisible.value = true
  generateFormRef.value?.clearValidate()
}

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 EmployeeYearLeaderOutputApi.createEmployeeYearLeaderOutput(formData.value)
      message.success(t('common.createSuccess'))
    } else {
      await EmployeeYearLeaderOutputApi.updateEmployeeYearLeaderOutput(formData.value)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    await getList()
  } finally {
    formLoading.value = false
  }
}

const submitGenerateForm = async () => {
  if (!generateFormRef.value) {
    return
  }
  const valid = await generateFormRef.value.validate()
  if (!valid) {
    return
  }
  generateLoading.value = true
  try {
    const data = await EmployeeYearLeaderOutputApi.generateEmployeeYearLeaderOutput(generateFormData)
    if (data.createdCount > 0) {
      message.success(
        `成功为 ${data.outputYear} 年度生成 ${data.createdCount} 名所长的考核产值记录，已跳过 ${data.skippedCount} 条重复记录。`
      )
    } else {
      message.info(`${data.outputYear} 年度没有需要新增的所长考核产值记录，已跳过 ${data.skippedCount} 条重复记录。`)
    }
    generateDialogVisible.value = false
    queryParams.outputYear = data.outputYear
    queryParams.pageNo = 1
    await getList()
  } finally {
    generateLoading.value = false
  }
}

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

let activatedOnce = false

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

onActivated(() => {
  // KeepAlive 首次挂载也会触发 onActivated，跳过首轮避免重复请求列表。
  if (!activatedOnce) {
    activatedOnce = true
    return
  }
  getList()
})
</script>
