<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import { GlobalStore } from '@/stores/index'
import Drawer from '@/components/Drawer/index.vue'
import TableBase from '@/components/TableBase/index.vue'
import { Edit, Delete, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { ColumnProps } from '@/components/TableBase/interface/index'
import { useTablePublic } from '@/hooks/useTablePublic'
import {
  PerformancePoints_List,
  PerformancePoints_Add,
  PerformancePoints_Edit,
  PerformancePoints_Del
} from '@/api/performance/index'

const isNew = ref(true)
const formLabelWidth = ref('120px')
const ruleFormRef = ref<FormInstance>()
const drawerRef = ref<InstanceType<typeof Drawer> | null>(null)
const TableRef = ref<InstanceType<typeof TableBase> | null>(null)
const { resetForm, globalStore, searchOnTableList, updateOnTableList } = useTablePublic()

// 初始化查询参数
const initParam = reactive({
  User_tokey: globalStore.GET_User_tokey,
  T_name: ''
})

// 表单数据
const form = ref({
  Id: '',
  T_name: '',
  T_points: '',
  T_remark: ''
})

// 表单验证规则
const rules = reactive<FormRules>({
  T_name: [{ required: true, message: '请输入绩效点名称', trigger: 'blur' }],
  T_points: [
    { required: true, message: '请输入绩效点数量', trigger: 'blur' },
    {
      pattern: /^(\d+(\.\d+)?|\d+\/\d+)$/,
      message: '请输入正确的数字或分数格式（如：10 或 3/4）',
      trigger: 'blur'
    }
  ]
})

// 表格列配置
const columns: ColumnProps[] = [
  { type: 'index', label: '序号', width: 80 },
  { prop: 'T_name', label: '名称', minWidth: 150 },
  {
    prop: 'T_points_display',
    label: '数量',
    width: 120,
    align: 'center',
    name: 'T_points_display'
  },
  { prop: 'T_remark', label: '备注', minWidth: 200, ellipsis: true },
  { prop: 'operation', label: '操作', width: 160, fixed: 'right' }
]

// 打开新增/编辑抽屉
const openDrawer = (type: 'add' | 'edit', row?: any) => {
  isNew.value = type === 'add'
  if (type === 'edit' && row) {
    // 根据分母处理绩效点数量的显示
    let pointsValue = ''
    if (row.T_points_denominator && row.T_points_denominator !== 1) {
      pointsValue = `${row.T_points_numerator}/${row.T_points_denominator}`
    } else {
      pointsValue = row.T_points_numerator.toString()
    }

    form.value = {
      Id: row.Id,
      T_name: row.T_name,
      T_points: pointsValue,
      T_remark: row.T_remark || ''
    }
  } else {
    form.value = {
      Id: '',
      T_name: '',
      T_points: '',
      T_remark: ''
    }
  }
  drawerRef.value?.openDrawer()
}

// 抽屉关闭回调
const callbackDrawer = (done: () => void) => {
  done()
  resetForm(ruleFormRef.value)
}

// 提交表单
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async valid => {
    if (valid) {
      try {
        const params = {
          User_tokey: globalStore.GET_User_tokey,
          T_name: form.value.T_name,
          T_points: form.value.T_points,
          T_remark: form.value.T_remark
        }

        let res: any
        if (isNew.value) {
          res = await PerformancePoints_Add(params)
        } else {
          res = await PerformancePoints_Edit({
            ...params,
            T_id: form.value.Id
          })
        }

        if (res.Code === 200) {
          ElMessage.success(isNew.value ? '添加成功！' : '修改成功！')
          drawerRef.value?.closeDrawer()
          nextTick(() => {
            updateTableList()
          })
        }
      } catch (error) {
        console.error('提交失败:', error)
      }
    }
  })
}

