<template>
  <el-dialog 
    v-model="visible" 
    width="95%" 
    v-loading="baseLoading" 
    top="2vh" 
    :close-on-click-modal="false" 
    destroy-on-close
    class="salary-info-dialog"
  >
    <div class="salary-info-container">
      <!--基本信息-->
      <div class="base-info-section">
        <div class="base-info-content">
          <div class="info-group">          
            <div class="info-item">
              <span class="info-label">姓名：</span>
              <el-tag v-if="salaryData.baseInfo[0]?.realName">{{ salaryData.baseInfo[0].realName }}</el-tag>
              <span v-else class="info-value">-</span>
            </div>
            <div class="info-item">
              <span class="info-label">身份证号：</span>
              <el-tag v-if="salaryData.baseInfo[0]?.idCard">{{ salaryData.baseInfo[0].idCard }}</el-tag>
              <span v-else class="info-value">-</span>
            </div>
          </div>
          <el-form :model="nowUser" :inline="true" class="search-form">
            <el-form-item label="年份">
              <el-date-picker
                v-model="nowUser.nf"
                type="year"
                format="YYYY"
                value-format="YYYY"
                placeholder="选择年"
                style="width: 150px">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="月份">
              <el-date-picker
                v-model="nowUser.yff"
                type="month"
                format="M"
                value-format="M"
                placeholder="选择月"
                style="width: 150px">
              </el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button @click="searchUserInfo" type="primary" icon="Search">
                查询
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <el-card shadow="hover" class="info-card">
        <template #header>
          <div class="card-header">
            <el-icon><Money /></el-icon>
            <span>工资明细</span>
          </div>
        </template>
        <!--应发部分-->
        <div v-if="showAllContent" class="section-title">
          <el-icon><TrendCharts /></el-icon>
          <span>应发部分</span>
        </div>
        <el-table
          v-if="showAllContent"
          :data="salaryData.baseInfo"
          size="small"
          border
          class="salary-table"
          style="width: 100%"
        >
            <el-table-column label="应发部分">
              <el-table-column prop="postSalary" label="岗位工资" min-width="60" align="center"></el-table-column>
              <el-table-column prop="payWage" label="薪级工资" min-width="60" align="center"></el-table-column>
              <el-table-column label="见习期工资" prop="studentPay" min-width="60" align="center"></el-table-column>
              <el-table-column prop="liveAllowance" label="生活补贴" min-width="60" align="center"></el-table-column>
              <el-table-column prop="postAllowance" label="岗位津贴" min-width="60" align="center"></el-table-column>
              <el-table-column label="住房(租金)补贴" prop="houseSubsidies" min-width="60" align="center"></el-table-column>
              <el-table-column label="新职工住房补贴" prop="newHouseSubsidies" min-width="60" align="center"></el-table-column>
              <el-table-column label="回民补贴" prop="huiSubsidies" min-width="60" align="center"></el-table-column>
              <el-table-column label="养老保险补贴" prop="oldSubsidies" min-width="60" align="center"></el-table-column>
              <el-table-column label="教龄津贴" prop="ageAllowance" min-width="60" align="center"></el-table-column>
              <el-table-column label="特教补贴" prop="specialSubsidies" min-width="60" align="center"></el-table-column>
              <el-table-column label="特级教师津贴" prop="teacherAllowance" min-width="60" align="center"></el-table-column>
              <el-table-column label="特岗津贴(一)" prop="sPostAllowance1" min-width="60" align="center"></el-table-column>
              <el-table-column label="特岗津贴(二)" prop="sPostAllowance2" min-width="60" align="center"></el-table-column>
              <el-table-column label="其他" prop="other" min-width="60" align="center"></el-table-column>
              <el-table-column label="奖励性绩效工资" prop="meritPay" min-width="60" align="center"></el-table-column>
              <el-table-column label="乡镇工作补贴" prop="villageSubsidies" min-width="60" align="center"></el-table-column>
              <el-table-column label="临时性补贴" prop="temporarySubsidies" min-width="60" align="center"></el-table-column>
              <el-table-column label="上下班交通补贴" prop="trafficSubsidies" min-width="60" align="center"></el-table-column>
              <el-table-column label="保留津贴" prop="keepAllowance" min-width="60" align="center"></el-table-column>
              <el-table-column label="补发工资" prop="retroactivePay" min-width="60" align="center"></el-table-column>
              <el-table-column label="应休未休假补贴" prop="vacationMoney" min-width="60" align="center"></el-table-column>
              <el-table-column label="应发工资" prop="shouldPay" min-width="60" align="center"></el-table-column>
              <el-table-column label="基础专项绩效" prop="baseSalary" min-width="60" align="center"></el-table-column>
              <el-table-column label="基础工资应税收入" prop="shouldTaxMoney" min-width="60" align="center"></el-table-column>
            </el-table-column>
          </el-table>
          <div v-if="showAllContent" class="formula-tag">
            <el-tag type="danger" size="small">基础工资应税收入= 岗位工资 +薪级工资+见习期工资+生活补贴+岗位津贴+教龄津贴+特教补贴+特级教师津贴+特岗津贴（1）+特岗津贴（2）+奖励绩效性工资+乡镇工作补贴+临时补贴+保留津贴+应休未休假-个人补缴-其他扣款-医疗救助金</el-tag>
          </div>
        
        <!--应扣部分-->
        <div v-if="showAllContent" class="section-title">
          <el-icon><Remove /></el-icon>
          <span>应扣部分</span>
        </div>
        <el-table
          v-if="showAllContent"
          size="small"
          border
          :data="salaryData.baseInfo"
          class="salary-table"
          style="width: 100%">
            <el-table-column label="应扣部分">
              <el-table-column label="住房公积金" min-width="90" prop="houseFund"></el-table-column>
              <el-table-column label="医疗保险金" min-width="90" prop="medicalInsurance"></el-table-column>
              <el-table-column label="失业保险金" min-width="90" prop="unemployInsurance"></el-table-column>
              <el-table-column label="养老保险金" min-width="90" prop="endowInsurance"></el-table-column>
              <el-table-column label="工会费" min-width="60" prop="unionFee"></el-table-column>
              <el-table-column label="儿童统筹" min-width="90" prop="childrenWhole"></el-table-column>
              <el-table-column label="个人所得税" width="90" prop="personalTax"></el-table-column>
              <el-table-column label="其他扣款" min-width="90" prop="otherDeduction"></el-table-column>
              <el-table-column label="病事假扣款" min-width="90" prop="sickDeduction"></el-table-column>
              <el-table-column label="医疗救助基金" min-width="90" prop="medicalFund"></el-table-column>
              <el-table-column label="工伤保险" min-width="90" prop="inductrialInjury"></el-table-column>
              <el-table-column label="个人补缴" min-width="90" prop="personalPay"></el-table-column>
              <el-table-column label="应扣合计" min-width="90" prop="withhold"></el-table-column>
            </el-table-column>
          </el-table>
          <div v-if="showAllContent" class="formula-tag">
            <el-tag size="small">个人所得税 = 个税计算数据中的《 累计应补(退)税额 》</el-tag>
          </div>

        <!--劳务费-->
        <div class="section-title">
          <el-icon><Document /></el-icon>
          <span>造单收入清单</span>
        </div>
        <el-table 
          size="small" 
          border 
          :data="allProjectData"
          class="salary-table"
          style="width: 100%">
            <el-table-column label="造单收入清单">
              <el-table-column label="造单部门" prop="deptName"></el-table-column>
              <el-table-column label="造单人" prop="createName"></el-table-column>
              <el-table-column label="项目编号" prop="projectNo"></el-table-column>
              <el-table-column label="项目名" prop="title"></el-table-column>
              <el-table-column label="金额" prop="realMoney"></el-table-column>
              <el-table-column label="付讫时间" prop="payTime"></el-table-column>
              <el-table-column label="免税或暂不交税" prop="freeTax">
                <template #default="scope">
                  <span v-if="scope.row.freeTax=='1'">√</span>
                </template>
              </el-table-column>
            </el-table-column>
          </el-table>

        <!--专项扣除-->
        <div class="section-title">
          <el-icon><DataAnalysis /></el-icon>
          <span>个税计算数据</span>
        </div>
        <el-table
          size="small"
          border
          :data="salaryExtendData"
          class="salary-table"
          style="width: 100%">
            <el-table-column label="个税计算数据">
              <el-table-column prop="currentIncome" label="应税收入" min-width="60" align="center"></el-table-column>
              <el-table-column prop="totalIncome" label="累计收入额" min-width="60" align="center"></el-table-column>
              <el-table-column prop="totalDeduction" label="累计减除费用" min-width="60" align="center"></el-table-column>
              <el-table-column prop="totalSpecialDecution" label="累计专项扣除" min-width="60" align="center"></el-table-column>
              <el-table-column label="累计专项扣除附加" align="center">
                <el-table-column prop="totalChildEdu" label="累计子女教育" min-width="60" align="center"></el-table-column>
                <el-table-column prop="totalConEdu"   label="累计继续教育" min-width="60" align="center"> </el-table-column>
                <el-table-column prop="totalHouseInterest" label="累计住房贷款利息" min-width="60" align="center"></el-table-column>
                <el-table-column prop="totalHouse" label="累计住房租金" min-width="60" align="center"></el-table-column>
                <el-table-column prop="totalSupportOld"  label="累计赡养老人" min-width="60" align="center"></el-table-column>
                <el-table-column prop="totalBabyMoney"  label="累计婴幼儿照护费用" min-width="60" align="center"></el-table-column>
              </el-table-column>
              <el-table-column prop="totalTaxMoney"  label="累计应纳税所得额" min-width="60" align="center"></el-table-column>
              <el-table-column prop="taxRate"  label="税率" min-width="60" align="center"></el-table-column>
              <el-table-column prop="quickDecution"  label="速算扣除数" min-width="60" align="center"></el-table-column>
              <el-table-column prop="totalRealTaxPay"  label="累计应扣缴税额" min-width="60" align="center"></el-table-column>
              <el-table-column prop="totalPrePayTax"  label="累计已预缴税额" min-width="60" align="center"></el-table-column>
              <el-table-column prop="totalRetrieveTax"  label="累计应补(退)税额" min-width="60" align="center"></el-table-column>
            </el-table-column>
          </el-table>
          <div class="formula-tag">
            <el-tag type="warning" size="small">应税收入= 基础工资应税收入+造单收入</el-tag>
            <el-tag type="success" size="small" class="ml10">累计专项扣除=当年累计个人承担的住房公积金+医疗保险金+失业保险金+养老保险金</el-tag>
          </div>

        <!--实发合计-->
        <div v-if="showAllContent" class="section-title">
          <el-icon><Wallet /></el-icon>
          <span>实发合计</span>
        </div>
        <el-table
          v-if="showAllContent"
          size="small"
          border
          :data="[staticsData]"
          class="salary-table summary-table"
          empty-text=" "
          style="width: 100%">
            <el-table-column label="小计">
              <el-table-column label="应发工资" prop="shouldPay"></el-table-column>
              <el-table-column label="应扣合计" prop="shouldDedu"></el-table-column>
              <el-table-column label="实发工资" prop="realWage"></el-table-column>
              <el-table-column label="造单收入" prop="orderMoney"></el-table-column>
            </el-table-column>
          </el-table>
          <div v-if="showAllContent" class="formula-tag">
            <el-tag type="primary" size="small">实发工资= 应发工资-应扣合计</el-tag>
          </div>
      </el-card>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import { Money, TrendCharts, Remove, Document, DataAnalysis, Wallet } from '@element-plus/icons-vue'
