<script setup lang="ts">
import { ref, reactive, nextTick, computed } 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 {
  PerformanceTarget_List,
  PerformanceTarget_Add,
  PerformanceTarget_Edit,
  PerformanceTarget_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_operator: '≥',
  T_assess_points: '',
  T_base: '',
  T_post: '',
  T_perf: ''
})

// 运算符选项
const operatorOptions = [
  { label: '≥', value: '≥' },
  { label: '<', value: '<' }
]

// 表单验证规则
const rules = reactive<FormRules>({
  T_name: [{ required: true, message: '请输入工资级别', trigger: 'blur' }],
  T_operator: [{ required: true, message: '请选择运算符', trigger: 'blur' }],
  T_assess_points: [
    { required: true, message: '请输入月考核工作量', trigger: 'blur' },
    { pattern: /^\d+$/, message: '请输入正整数', trigger: 'blur' }
  ],
  T_base: [
    { required: true, message: '请输入无责底薪', trigger: 'blur' },
    { pattern: /^\d+(\.\d+)?$/, message: '请输入正确的金额格式', trigger: 'blur' }
  ],
  T_post: [
    { required: true, message: '请输入补助', trigger: 'blur' },
    { pattern: /^\d+(\.\d+)?$/, message: '请输入正确的金额格式', trigger: 'blur' }
  ],
  T_perf: [
    { required: true, message: '请输入绩效金额', trigger: 'blur' },
    { pattern: /^\d+(\.\d+)?$/, message: '请输入正确的金额格式', trigger: 'blur' }
  ]
})

// 表格列配置
const columns: ColumnProps[] = [
  { type: 'index', label: '序号', width: 80 },
  { prop: 'T_name', label: '工资级别' },
  { 
    prop: 'T_points_display', 
    label: '月考核工作量(个)', 
    align: 'center',
    name: 'T_points_display'
  },
  { prop: 'T_base', label: '无责底薪(元)',  align: 'center' },
  { prop: 'T_post', label: '补助(元)',  align: 'center' },
  { prop: 'T_perf', label: '绩效金额(元)',  align: 'center' },
  { 
    prop: 'total_income', 
    label: '总收入(元)', 
    width: 120, 
    align: 'center',
    name: 'total_income'
  },
  { prop: 'operation', label: '操作', width: 160, fixed: 'right' }
]

