<template>
  <el-dialog
    title="记账信息"
    v-model="visible"
    width="70%"
    append-to-body
    draggable
    @close="close"
    :close-on-click-modal = "false"
  >
    <!-- 功能按钮 -->
    <div style="padding: 8px 24px 16px 24px">
      <el-form size="small" label-width="140px" v-model="form">
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="客户名称">
              <div>{{ form.companyName }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属月份">
              <div>{{ form.year }}-{{ form.month }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务状态">
              <el-select
                v-model="form.status"
                :disabled="form.status === 3"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in selectStatus"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-divider content-position="left">工资</el-divider>
          <el-col :span="24" class="details-container">
            <!--操作按钮 开始-->
            <div class="details-head" style="margin-bottom: 15px;">
              <div class="title">
                <i class="fa fa-th-list" aria-hidden="true" /> 工资人员信息
              </div>
            </div>
            <div class="details-body">
              <div>
                <el-table
                  ref="sourceTable"
                  :data="form.salary.details"
                  size="small"
                  max-height="490px"
                  border
                  show-summary
                  :summary-method="getSummaries"
                  highlight-current-row
                  header-row-class-name="list-header-row"
                  row-class-name="list-row"
                  class="salary-table"
                  @selection-change="handleCheckChange"
                  @current-change="handleCurrentChange"
                >
                  <el-table-column type="selection" width="50" align="center" />
                  <el-table-column
                    type="index"
                    label="序号"
                    width="50"
                    align="center"
                  />
                  <el-table-column
                    label="员工姓名"
                    width="120"
                    align="center"
                    prop="employeeName"
                  >
                    <template #default="scope">
                      <div>
                        {{ scope.row.employeeName }}
                      </div>
                      <span
                        style="
                          color: red;
                          position: absolute;
                          z-index: 10;
                          top: 4px;
                          right: 12px;
                        "
                        >*</span
                      >
                    </template>
                  </el-table-column>
                  <el-table-column label="身份证号" width="130" align="center">
                    <template #default="scope">
                      <div>
                        {{ scope.row.idCode }}
                      </div>
                      <span
                        style="
                          color: red;
                          position: absolute;
                          z-index: 10;
                          top: 4px;
                          right: 12px;
                        "
                        >*</span
                      >
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="应发工资"
                    width="90"
                    align="right"
                    prop="planSalary"
                  >
                    <template #default="scope">
                      <div>
                        {{ rowNum(scope.row.planSalary) }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="实发工资"
                    width="90"
                    align="right"
                    prop="actuallySalary"
                  >
                    <template #default="scope">
                      <div>
                        {{ rowNum(scope.row.actuallySalary) }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="奖金及其他"
                    width="90"
                    align="right"
                    prop="bonusAmount"
                  >
                    <template #default="scope">
                      <div>
                        {{ rowNum(scope.row.bonusAmount) }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="社保" align="center">
                    <el-table-column
                      label="养老保险"
                      width="75"
                      align="right"
                      prop="endowmentInsurance"
                    >
                      <template #default="scope">
                        <div>
                          {{ rowNum(scope.row.endowmentInsurance) }}
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column
                      label="医疗保险"
                      width="75"
                      align="right"
                      prop="medicalInsurance"
                    >
                      <template #default="scope">
                        <div>
                          {{ rowNum(scope.row.medicalInsurance) }}
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column
                      label="失业险"
                      width="75"
                      align="right"
                      prop="unemploymentBenefit"
                    >
                      <template #default="scope">
                        <div>
                          {{ rowNum(scope.row.unemploymentBenefit) }}
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column
                      label="大病险"
                      width="75"
                      align="right"
                      prop="seriousIllnessInsurance"
                    >
                      <template #default="scope">
                        <div>
                          {{ rowNum(scope.row.seriousIllnessInsurance) }}
                        </div>
                      </template>
                    </el-table-column>
                  </el-table-column>
                  <el-table-column
                    label="公积金"
                    width="75"
                    align="right"
                    prop="housingFund"
                  >
                    <template #default="scope">
                      <div>
                        {{ rowNum(scope.row.housingFund) }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="个税"
                    align="right"
                    width="75"
                    prop="currentIndividualIncomeTax"
                  >
                    <template #default="scope">
                      <div>
                        {{ rowNum(scope.row.currentIndividualIncomeTax) }}
                      </div>
                    </template></el-table-column
                  >
                  <el-table-column
                    label="其他扣款"
                    width="75"
                    align="right"
                    prop="otherCut"
                  >
                    <template #default="scope">
                      <div>
                        {{ rowNum(scope.row.otherCut) }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="备注"
                    width="100"
                    header-align="center"
                  >
                    <template #default="scope">
                      <div>
                        {{ scope.row.remark }}
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-col>
          <el-col :span="24">
            <el-divider />
          </el-col>
          <el-col :span="24">
            <el-form-item label="合计工资">
              {{ rowNum(form.salary.amount) }}
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="工资备注">
              {{ form.salary.content }}
            </el-form-item>
          </el-col>
          <el-divider content-position="left">收票</el-divider>
          <el-col :span="6">
            <el-form-item label="收入票">
              {{ form.ticket.incomeTicket }}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="成本票">
              {{ form.ticket.costTicket }}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="费用票">
              {{ form.ticket.feeTicketNumber }}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="银行对账">
              {{ form.ticket.bankCopyNumber }}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="银行回单">
              {{ form.ticket.bankSlipsNumber }}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="工资单">
              {{ form.ticket.salaryTicket }}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="社保公积金">
              {{ form.ticket.ssafTicket }}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="其他票">
              {{ form.ticket.otherTicket }}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="合计">
              {{ form.ticket.sumNumber }}
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              {{ form.ticket.content }}
            </el-form-item>
          </el-col>
          <el-divider content-position="left">记账</el-divider>
          <el-col :span="8">
            <el-form-item label="本期收入">
              {{ rowNum(form.keepAccount.currentIncome) }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="本年收入">
              {{ rowNum(form.keepAccount.currentYearIncome) }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="本年累计成本">
              {{ rowNum(form.keepAccount.cumulativeCost) }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="本年利润总额">
              {{ rowNum(form.keepAccount.currentYearProfit) }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否暂估">
              {{ form.keepAccount.isProvisionalEstimate }}
            </el-form-item>
          </el-col>
          <el-col v-if="form.keepAccount.isProvisionalEstimate === 1" :span="8">
            <el-form-item label="暂估金额">
              {{ rowNum(form.keepAccount.provisionalEstimateAmount) }}
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              {{ form.keepAccount.content }}
            </el-form-item>
          </el-col>
          <el-divider content-position="left">报税</el-divider>
          <el-col :span="12">
            <el-form-item label="可弥补之前年度亏损">
              {{ rowNum(form.reportTax.previousAnnualLosses) }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="增值税">
              {{ rowNum(form.reportTax.valueAddedTax) }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="城建税">
              {{ rowNum(form.reportTax.cityConstructTax) }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="教育费附加">
              {{ rowNum(form.reportTax.additionsTaxOfEducation) }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地方教育费附加">
              {{ rowNum(form.reportTax.ladditionsTaxOfEducation) }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业所得税">
              {{ rowNum(form.reportTax.businessIncomeTax) }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="印花税">
              {{ rowNum(form.reportTax.stampTax) }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="文化事业建设税">
              {{ rowNum(form.reportTax.culturalConstructTax) }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="消费税">
              {{ rowNum(form.reportTax.excise) }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合计">
              {{ rowNum(form.reportTax.sumTax) }}
            </el-form-item>
          </el-col>
          <el-divider content-position="left">个税</el-divider>
          <el-col :span="12">
            <el-form-item label="个税金额">
              {{ rowNum(form.individual.amount) }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注">
              {{ form.individual.remark }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="form-btns-container" style="height: 40px">
      <el-button size="small" icon="close" style="float: right" @click="close">
        取消</el-button
      >
    </div>
    <!-- <feedback-dialog ref="feedbackDialogView" :parent="this" />
    <print-dialog ref="printDialog" :parent="this" /> -->
  </el-dialog>
</template>
<script setup>
import {
  getDetail,
  saveDetail,
  updateDetail,
} from "@/api/business/crm/serviceWorkOrder";
import { rowNum, numberToCurrencyNo } from "@/utils/index";
import { ref } from "vue";
const { proxy } = getCurrentInstance();
const visible = ref(false);
const width = ref(1000);
const selections = ref([]);
const currentSource = ref(null);

const props = defineProps({
  getList: {
    type: Function,
    default: () => {},
  },
});
const selectStatus = ref([
  {
    label: "未开始",
    value: 0,
    color: "#fff",
  },
  {
    label: "进行中",
    value: 1,
    color: "#FFB836",
  },
  {
    label: "已完成",
    value: 3,
    color: "#2FCB81",
  },
]);
const { getList } = toRefs(props);
const total = ref(0);

const employeeEmptyData = {
  id: null,
  title: "",
  remark: "",
  employeeName: "",
  departmentName: "",
  idCode: "",
  salaryAmount: "",
  bonusAmount: "",
  allowanceAmount: "",
  subsidyAmount: "",
  absenceCut: "",
  planSalary: 0,
  actuallySalary: 0,
  endowmentInsurance: 0,
  medicalInsurance: 0,
  unemploymentBenefit: 0,
  seriousIllnessInsurance: 0,
  housingFund: 0,
  otherCut: 0,
  cumulativeIncome: 0,
  cumulativeSpecialCut: 0,
  cumulativeChildEduCut: 0,
  cumulativeHouseLoanInterestCut: 0,
  cumulativeHouseRentCut: 0,
  cumulativeSupportElderCut: 0,
  cumulativeContinuingEduCut: 0,
  cumulativeBabyCareCut: 0,
  sumSpecialCumulativeCut: 0,
  cumulativeOtherCut: 0,
  cumulativeIndividualIncomeTax: 0,
  cumulativeHasPaidIit: 0,
  currentIndividualIncomeTax: 0,
  idiograph: "",
  details: [],
  editStatus: true,
};

const form = ref({});

const emptyForm = {
  salary: {
    details: [],
  },
  ticket: {},
  keepAccount: {},
  reportTax: {},
  individual: {},
  details: [],
};

function open(detail) {
  visible.value = true;
  form.value = { ...emptyForm, ...detail };
  loadData();
}

function loadData() {
  getDetail(form.value).then((res) => {
    form.value = { ...proxy.deepClone(emptyForm), ...res.data };
    computeTotal();
  });
}

function close() {
  visible.value = false;
  reset();
}

function reset() {
  form.value = proxy.deepClone(emptyForm);
}

function printSalary() {}
function exportSalary() {}

function handleCurrentChange(row) {
  currentSource.value = row;
}

function handleCheckChange(selection) {
  selections.value = selection.map((item) => item);
}

function handleEmployeeCreate() {
  // 此处必须进行深拷贝，否则添加的明细，将都指向了一个对象
  const _newSource = JSON.parse(JSON.stringify(employeeEmptyData));
  form.value.details.push(_newSource);
  handleCurrentChange(_newSource);
}

function handleEmployeeBatchDelete() {
  proxy.$modal
    .confirm("确定删除?")
    .then(() => {
      form.value.salary.details = form.value.details.filter(
        (item) => selections.value.indexOf(item) === -1
      );
    })
    .catch(() => {
      proxy.$modal.msg("已取消删除");
    });
}

function rowChangeSum(row) {
  let actuallySalary = 0;
  actuallySalary += row.planSalary == null ? 0 : row.planSalary;
  actuallySalary += row.bonusAmount == null ? 0 : row.bonusAmount;
  actuallySalary -= row.endowmentInsurance == null ? 0 : row.endowmentInsurance;
  actuallySalary -= row.medicalInsurance == null ? 0 : row.medicalInsurance;
  actuallySalary -=
    row.unemploymentBenefit == null ? 0 : row.unemploymentBenefit;
  actuallySalary -=
    row.seriousIllnessInsurance == null ? 0 : row.seriousIllnessInsurance;
  actuallySalary -= row.housingFund == null ? 0 : row.housingFund;
  actuallySalary -=
    row.currentIndividualIncomeTax == null ? 0 : row.currentIndividualIncomeTax;
  actuallySalary -= row.otherCut == null ? 0 : row.otherCut;
  row.actuallySalary = actuallySalary;
  computeTotal();
}

function computeTotal() {
  let totalSalay = 0;
  form.value.details.forEach((l) => {
    totalSalay += l.actuallySalary == null ? 0 : l.actuallySalary;
  });
  form.value.amount = totalSalay.toFixed(2);
}

function getSummaries(param) {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    } else if (index === 1) {
      sums[index] = "";
      return;
    }
    const values = data.map((item) => Number(item[column.property]));

    if (!values.every((value) => isNaN(value))) {
      sums[index] = values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!isNaN(value)) {
          return (Number(prev) + Number(curr)).toFixed(2);
        } else {
          return Number(prev).toFixed(2);
        }
      }, 0);
      sums[index] = numberToCurrencyNo(sums[index]);
    } else {
      sums[index] = "";
    }
  });
  return sums;
}

function handleSave() {
  for (let i = 0; i < form.value.details.length; i++) {
    const l = form.value.details[i];
    // 数据校验
    if (!l.employeeName) {
      proxy.$modal.msgError(`第${i + 1}行员工姓名不能为空`);
      return;
    }
    if (!l.idCode) {
      proxy.$modal.msgError(`第${i + 1}行身份证号不能为空`);
      return;
    }
    // 正则表达式匹配身份证号的格式
    const idRegExp =
      /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|X|x)$/;
    const regExp = /^([a-zA-z]|[0-9]){5,17}$/;
    if (!(regExp.test(l.idCode) || idRegExp.test(l.idCode))) {
      proxy.$modal.msgError(`第${i + 1}行请输入正确的身份证号！`);
      return;
    }
  }
  proxy.$modal
    .confirm("确认保存么？")
    .then(() => {
      const saveValue = proxy.deepClone(form.value);
      saveValue.status = 2;
      if (saveValue.id == null) {
        saveDetail(saveValue).then((res) => {
          proxy.$modal.msgSuccess("保存成功");
          reset();
          close();
          getList.value();
        });
      } else {
        updateDetail(saveValue).then((res) => {
          proxy.$modal.msgSuccess("保存成功");
          reset();
          close();
          getList.value();
        });
      }
    })
    .catch((err) => {
      proxy.$modal.msg("取消保存");
    });
}

function ticketNumberChange() {
  let amount = 0;
  amount += form.value.ticket.incomeTicket;
  amount += form.value.ticket.costTicket;
  amount += form.value.ticket.feeTicketNumber;
  amount += form.value.ticket.ssafTicket;
  amount += form.value.ticket.salaryTicket;
  amount += form.value.ticket.bankSlipsNumber;
  amount += form.value.ticket.bankCopyNumber;
  amount += form.value.ticket.bankCopy;
  amount += form.value.ticket.otherTicket;
  form.value.ticket.sumNumber = amount;
}

/** 计算税额 */
function taxChangeHandler() {
  let amount = 0;

  amount +=
    form.value.reportTax.ladditionsTaxOfEducation == null
      ? 0
      : form.value.reportTax.ladditionsTaxOfEducation;
  amount +=
    form.value.reportTax.valueAddedTax == null
      ? 0
      : form.value.reportTax.valueAddedTax;
  amount +=
    form.value.reportTax.cityConstructTax == null
      ? 0
      : form.value.reportTax.cityConstructTax;
  amount +=
    form.value.reportTax.additionsTaxOfEducation == null
      ? 0
      : form.value.reportTax.additionsTaxOfEducation;
  amount +=
    form.value.reportTax.businessIncomeTax == null
      ? 0
      : form.value.reportTax.businessIncomeTax;
  amount +=
    form.value.reportTax.stampTax == null ? 0 : form.value.reportTax.stampTax;
  amount +=
    form.value.reportTax.culturalConstructTax == null
      ? 0
      : form.value.reportTax.culturalConstructTax;
  amount +=
    form.value.reportTax.excise == null ? 0 : form.value.reportTax.excise;
  form.value.reportTax.sumTax = amount;
}

// 暴露给父组件的方法
defineExpose({
  open,
});
</script>