import { useMessage } from '/@/hooks/message'
import { queryUserInfo, queryExtendSalaryInfo, checkAuth } from '/@/api/professional/salaries/teachersalary'

const message = useMessage()

// 对话框显示状态
const visible = ref(false)

// 数据
const salaryData = reactive({
  baseInfo: [] as any[]
})

const nowUser = ref<any>({})
const baseLoading = ref(false)
const salaryExtendData = ref<any[]>([])
const allProjectData = ref<any[]>([])
const staticsData = reactive({
  shouldPay: 0,
  shouldDedu: 0,
  realWage: 0,
  orderMoney: 0,
  personTax: 0
})
const showAllContent = ref(false)

// 检查权限
const checkAuthMethod = async () => {
  try {
    const res = await checkAuth()
    showAllContent.value = res.data
  } catch (error) {
    // 检查权限失败
  }
}

// 构建用户信息
const makeUserInfo = (data: any) => {
  const row = JSON.parse(JSON.stringify(data))
  salaryData.baseInfo = []
  row.realName = (row.realName == "" || row.realName == null ? row.userName : row.realName)
  salaryData.baseInfo.push(row)

  staticsData.shouldPay = row.shouldPay || 0
  staticsData.shouldDedu = row.withhold || 0
  staticsData.realWage = row.realWage || 0
  staticsData.personTax = (row.personalTax as number) || 0
}

