<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="所属公司" prop="companyId">
        <el-select
          v-model="queryParams.companyId"
          filterable
          placeholder="请选择所属公司"
          class="!w-240px"
        >
          <el-option
            v-for="company in companyOptions"
            :key="company.id"
            :label="company.name"
            :value="company.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['hr:insurance-month-record:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增社保核算
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="标题" align="center" prop="title" width="200">
        <template #default="scope">
          <el-button type="primary" link @click="openDetail(scope.row)">{{
            scope.row.title
          }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="所属公司" align="center" prop="companyName" />
      <el-table-column label="参保人数" align="center" prop="num" />
      <el-table-column label="个人社保" align="center" prop="personalInsuranceAmount" />
      <el-table-column label="公司社保" align="center" prop="corporateInsuranceAmount" />
      <el-table-column label="个人公积金" align="center" prop="personalProvidentFundAmount" />
      <el-table-column label="公司公积金" align="center" prop="corporateProvidentFundAmount" />
      <el-table-column label="本月停保人数" align="center" prop="stopNum" />

      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <!-- <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['hr:insurance-month-record:update']"
          >
            编辑
          </el-button> -->
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.irecordId)"
            v-hasPermi="['hr:insurance-month-record:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <InsuranceMonthRecordForm ref="formRef" @success="getList" />
  <!-- 详情抽屉弹窗 -->
  <el-drawer
    v-model="drawerVisible"
    title="社保详情"
    size="70%"
    :before-close="handleClose"
    :with-header="false"
  >
    <div>
      <el-card class="my-card">
        <h3>{{ currentRow.title }}</h3>
        <!-- <p>
          参保人数: <el-button type="primary" link>{{ currentRow.num }}</el-button>
        </p>
        <p>
          个人社保:
          <el-button type="primary" link>{{ currentRow.personalInsuranceAmount }}</el-button>
        </p>
        <p>
          公司社保:
          <el-button type="primary" link>{{ currentRow.corporateInsuranceAmount }}</el-button>
        </p>
        <p>
          个人公积金:
          <el-button type="primary" link>{{ currentRow.personalProvidentFundAmount }}</el-button>
        </p>
        <p>
          公司公积金:
          <el-button type="primary" link>{{ currentRow.corporateProvidentFundAmount }}</el-button>
        </p>
        <p>
          本月停保人数: <el-button type="primary" link>{{ currentRow.stopNum }}</el-button>
        </p> -->
        <el-table :data="[currentRow]" border>
          <el-table-column prop="num" label="参保人数" width="120">
            <template #default="scope">
              <el-button v-if="scope.row.num && scope.row.num > 0" type="primary" link>{{
                scope.row.num
              }}</el-button>
              <span class="c_grid" v-else>{{ scope.row.num }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="personalInsuranceAmount" label="个人社保" width="120">
            <template #default="scope">
              <el-button
                v-if="scope.row.personalInsuranceAmount && scope.row.personalInsuranceAmount > 0"
                type="primary"
                link
                >{{ scope.row.personalInsuranceAmount }}</el-button
              >
              <span class="c_grid" v-else>{{ scope.row.personalInsuranceAmount }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="corporateInsuranceAmount" label="公司社保" width="120">
            <template #default="scope">
              <el-button
                v-if="scope.row.corporateInsuranceAmount && scope.row.corporateInsuranceAmount > 0"
                type="primary"
                link
                >{{ scope.row.corporateInsuranceAmount }}</el-button
              >
              <span class="c_grid" v-else>{{ scope.row.corporateInsuranceAmount }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="personalProvidentFundAmount" label="个人公积金" width="120">
            <template #default="scope">
              <el-button
                v-if="
                  scope.row.personalProvidentFundAmount && scope.row.personalProvidentFundAmount > 0
                "
                type="primary"
                link
                >{{ scope.row.personalProvidentFundAmount }}</el-button
              >
              <span class="c_grid" v-else>{{ scope.row.personalProvidentFundAmount }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="corporateProvidentFundAmount" label="公司公积金" width="120">
            <template #default="scope">
              <el-button
                v-if="
                  scope.row.corporateProvidentFundAmount &&
                  scope.row.corporateProvidentFundAmount > 0
                "
                type="primary"
                link
                >{{ scope.row.corporateProvidentFundAmount }}</el-button
              >
              <span class="c_grid" v-else>{{ scope.row.corporateProvidentFundAmount }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="stopNum" label="本月停保人数" width="120">
            <template #default="scope">
              <el-button v-if="scope.row.stopNum && scope.row.stopNum > 0" type="primary" link>{{
                scope.row.stopNum
              }}</el-button>
              <span class="c_grid" v-else>{{ scope.row.stopNum }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!-- 动态表格 -->
      <el-card class="mt-20px">
        <el-button type="primary" plain @click="openAddEmployeeDialog">
          <Icon icon="ep:plus" class="mr-5px" /> 添加参保人员
        </el-button>
        <el-table
          v-loading="tableLoading"
          :data="tableData"
          :stripe="true"
          :show-overflow-tooltip="true"
          height="calc(100vh - 400px)"
        >
          <el-table-column
            v-for="item in fieldList"
            :key="item.fieldName"
            :prop="item.fieldName"
            :label="item.name"
            :width="item.width"
            :fixed="item.fixed"
          />
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="scope">
              <el-button type="danger" link @click="handleStopInsure(scope.row)"
                >停止参保</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 表格分页 -->
        <Pagination
          :total="tableTotal"
          v-model:page="tablePageNo"
          v-model:limit="tablePageSize"
          @pagination="handleTablePagination"
        />
      </el-card>
    </div>
  </el-drawer>
  <!-- 添加参保人员弹窗 -->
  <el-dialog
    v-model="addEmployeeDialogVisible"
    title="选择参保人员"
    width="500px"
    :before-close="handleAddEmployeeClose"
  >
    <el-form ref="addEmployeeFormRef" :model="addEmployeeForm" label-width="100px">
      <el-form-item label="参保人员" prop="employeeId" required>
        <el-select
          v-model="addEmployeeForm.employeeId"
          filterable
          placeholder="请选择参保人员"
          style="width: 100%"
          multiple
        >
          <el-option
            v-for="employee in employeeOptions"
            :key="employee.id"
            :label="employee.employeeName"
            :value="employee.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleAddEmployeeClose">取消</el-button>
      <el-button type="primary" @click="handleAddEmployeeConfirm">确认</el-button>
    </template>
  </el-dialog>
  <!-- 用户选择弹窗 -->
  <EmployeeSelectForm ref="userSelectFormRef" @confirm="handleUserSelectConfirm" />
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { InsuranceMonthRecordApi, InsuranceMonthRecord } from '@/api/hr/insurancemonthrecord'
import { InsuranceSchemeApi } from '@/api/hr/insurancescheme'
import { EmployeeApi } from '@/api/hr/employee'
import InsuranceMonthRecordForm from './InsuranceMonthRecordForm.vue'
import * as DeptApi from '@/api/system/dept'
import { EmployeeVO } from '@/api/hr/employee'
import { CategoryVO } from '@/api/bpm/category'

/** 每月社保记录 列表 */
defineOptions({ name: 'HrInsuranceMonthRecord' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<InsuranceMonthRecord[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  title: undefined,
  companyId: undefined,
  year: undefined,
  month: undefined,
  num: undefined,
  status: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
// 详情表格数据与分页
const tableData = ref([])
const tableLoading = ref(false)
const tablePageNo = ref(1)
const tablePageSize = ref(10)
const tableTotal = ref(0)
const companyOptions = ref([])

// 获取参保人员选项
const getCompanyOptions = async () => {
  try {
    const deptData = await DeptApi.getCompanyList()
    companyOptions.value = deptData
  } catch (error) {
    console.error('获取人员列表失败', error)
  }
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await InsuranceMonthRecordApi.queryInsuranceRecordList(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 formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}
// 打开社保表页面
const drawerVisible = ref(false)
const currentRow = ref({})
/**
 * 表头字段
 */
const fieldList = ref([
  {
    fieldName: 'employeeName',
    name: '姓名',
    width: 140,
    fixed: 'left'
  },
  {
    fieldName: 'workNo',
    name: '工号',
    width: 80
  },
  {
    fieldName: 'deptName',
    name: '部门',
    width: 80
  },
  {
    fieldName: 'entryTime',
    name: '入职日期',
    width: 180
  },
  {
    fieldName: 'mobile',
    name: '手机号码',
    width: 140
  },
  {
    fieldName: 'city',
    name: '参保城市',
    width: 80
  },
  {
    fieldName: 'schemeName',
    name: '参保方案',
    width: 120
  },
  {
    fieldName: 'personalInsuranceAmount',
    name: '个人社保费',
    width: 120
  },
  {
    fieldName: 'corporateInsuranceAmount',
    name: '公司社保费',
    width: 120
  },
  {
    fieldName: 'personalProvidentFundAmount',
    name: '个人公积金费',
    width: 120
  },
  {
    fieldName: 'corporateProvidentFundAmount',
    name: '公司公积金费',
    width: 120
  }
])
const openDetail = async (row) => {
  const res = await InsuranceSchemeApi.queryInsuranceRecordList(row.irecordId)
  currentRow.value = res
  currentRow.value.irecordId = row.irecordId
  drawerVisible.value = true
  // 重置分页并加载表格数据
  tablePageNo.value = 1
  await getTableData()
}
// 获取表格数据
const getTableData = async () => {
  tableLoading.value = true
  try {
    const res = await InsuranceSchemeApi.queryInsurancePageList({
      irecordId: currentRow.value.irecordId,
      page: tablePageNo.value,
      limit: tablePageSize.value,
      status: 1
    })
    tableData.value = res.list
    tableTotal.value = res.total
  } finally {
    tableLoading.value = false
  }
}
// 表格分页事件
const handleTablePagination = () => {
  getTableData()
}

const handleClose = () => {
  drawerVisible.value = false
}

// 添加参保人员弹窗
const addEmployeeDialogVisible = ref(false)
const addEmployeeFormRef = ref()
const addEmployeeForm = reactive({
  employeeId: undefined
})
const employeeOptions = ref([])
const userSelectFormRef = ref()
const selectedStartUsers = ref<EmployeeVO[]>([])
const currentSelectType = ref<'start' | 'manager'>('start')
// 创建本地数据副本
const modelData = defineModel<any>()
const props = defineProps({
  userList: {
    type: Array,
    required: true
  }
})
// 初始化选中的用户
// watch(
//   () => modelData.value,
//   (newVal) => {
//     if (newVal.startUserIds?.length) {
//       selectedStartUsers.value = props.userList.filter((user: EmployeeVO) =>
//         newVal.startUserIds.includes(user.id)
//       ) as EmployeeVO[]
//     } else {
//       selectedStartUsers.value = []
//     }
//   },
//   {
//     immediate: true
//   }
// )
// 打开添加参保人员弹窗
const openAddEmployeeDialog = async () => {
  // addEmployeeDialogVisible.value = true
  // 获取可选人员列表
  // await getEmployeeOptions()
  currentSelectType.value = 'start'
  userSelectFormRef.value.open(0, selectedStartUsers.value)
}
/** 处理用户选择确认 */
const handleUserSelectConfirm = async (_, users: EmployeeVO[]) => {
  // if (currentSelectType.value === 'start') {
  //   modelData.value = {
  //     ...modelData.value,
  //     startUserIds: users.map((u) => u.id)
  //   }
  const userIds = users.map((u) => u.id)
  console.log(userIds)

  try {
    // await addEmployeeFormRef.value.validate()
    const params = {
      irecordId: currentRow.value.irecordId,
      employeeIds: users.map((u) => u.id)
    }
    await InsuranceSchemeApi.addInsuranceEmp(params)
    message.success('添加成功')
    addEmployeeDialogVisible.value = false
    // 刷新表格数据
    await getTableData()
  } catch (error) {
    console.error('添加参保人员失败', error)
  }

  // } else {
  //   modelData.value = {
  //     ...modelData.value,
  //     managerUserIds: users.map((u) => u.id)
  //   }
  // }
}

// 获取参保人员选项
const getEmployeeOptions = async () => {
  try {
    const res = await await EmployeeApi.getSimpleUserListByCompanyId(currentRow.value.companyId)
    employeeOptions.value = res
  } catch (error) {
    console.error('获取人员列表失败', error)
  }
}

// 确认添加参保人员
const handleAddEmployeeConfirm = async () => {
  try {
    await addEmployeeFormRef.value.validate()
    const params = {
      irecordId: currentRow.value.irecordId,
      employeeIds: addEmployeeForm.employeeId
    }
    await InsuranceSchemeApi.addInsuranceEmp(params)
    message.success('添加成功')
    addEmployeeDialogVisible.value = false
    // 刷新表格数据
    await getTableData()
  } catch (error) {
    console.error('添加参保人员失败', error)
  }
}

// 关闭添加参保人员弹窗
const handleAddEmployeeClose = () => {
  addEmployeeDialogVisible.value = false
  addEmployeeFormRef.value?.resetFields()
}
const handleStopInsure = async (row) => {
  try {
    // 停止参保的二次确认
    await message.confirm('是否确认停止参保？')
    // 停止参保
    const ids = []
    ids.push(row.iempRecordId)
    console.log(ids)
    await InsuranceMonthRecordApi.stop(ids.join(','))
    message.success(t('common.updateSuccess'))

    // 刷新列表
    await getTableData()
  } catch {}
}
/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await InsuranceMonthRecordApi.deleteInsuranceMonthRecord(id)
    message.success(t('common.delSuccess'))
    currentRow.value = {}
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除每月社保记录 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await InsuranceMonthRecordApi.deleteInsuranceMonthRecordList(checkedIds.value)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: InsuranceMonthRecord[]) => {
  checkedIds.value = records.map((item) => item.id)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await InsuranceMonthRecordApi.exportInsuranceMonthRecord(queryParams)
    download.excel(data, '每月社保记录.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
/** 初始化 **/
onMounted(() => {
  getList()
  // 获取可选人员列表
  getCompanyOptions()
})
</script>
<style scoped>
.my-card p {
  font-size: 14px;
  line-height: 25px;
  color: #888;
}

.my-card h3 {
  margin-bottom: 10px;
  color: #333;
}
.c_grid {
  color: #999;
}
</style>
