<template>
  <el-dialog
    title="记账信息"
    v-model="visible"
    :width="width"
    append-to-body
    draggable
    :close-on-click-modal = "false"
    @close="close"
  >
    <!-- 功能按钮 -->
    <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="24">
            <el-divider />
          </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.currentIncome) }}</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.currentYearIncome) }}</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.inputInvoice" size="small" placeholder="进项发票联" :step="1" step-strictly :controls="false" style="width: 100%;" /> -->
              <div>{{ rowNum(form.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.currentYearProfit) }}</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(previousAnnualLosses) }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                v-if="form.status === 2"
                v-model.trim="form.verifyContent"
                type="textarea"
                rows="2"
              />
              <div v-else>{{ form.verifyContent }}</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="form-btns-container" style="height: 40px">
      <el-button
        v-if="verifiable() && form.status === 3"
        type="warning"
        icon="back"
        size="small"
        style="float: right; margin-left: 12px"
        @click="returnStatus()"
      >
        退回</el-button
      >
    </div>
    <feedback-dialog ref="feedbackDialogView" :verify="verify" />
    <!-- <print-dialog ref="printDialog" /> -->
  </el-dialog>
</template>
<script setup>
import {
  getDetail,
  verifyDetail,
  turnBackDetail,
} from "@/api/business/production/keepAccount";
import feedbackDialog from "../feedbackDialog.vue";
import { rowNum } from "@/utils/index";
import { salaryStatusTypes } from "@/utils/default";
import useUserStore from "@/store/modules/user";
import { ref } from "vue";
const { proxy } = getCurrentInstance();
const visible = ref(false);
const width = ref(800);
const selections = ref([]);
const currentSource = ref(null);

const permissions = useUserStore().permissions;
const all_permission = "*:*:*";

const feedbackDialogView = ref(null);

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

const { getList } = toRefs(props);
const total = ref(0);

const data = reactive({
  confirmChoices: [
    {
      label: "有",
      value: 1,
    },
    {
      label: "无",
      value: 0,
    },
  ],
  salaryDetail: null,
  selectStatus: [
    {
      label: "未开始",
      value: 0,
      color: "#fff",
    },
    {
      label: "待确认",
      value: 1,
      color: "#fcd080",
    },
    {
      label: "待审核",
      value: 2,
      color: "#80a7fc",
    },
    {
      label: "已完成",
      value: 3,
      color: "#57e63e",
    },
    {
      label: "驳回待处理",
      value: 4,
      color: "#e63e3e",
    },
  ],
});

const { confirmChoices, salaryDetail, selectStatus } = toRefs(data);

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({
  amount: null,
  details: [],
});

const emptyForm = {
  details: [],
};

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

function loadData() {
  Promise.all([getDetail(form.value)]).then((res) => {
    form.value = { ...proxy.deepClone(emptyForm), ...res[0].data };
  });
}

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

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

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

function showVerify() {
  if (salaryDetail.value == null || salaryDetail.value.status !== 3) {
    return false;
  }
  if (
    form.value.id == null ||
    form.value.status === 0 ||
    form.value.status === 1 ||
    form.value.status === 3 ||
    form.value.status === 4
  ) {
    return false;
  } else if (verifiable()) {
    return true;
  } else {
    return false;
  }
}

function verifiable() {
  return (
    permissions.includes(all_permission) ||
    permissions.includes("business:keepAccount:verify")
  );
}

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

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

function handleVerify(status, feedbackStatus) {
  if (status === 4) {
    const saveValue = proxy.deepClone(form.value);
    saveValue.status = status;
    saveValue.feedbackStatus = 1;
    feedbackDialogView.value.open(saveValue);
  } else if (status === 3 && feedbackStatus === 1) {
    const saveValue = proxy.deepClone(form.value);
    saveValue.status = status;
    saveValue.feedbackStatus = feedbackStatus;
    feedbackDialogView.value.open(saveValue);
  } else {
    proxy.$modal
      .confirm("确认审核么？")
      .then((_) => {
        const saveValue = proxy.deepClone(form.value);
        saveValue.status = status;
        verify(saveValue);
      })
      .catch((_) => {
        proxy.$modal.msg("已取消审核");
      });
  }
}

function verify(data) {
  verifyDetail(data).then((res) => {
    reset();
    getList.value();
    close();
  });
}

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

function returnStatus(status) {
  proxy.$modal
    .confirm("确认退回么？")
    .then((_) => {
      const saveValue = form.value;
      saveValue.status = 1;
      turnBackDetail(saveValue).then((res) => {
        reset();
        getList.value();
        close();
      });
    })
    .catch((_) => {
      proxy.$modal.msg("已取消退回");
    });
}

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

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

function getStatusOfSalary(arg) {
  const index = salaryStatusTypes.findIndex((v) => v.value === arg.status);
  return index <= 0 ? "未开始" : salaryStatusTypes[index].label;
}
// 暴露给父组件的方法
defineExpose({
  open,
});
</script>