// 查询扩展薪资信息
const queryExtendSalaryInfoMethod = async (row: any) => {
  salaryExtendData.value = []
  const params = { nf: row.nf, yf: row.yf, teacherNo: row.teacherNo }
  try {
    const res = await queryExtendSalaryInfo(params)
    salaryExtendData.value.push(res.data.salaryTax)
    allProjectData.value = res.data.allProject
    staticsData.orderMoney = res.data.totalMoney
  } catch (error) {
    // 查询失败
  }
}

// 搜索用户信息
const searchUserInfo = async () => {
  if (!nowUser.value.idCard) {
    message.warning('请输入身份证号')
    return
  }
  if (!nowUser.value.nf) {
    message.warning('请选择年份')
    return
  }
  if (!nowUser.value.yff) {
    message.warning('请选择月份')
    return
  }

  baseLoading.value = true
  const data = { idCard: nowUser.value.idCard, nf: nowUser.value.nf, yf: nowUser.value.yff }
  try {
    const response = await queryUserInfo(data)
    if (response.data.data == null) {
      message.info('未查询到该时间段的数据')
      salaryData.baseInfo = []
      const obj: any = {}
      obj.realName = nowUser.value.realName
      obj.idCard = nowUser.value.idCard
      salaryData.baseInfo.push(obj)

      salaryExtendData.value = []
      Object.assign(staticsData, {
        shouldPay: 0,
        shouldDedu: 0,
        realWage: 0,
        orderMoney: 0,
        personTax: 0
      })
    } else {
      const resData = response.data.data
      resData.realName = nowUser.value.realName
      resData.nf = nowUser.value.nf
      resData.yf = nowUser.value.yff
      resData.teacherNo = nowUser.value.teacherNo
      makeUserInfo(resData)
      await queryExtendSalaryInfoMethod(resData)
      message.success('查询成功')
    }
  } catch (error: any) {
    // 错误处理已在数据请求层统一处理，此处不需要提示
  } finally {
    baseLoading.value = false
  }
}

