<template>
  <el-dialog title="收票信息" v-model="visible" :width="width" append-to-body draggable @close="close" :close-on-click-modal = "false">
    <!-- 功能按钮 -->
    <div style="padding: 8px 24px 16px 24px">
      <el-form size="small" label-width="100px" 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="6">
            <el-form-item label="收入票">
              <div v-if="form.status === 3">{{ form.incomeTicket }}</div>
              <div v-else>{{ form.hasIncomeTicket === 1 ? "有" : "无" }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="成本票">
              <div v-if="form.status === 3">{{ form.costTicket }}</div>
              <div v-else>{{ form.hasCostTicket === 1 ? "有" : "无" }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="费用票">
              <div v-if="form.status === 3">{{ form.feeTicketNumber }}</div>
              <div v-else>{{ form.feeTicket === 1 ? "有" : "无" }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="银行对账单">
              <div v-if="form.status === 3">{{ form.bankCopyNumber }}</div>
              <div v-else>{{ form.bankCopy === 1 ? "有" : "无" }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="银行回单">
              <div v-if="form.status === 3">{{ form.bankSlipsNumber }}</div>
              <div v-else>{{ form.bankSlips === 1 ? "有" : "无" }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="工资表">
              <div v-if="form.status === 3">{{ form.salaryTicket }}</div>
              <div v-else>
                {{
                  salaryDetail == null
                  ? "未开始"
                  : getStatusOfSalary(salaryDetail)
                }}
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="社保公积金票据">
              <div v-if="form.status === 3">{{ form.ssafTicket }}</div>
              <div v-else>{{ form.hasSsafTicket === 1 ? "有" : "无" }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="其他">
              <div v-if="form.status === 3">{{ form.otherTicket }}</div>
              <div v-else>{{ form.others === 1 ? "有" : "无" }}</div>
            </el-form-item>
          </el-col>
          <el-col v-if="form.saveStatus === 4" :span="12">
            <el-form-item label="邮寄日期" required>
              <!-- <el-date-picker
                v-model="form.postDate"
                style="width: 100%"
                type="date"
                value-format="YYYY-MM-DD"
                format="YYYY-MM-DD"
                size="small"
              /> -->
              {{ form.postDate }}
            </el-form-item>
          </el-col>
          <el-col v-if="form.saveStatus === 4" :span="12">
            <el-form-item label="快递单号" required>
              <!-- <el-input
                v-model="form.postNo"
                style="width: 100%"
                size="small"
              /> -->
              {{ form.postNo }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="节点状态" required>
              <!-- <el-radio-group v-model="form.status">
                <el-radio :label="2">流转并提交</el-radio>
                <el-radio :label="1">流转到待确认</el-radio>
              </el-radio-group> -->
              <div>{{ getStatusLabel(form.status) }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注">
              <!-- <el-input v-model.trim="form.content" type="textarea" rows="2" /> -->
              <div>{{ form.content }}</div>
            </el-form-item>
          </el-col>
          <el-col v-if="showVerify() || form.status === 3" :span="24">
            <el-divider />
          </el-col>
          <el-col v-if="showVerify()" :span="12">
            <el-form-item label="收入票">
              <el-input-number v-model="form.incomeTicket" size="small" placeholder="收入票" :step="1" step-strictly
                :controls="false" style="width: 100%" @change="ticketNumberChange" />
            </el-form-item>
          </el-col>
          <el-col v-if="showVerify()" :span="12">
            <el-form-item label="成本票">
              <el-input-number v-model="form.costTicket" size="small" placeholder="成本票" :step="1" step-strictly
                :controls="false" style="width: 100%" @change="ticketNumberChange" />
            </el-form-item>
          </el-col>
          <el-col v-if="showVerify()" :span="12">
            <el-form-item label="费用票">
              <el-input-number v-model="form.feeTicketNumber" size="small" placeholder="费用票" :step="1" step-strictly
                :controls="false" style="width: 100%" @change="ticketNumberChange" />
            </el-form-item>
          </el-col>
          <el-col v-if="showVerify()" :span="12">
            <el-form-item label="银行对账">
              <el-input-number v-model="form.bankCopyNumber" size="small" placeholder="银行回单" :step="1" step-strictly
                :controls="false" style="width: 100%" @change="ticketNumberChange" />
            </el-form-item>
          </el-col>
          <el-col v-if="showVerify()" :span="12">
            <el-form-item label="银行回单">
              <el-input-number v-model="form.bankSlipsNumber" size="small" placeholder="银行回单" :step="1" step-strictly
                :controls="false" style="width: 100%" @change="ticketNumberChange" />
            </el-form-item>
          </el-col>
          <el-col v-if="showVerify()" :span="12">
            <el-form-item label="工资单">
              <el-input-number v-model="form.salaryTicket" size="small" placeholder="工资单" :step="1" step-strictly
                :controls="false" style="width: 100%" @change="ticketNumberChange" />
            </el-form-item>
          </el-col>
          <el-col v-if="showVerify()" :span="12">
            <el-form-item label="社保公积金">
              <el-input-number v-model="form.ssafTicket" size="small" placeholder="社保公积金" :step="1" step-strictly
                :controls="false" style="width: 100%" @change="ticketNumberChange" />
            </el-form-item>
          </el-col>
          <el-col v-if="showVerify()" :span="12">
            <el-form-item label="其他票">
              <el-input-number v-model="form.otherTicket" size="small" placeholder="其他票" :step="1" step-strictly
                :controls="false" style="width: 100%" @change="ticketNumberChange" />
            </el-form-item>
          </el-col>
          <el-col v-if="showVerify()" :span="12">
            <el-form-item label="合计">
              <span>{{ form.sumNumber }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="审核备注">
              <el-input v-if="form.status === 2" show-word-limit maxlength="200" 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="showVerify()" type="danger" size="small" style="float: right; margin-left: 12px"
        @click="handleVerify(4)" icon="back">
        驳回</el-button>
      <el-button v-if="showVerify()" type="primary" size="small" icon="check" style="float: right; margin-left: 12px"
        @click="handleVerify(3, 0)">审核通过</el-button>
      <el-button v-if="showVerify()" type="primary" size="small" icon="check" style="float: right; margin-left: 12px"
        @click="handleVerify(3, 1)">
        审核通过并反馈</el-button>
      <el-button v-if="renturn() && form.status === 3" type="warning" size="small" icon="back"
        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,
  getSalaryDetail,
} from "@/api/business/production/receiveTicket";
import feedbackDialog from "../feedbackDialog.vue";
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),
    getSalaryDetail({
      companyId: form.value.companyId,
      year: form.value.year,
      month: form.value.month,
    }),
  ]).then((res) => {
    form.value = { ...proxy.deepClone(emptyForm), ...res[0].data };
    salaryDetail.value = res[1].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() {
  // console.log(permissions)
  // console.log(permissions)
  return (
    permissions.includes(all_permission) ||
    permissions.includes("business:receiveTicket:verify")
  );
}
function renturn(){
  return (
    permissions.includes(all_permission) ||
    permissions.includes("business:receiveTicket:return")
  );
}

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((_) => {
      turnBackDetail(form.value).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.bankCopyNumber;
  amount += form.value.bankSlipsNumber;
  amount += form.value.salaryTicket;
  amount += form.value.ssafTicket;
  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>