<template>
  <ContentWrap>
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px"
      label-width="88px"
    >
      <el-form-item label="年度" prop="kYear">
        <el-date-picker
          v-model="queryYearValue"
          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:year-k-value: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="年度" prop="kYear" width="120" />
      <el-table-column align="center" label="K值" width="120">
        <template #default="scope">
          {{ formatPercentText(scope.row.kValue, 2) }}
        </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:year-k-value:update']"
            link
            type="primary"
            @click="openDialog('update', scope.row.id)"
          >
            编辑
          </el-button>
          <el-button
            v-hasPermi="['tjt:year-k-value: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="520">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="100px">
      <el-form-item label="年度" prop="kYear">
        <el-date-picker
          v-model="formYearValue"
          class="!w-1/1"
          placeholder="请选择年度"
          type="year"
          value-format="YYYY"
        />
      </el-form-item>
      <el-form-item label="K值(%)" prop="kValue">
        <el-input-number
          v-model="kValuePercent"
          :max="100"
          :min="0"
          :precision="2"
          :step="0.1"
          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 YearKValueApi from '@/api/tjt/yearKValue'
import { formatPercentText, fromPercentValue, toPercentValue } from '@/views/tjt/shared/planning'

defineOptions({ name: 'TjtYearKValue' })

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

const loading = ref(false)
const formLoading = ref(false)
const total = ref(0)
const list = ref<YearKValueApi.YearKValueVO[]>([])
const queryFormRef = ref()
const formRef = ref()
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formType = ref<'create' | 'update'>('create')

const queryParams = reactive<YearKValueApi.YearKValuePageReqVO>({
  pageNo: 1,
  pageSize: 10,
  kYear: undefined,
  enabledFlag: undefined
})

const createFormData = (): YearKValueApi.YearKValueVO => ({
  kYear: new Date().getFullYear(),
  kValue: 0.4,
  enabledFlag: true,
  remark: ''
})

const formData = ref<YearKValueApi.YearKValueVO>(createFormData())

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

const formYearValue = computed({
  get: () => (formData.value.kYear ? String(formData.value.kYear) : undefined),
  set: (value?: string) => {
    formData.value.kYear = value ? Number(value) : undefined
  }
})

const kValuePercent = computed({
  get: () => toPercentValue(formData.value.kValue) ?? 0,
  set: (value?: number) => {
    formData.value.kValue = fromPercentValue(value) ?? undefined
  }
})

const formRules = reactive<FormRules>({
  kYear: [{ required: true, message: '年度不能为空', trigger: 'change' }],
  kValue: [{ required: true, message: 'K值不能为空', trigger: 'change' }]
})

const getList = async () => {
  loading.value = true
  try {
    const data = await YearKValueApi.getYearKValuePage(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()
  formRef.value?.clearValidate()
}

const openDialog = async (type: 'create' | 'update', id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'create' ? '新增年度K值' : '编辑年度K值'
  formType.value = type
  await nextTick()
  resetForm()
  if (!id) {
    return
  }
  formLoading.value = true
  try {
    formData.value = await YearKValueApi.getYearKValue(id)
    formRef.value?.clearValidate()
  } finally {
    formLoading.value = false
  }
}

const buildSavePayload = (): YearKValueApi.YearKValueVO => ({
  id: formData.value.id,
  kYear: Number(formData.value.kYear),
  kValue: Number(formData.value.kValue),
  remark: formData.value.remark?.trim() || '',
  enabledFlag: formData.value.enabledFlag ?? true
})

const submitForm = async () => {
  if (!formRef.value) {
    return
  }
  const valid = await formRef.value.validate()
  if (!valid) {
    return
  }
  formLoading.value = true
  try {
    const payload = buildSavePayload()
    if (formType.value === 'create') {
      await YearKValueApi.createYearKValue(payload)
      message.success(t('common.createSuccess'))
    } else {
      await YearKValueApi.updateYearKValue(payload)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    await getList()
  } finally {
    formLoading.value = false
  }
}

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

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

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