// 初始化
const init = (row: any) => {
  visible.value = true
  nextTick(() => {
    checkAuthMethod()
    nowUser.value = JSON.parse(JSON.stringify(row))
    nowUser.value.yff = row.yf
    makeUserInfo(row)
    queryExtendSalaryInfoMethod(row)
  })
}

// 暴露方法
defineExpose({
  init
})
</script>

<style lang="scss" scoped>
.salary-info-dialog {
  :deep(.el-dialog__body) {
    padding: 10px !important;
    max-height: calc(100vh - 120px);
    overflow-y: auto;
  }
}

.salary-info-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.base-info-section {
  padding: 12px 16px;
  background: #fff;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.base-info-content {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  gap: 16px;
}

.info-group {
  display: flex;
  flex-direction: row;
  gap: 16px;
  flex-wrap: wrap;
}

.info-item {
  display: flex;
  gap: 6px;

  .info-label {
    font-weight: 500;
    color: #606266;
    font-size: 13px;
  }

  .info-value {
    color: #303133;
    font-size: 13px;
    font-weight: 500;
  }
}

.search-form {
  margin-left: auto;
  margin-bottom: 0;
}

.info-card {
  :deep(.el-card__header) {
    padding: 16px 20px;
    background: #f5f7fa;
    border-bottom: 1px solid #ebeef5;
  }

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

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;

  .el-icon {
    font-size: 18px;
    color: var(--el-color-primary);
  }
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 24px 0 12px 0;
  padding-bottom: 8px;
  border-bottom: 2px solid #e4e7ed;
  font-size: 15px;
  font-weight: 600;
  color: #303133;

  .el-icon {
    font-size: 16px;
    color: var(--el-color-primary);
  }

  &:first-child {
    margin-top: 0;
  }
}

.salary-table {
  margin-bottom: 16px;

  :deep(.el-table__header) {
    th {
      background: #f5f7fa;
      color: #606266;
      font-weight: 600;
    }
  }

  :deep(.el-table__body) {
    td {
      padding: 8px 0;
    }
  }

  :deep(.el-table__cell) {
    padding: 8px 4px;
    font-size: 13px;
  }
}

.summary-table {
  :deep(.el-table__body) {
    td {
      font-weight: 600;
      font-size: 14px;
      color: var(--el-color-primary);
    }
  }
}

.formula-tag {
  margin-top: 12px;
  margin-bottom: 8px;
  line-height: 1.6;

  .el-tag {
    margin-right: 8px;
    padding: 6px 12px;
    font-size: 12px;
    white-space: normal;
    word-break: break-all;
  }

  .ml10 {
    margin-left: 10px;
  }
}

// 响应式优化
@media (max-width: 1400px) {
  .salary-info-dialog {
    :deep(.el-dialog) {
      width: 98% !important;
    }
  }
}

// 滚动条优化
.salary-info-dialog {
  :deep(.el-dialog__body) {
    &::-webkit-scrollbar {
      width: 8px;
      height: 8px;
    }

    &::-webkit-scrollbar-track {
      background: #f1f1f1;
      border-radius: 4px;
    }

    &::-webkit-scrollbar-thumb {
      background: #c1c1c1;
      border-radius: 4px;

      &:hover {
        background: #a8a8a8;
      }
    }
  }
}
</style>