// 删除绩效点
const deletePerformancePoint = (row: any) => {
  ElMessageBox.confirm('您确定要删除这个绩效点吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const res: any = await PerformancePoints_Del({
          User_tokey: globalStore.GET_User_tokey,
          T_id: row.Id
        })
        if (res.Code === 200) {
          ElMessage.success('删除成功！')
          nextTick(() => {
            updateTableList()
          })
        }
      } catch (error) {
        console.error('删除失败:', error)
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 搜索功能
const searchInfo = () => {
  TableRef.value?.searchTable()
}

// 更新表格数据
const updateTableList = () => {
  TableRef.value?.getTableList()
}
</script>

<template>
  <div class="performance-points">
    <TableBase ref="TableRef" :columns="columns" :requestApi="PerformancePoints_List" :initParam="initParam">
      <template #table-header>
        <div class="input-suffix">
          <el-row :gutter="20" style="margin-bottom: 0">
            <el-col :xl="12" :lg="12" :md="12">
              <span class="inline-flex items-center">名称：</span>
              <el-input
                v-model="initParam.T_name"
                type="text"
                class="w-50 m-2"
                placeholder="按名称搜索"
                @change="searchOnTableList(TableRef)"
              />
              <el-button type="primary" @click="searchOnTableList(TableRef)">搜索</el-button>
            </el-col>

            <el-col :xl="8" :md="8" class="btn">
              <el-button type="primary" @click="openDrawer('add')">添加</el-button>
            </el-col>
          </el-row>
        </div>
      </template>

      <template #T_points_display="{ row }">
        <span v-if="row.T_points_denominator && row.T_points_denominator !== 1">
          {{ row.T_points_numerator }}/{{ row.T_points_denominator }}
        </span>
        <span v-else>
          {{ row.T_points_numerator }}
        </span>
      </template>

      <template #right="{ row }">
        <el-button link type="primary" size="small" :icon="Edit" @click="openDrawer('edit', row)"> 编辑 </el-button>
        <el-button link type="danger" size="small" :icon="Delete" @click="deletePerformancePoint(row)">
          删除
        </el-button>
      </template>
    </TableBase>

    <!-- 新增/编辑抽屉 -->
    <Drawer ref="drawerRef" :handleClose="callbackDrawer">
      <template #header="{ params }">
        <h4 :id="params.titleId" :class="params.titleClass">{{ isNew ? '添加' : '编辑' }} - 绩效点管理</h4>
      </template>

      <el-form ref="ruleFormRef" :model="form" :rules="rules" :label-width="formLabelWidth">
        <el-form-item label="名称" prop="T_name">
          <el-input v-model="form.T_name" placeholder="请输入名称" maxlength="50" show-word-limit />
        </el-form-item>

        <el-form-item label="数量" prop="T_points">
          <el-input v-model="form.T_points" placeholder="请输入绩效点数量（如：10 或 3/4）" maxlength="20">
            <template #append>
              <span>个</span>
            </template>
          </el-input>
          <div class="form-tip">支持整数（如：10）或分数格式（如：3/4）</div>
        </el-form-item>

        <el-form-item label="备注" prop="T_remark">
          <el-input
            v-model="form.T_remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item>
          <div class="form-buttons">
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              {{ isNew ? '添加' : '修改' }}
            </el-button>
            <el-button @click="drawerRef?.closeDrawer()">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </Drawer>
  </div>
</template>

<style scoped lang="scss">
@import '@/styles/var.scss';

.performance-points {
  @include f-direction;
  .input-suffix {
    width: 100%;
    .inline-flex {
      white-space: nowrap;
    }
    .btn {
      display: flex;
      justify-content: flex-end;
      align-items: center;
    }
    .w-50 {
      width: 12.5rem;
    }
  }
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.4;
}

.form-buttons {
  display: flex;
  justify-content: center;
  gap: 12px;
  margin-top: 20px;

  .el-button {
    min-width: 80px;
  }
}

:deep(.el-drawer__body) {
  padding: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-input-group__append) {
  background-color: #f5f7fa;
  border-left: none;
  color: #909399;
}
</style>