<template>
  <el-dialog
    title="记账信息"
    v-model="visible"
    :width="width"
    append-to-body
    draggable
    @close="close"
    :close-on-click-modal = "false"
  >
  <div v-loading="loading">
    <!-- 功能按钮 -->
    <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 v-if="form.status === 4" :span="12">
            <el-form-item label="驳回原因">
              <div>{{ form.feedbackContent }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-divider />
          </el-col>
          <el-col :span="12">
            <el-form-item label="本期收入">
              <el-input-number
                v-model="form.currentIncome"
                size="small"
                placeholder="本期收入"
                :precision="2"
                :controls="false"
                style="width: 100%"
              />
              <!-- <div>{{ currentIncome }}</div> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="本年收入">
              <el-input-number
                v-model="form.currentYearIncome"
                size="small"
                placeholder="本年收入"
                :precision="2"
                :controls="false"
                style="width: 100%"
              />
              <!-- <div>{{ currentYearIncome }}</div> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="本年累计成本">
              <el-input-number
                v-model="form.cumulativeCost"
                size="small"
                placeholder="本年累计成本"
                :precision="2"
                :controls="false"
                style="width: 100%"
              />
              <!-- <div>{{ currentYearCost }}</div> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="本年利润总额">
              <el-input-number
                v-model="form.currentYearProfit"
                size="small"
                placeholder="本年利润总额"
                :precision="2"
                :controls="false"
                style="width: 100%"
              />
              <!-- <div>{{ currentYearProfit }}</div> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否暂估">
              <!-- <el-input-number v-model="form.is" size="small" placeholder="暂估金额"  :precision="2" :controls="false" style="width: 100%;" /> -->
              <el-checkbox
                v-model="form.isProvisionalEstimate"
                :true-label="1"
                :false-label="0"
              />
              <!-- <div>{{ feedback.provisionalEstimateAmount }}</div> -->
            </el-form-item>
          </el-col>
          <el-col v-if="form.isProvisionalEstimate === 1" :span="12">
            <el-form-item label="暂估金额">
              <el-input-number
                v-model="form.provisionalEstimateAmount"
                size="small"
                placeholder="暂估金额"
                :precision="2"
                :controls="false"
                style="width: 100%"
              />
              <!-- <div>{{ feedback.provisionalEstimateAmount }}</div> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="可弥补以前年度亏损">
              <!-- <el-input-number v-model="form.inputInvoice" size="small" placeholder="进项发票联" :step="1" step-strictly :controls="false" style="width: 100%;" /> -->
              <div>{{ rowNum(form.previousAnnualLosses) }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                v-model.trim="form.content"
                maxlength="200"
                show-word-limit
                type="textarea"
                rows="2"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div></div>
    <div class="form-btns-container" style="height: 40px">
      <el-button
        size="small"
        icon="Close"
        style="float: right; margin-left: 12px; margin-right: 12px"
        @click="close"
        >取消
      </el-button>
      <el-button
        type="primary"
        size="small"
        icon="Finished"
        style="float: right"
        @click="handleSave"
        >保存
      </el-button>
    </div>
  </div>
  </el-dialog>
</template>
<script setup>
import {
  getDetail,
  saveDetail,
  updateDetail,
} from "@/api/business/production/keepAccount";
import { reactive, ref } from "vue";
import { salaryStatusTypes } from "@/utils/default";
import { rowNum } from "@/utils/index";
const { proxy } = getCurrentInstance();
const visible = ref(false);
const width = ref(800);
const selections = ref([]);
const currentSource = ref(null);

const props = defineProps({
  getList: {
    type: Function,
    default: () => {},
  },
});

const { getList } = toRefs(props);

const data = reactive({
  confirmChoices: [
    {
      label: "有",
      value: 1,
    },
    {
      label: "无",
      value: 0,
    },
  ],
});

const { confirmChoices } = toRefs(data);
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 loading = ref(false)
const emptyForm = {
  details: [],
};

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

function loadData() {
  loading.value = true
  Promise.all([getDetail(form.value)]).then((res) => {
    form.value = { ...proxy.deepClone(emptyForm), ...res[0].data };
    if (form.value.status === 3) {
      proxy.$modal.msgError("该收票信息已提交待审核");
      close();
    }
  }).finally(() => {
    loading.value = false
  });
}

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.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);
    } else {
      sums[index] = "";
    }
  });
  return sums;
}

function handleSave() {
  // if (form.value.saveStatus == null || form.value.saveStatus === '') {
  //   proxy.$modal.msgError('请选择节点状态')
  //   return
  // }
  // if (form.value.saveStatus === 4) {
  //   if (form.value.postDate == null || form.value.postDate === '') {
  //     proxy.$modal.msgError('请选择邮寄日期')
  //     return
  //   }
  //   if (form.value.postNo == null || form.value.postNo === '') {
  //     proxy.$modal.msgError('请填写快递单号')
  //     return
  //   }
  // }
  proxy.$modal
    .confirm("确认保存么？")
    .then(() => {
      const saveValue = proxy.deepClone(form.value);
      saveValue.status = 3;
      if (saveValue.id == null) {
        loading.value = true
        saveDetail(saveValue).then((res) => {
          proxy.$modal.msgSuccess("保存成功");
          reset();
          close();
          getList.value();
        }).finally(() => {
          loading.value = false
        });;
      } else {
        loading.value = true
        updateDetail(saveValue).then((res) => {
          proxy.$modal.msgSuccess("保存成功");
          reset();
          close();
          getList.value();
        }).finally(() => {
          loading.value = false
        });;
      }
    })
    .catch((err) => {
      proxy.$modal.msg("取消保存");
    });
}
function saveStatusChangeHandle() {
  if (form.value.saveStatus === 2) {
    form.value.feeTicket = 0;
    form.value.inputInvoice = 0;
    form.value.inputDeduction = 0;
    form.value.revenueBookkeeping = 0;
    form.value.hasIncomeTicket = 0;
    form.value.hasSsafTicket = 0;
    form.value.hasCostTicket = 0;
    form.value.bankCopy = 0;
    form.value.others = 0;
    form.value.bankSlips = 0;
    form.value.payroll = 0;
  }
}

function getStatusOfSalary(arg) {
  const index = salaryStatusTypes.findIndex((v) => v.value === arg.status);
  return index <= 0 ? "未开始" : salaryStatusTypes[index].label;
}

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