<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 slot="title" class="dialog-title-container">
      <span class="title-label"><i class="el-icon-document" /> 工资信息</span>
      <i class="el-icon-close" @click="close" />
    </div> -->
    <!-- 功能按钮 -->
    <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="12">
            <el-form-item label="收入票">
              <el-select
                v-model.trim="form.hasIncomeTicket"
                :disabled="form.saveStatus === 2"
                placeholder="请选择"
                size="small"
                style="width: 100%"
              >
                <el-option
                  v-for="item in confirmChoices"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="成本票">
              <el-select
                v-model.trim="form.hasCostTicket"
                :disabled="form.saveStatus === 2"
                placeholder="请选择"
                size="small"
                style="width: 100%"
              >
                <el-option
                  v-for="item in confirmChoices"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="费用票">
              <el-select
                v-model.trim="form.feeTicket"
                :disabled="form.saveStatus === 2"
                placeholder="请选择"
                size="small"
                style="width: 100%"
              >
                <el-option
                  v-for="item in confirmChoices"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="银行对账单">
              <el-select
                v-model.trim="form.bankCopy"
                :disabled="form.saveStatus === 2"
                placeholder="请选择"
                size="small"
                style="width: 100%"
              >
                <el-option
                  v-for="item in confirmChoices"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="银行回单">
              <el-select
                v-model.trim="form.bankSlips"
                :disabled="form.saveStatus === 2"
                placeholder="请选择"
                size="small"
                style="width: 100%"
              >
                <el-option
                  v-for="item in confirmChoices"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工资表">
              <!-- <el-select v-model.trim="form.payroll" :disabled="form.saveStatus === 2" placeholder="请选择" size="small" style="width: 100%;">
                <el-option v-for="item in confirmChoices" :key="item.value" :label="item.label" :value="item.value" />
              </el-select> -->
              <div>
                {{
                  salaryDetail == null
                    ? "未开始"
                    : getStatusOfSalary(salaryDetail)
                }}
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="社保公积金票据">
              <el-select
                v-model.trim="form.hasSsafTicket"
                :disabled="form.saveStatus === 2"
                placeholder="请选择"
                size="small"
                style="width: 100%"
              >
                <el-option
                  v-for="item in confirmChoices"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="其他">
              <el-select
                v-model.trim="form.others"
                :disabled="form.saveStatus === 2"
                placeholder="请选择"
                size="small"
                style="width: 100%"
              >
                <el-option
                  v-for="item in confirmChoices"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-divider />
          </el-col>
          <el-col :span="24">
            <el-form-item label="节点状态" required>
              <el-radio-group
                v-model="form.saveStatus"
                @change="saveStatusChangeHandle"
              >
                <el-radio
                  v-if="
                    salaryDetail != null &&
                    (salaryDetail.status === 3 || salaryDetail.status === 2)
                  "
                  :label="2"
                  >无票据</el-radio
                >
                <el-radio
                  v-if="
                    salaryDetail != null &&
                    (salaryDetail.status === 3 || salaryDetail.status === 2)
                  "
                  :label="3"
                  >交接送达</el-radio
                >
                <el-radio
                  v-if="
                    salaryDetail != null &&
                    (salaryDetail.status === 3 || salaryDetail.status === 2)
                  "
                  :label="4"
                  >交接邮寄</el-radio
                >
              </el-radio-group>
            </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"
              />
            </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"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                v-model.trim="form.content"
                type="textarea"
                maxlength="200"
                show-word-limit
                rows="2"
              />
            </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; margin-left: 12px; margin-right: 12px"
        @click="close"
        >取消</el-button
      >
      <el-button
        type="warning"
        size="small"
        icon="Edit"
        style="float: right"
        @click="handleConfirmed"
      >
        待确认</el-button
      >
      <el-button
        size="small"
        type="primary"
        icon="Finished"
        style="float: right"
        @click="handleSave"
      >
        保存</el-button
      >
    </div>
    <!-- <feedback-dialog ref="feedbackDialogView" :parent="this" />
    <print-dialog ref="printDialog" :parent="this" /> -->
    </div>
  </el-dialog>
</template>
<script setup>
import {
  getDetail,
  saveDetail,
  updateDetail,
  getSalaryDetail,
} from "@/api/business/production/receiveTicket";
import { reactive, ref } from "vue";
import { salaryStatusTypes } from "@/utils/default";
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,
    },
  ],
  salaryDetail: null,
});

const { confirmChoices, salaryDetail } = 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 loading = ref(false)
const form = ref({});

const emptyForm = {
  details: [],
};

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

function loadData() {
  loading.value = true
  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;
    if (form.value.status === 2 || 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 handleConfirmed() {
  form.value.saveStatus = 1;
  handleSave();
}

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 = form.value.saveStatus === 1 ? 1 : 2;
      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>