// 打开新增/编辑抽屉
const openDrawer = (type: 'add' | 'edit', row?: any) => {
  isNew.value = type === 'add'
  if (type === 'edit' && row) {
    form.value = {
      Id: row.Id,
      T_name: row.T_name,
      T_operator: row.T_operator,
      T_assess_points: (row.T_assess_points || '').toString(),
      T_base: row.T_base.toString(),
      T_post: row.T_post.toString(),
      T_perf: row.T_perf.toString()
    }
  } else {
    form.value = {
      Id: '',
      T_name: '',
      T_operator: '≥',
      T_assess_points: '',
      T_base: '',
      T_post: '',
      T_perf: ''
    }
  }
  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_operator: form.value.T_operator,
          T_assess_points: parseInt(form.value.T_assess_points),
          T_base: parseFloat(form.value.T_base),
          T_post: parseFloat(form.value.T_post),
          T_perf: parseFloat(form.value.T_perf)
        }

        let res: any
        if (isNew.value) {
          res = await PerformanceTarget_Add(params)
        } else {
          res = await PerformanceTarget_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 deletePerformanceTarget = (row: any) => {
  ElMessageBox.confirm('您确定要删除这个绩效指标吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const res: any = await PerformanceTarget_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()
}

// 计算底薪（无责底薪 + 补助）
const baseSalary = computed(() => {
  const base = parseFloat(form.value.T_base) || 0
  const post = parseFloat(form.value.T_post) || 0
  const result = base + post
  return result > 0 ? result.toFixed(2) : '0.00'
})

// 计算总收入（无责底薪 + 补助 + 绩效金额）
const totalIncome = computed(() => {
  const base = parseFloat(form.value.T_base) || 0
  const post = parseFloat(form.value.T_post) || 0
  const perf = parseFloat(form.value.T_perf) || 0
  const result = base + post + perf
  return result > 0 ? result.toFixed(2) : '0.00'
})
</script>

<template>
  <div class="performance-target">
    <TableBase
      ref="TableRef"
      :columns="columns"
      :requestApi="PerformanceTarget_List"
      :initParam="initParam"
    >
      <template #table-header>
        <div class="input-suffix">
          <el-row :gutter="20" style="margin-bottom: 0" align="middle">
            <el-col :span="6">
              <div style="display: flex; align-items: center;">
                <span style="white-space: nowrap; margin-right: 8px;">工资级别：</span>
                <el-input
                  v-model="initParam.T_name"
                  placeholder="按工资级别搜索"
                  clearable
                  @change="searchInfo"
                  @keyup.enter="searchInfo"
                />
              </div>
            </el-col>
            <el-col :span="3">
              <el-button type="primary" @click="searchInfo">搜索</el-button>
            </el-col>
            <el-col :span="3" :push="12">
              <el-button type="primary" :icon="Plus" @click="openDrawer('add')">
                添加
              </el-button>
            </el-col>
          </el-row>
        </div>
      </template>

      <template #T_points_display="{ row }">
        <span>{{ row.T_operator }}{{ row.T_assess_points }}</span>
      </template>

      <template #total_income="{ row }">
        <span style="color: #E6A23C; font-weight: bold;">
          {{ Math.round(parseFloat(row.T_base) + parseFloat(row.T_post) + parseFloat(row.T_perf)) }}
        </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="deletePerformanceTarget(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_assess_points">
          <el-row :gutter="10">
            <el-col :span="6">
              <el-select v-model="form.T_operator" placeholder="请选择运算符">
                <el-option
                  v-for="item in operatorOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-col>
            <el-col :span="18">
              <el-input
                v-model="form.T_assess_points"
                placeholder="请输入月考核工作量"
                maxlength="10"
              >
                <template #append>
                  <span>个</span>
                </template>
              </el-input>
            </el-col>
          </el-row>
        </el-form-item>
        
        <el-form-item label="无责底薪" prop="T_base">
          <el-input
            v-model="form.T_base"
            placeholder="请输入无责底薪"
            maxlength="20"
          >
            <template #append>
              <span>元</span>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="补助" prop="T_post">
          <el-input
            v-model="form.T_post"
            placeholder="请输入补助金额"
            maxlength="20"
          >
            <template #append>
              <span>元</span>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="底薪" label-width="120px">
          <el-input
            :value="baseSalary"
            readonly
            disabled
            placeholder="自动计算"
          >
            <template #append>
              <span>元</span>
            </template>
          </el-input>
          <div style="font-size: 12px; color: #909399; margin-top: 4px;">
            底薪 = 无责底薪 + 补助
          </div>
        </el-form-item>
        
        <el-form-item label="绩效金额" prop="T_perf">
          <el-input
            v-model="form.T_perf"
            placeholder="请输入绩效金额"
            maxlength="20"
          >
            <template #append>
              <span>元</span>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="总收入" label-width="120px">
          <el-input
            :value="totalIncome"
            readonly
            disabled
            placeholder="自动计算"
          >
            <template #append>
              <span>元</span>
            </template>
          </el-input>
          <div style="font-size: 12px; color: #909399; margin-top: 4px;">
            总收入 = 无责底薪 + 补助 + 绩效金额
          </div>
        </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-target {
  @include f-direction;
  
  .input-suffix {
    width: 100%;
    
    .inline-flex {
      white-space: nowrap;
    }
    
    .btn {
      display: flex;
      justify-content: flex-end;
      align-items: center;
    }
  }
}

.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>