<template>
  <el-drawer v-model="open" :title="`审批详情`" :before-close="handleClose" direction="rtl" class="apply-detail-drawer"
    modal-class="el-subscribe-drawer" size="80%">

    <Index :apply="apply" style="max-height:70vh" @update="show">
      <template v-slot:descriptions>
        <el-descriptions-item label="说明" :span="2">
          <span v-if="apply.applyType == 10">
            {{ apply.applyPurchase.applyPurchaseExplain }}
          </span>
          <span v-else-if="apply.applyType == 20">
            {{ apply.sparePartApply.sparePartApplyExplain }}
          </span>
          <span v-else-if="apply.applyType == 30">
            {{ apply.maintenanceApply.maintenanceApplyExplain }}
          </span>
        </el-descriptions-item>
      </template>
      <div class="margin-top">
        <el-card shadow="hover">
          <ApplyPurchaseDetailsIndex :list="apply.applyPurchase.applyPurchaseDetailsList" :editable="false"
            @update="null" v-if="apply.applyType == 10" />
          <SparePartApplyDetailsIndex :list="apply.sparePartApply.sparePartApplyDetailsList" :editable="false"
            @update="null" v-else-if="apply.applyType == 20" />
          <MaintenanceApplyDetailsIndex :list="apply.maintenanceApply.maintenanceApplyDetailsList" :editable="false"
            @update="null" v-else-if="apply.applyType == 30" />
          <WarehouseApplyIndex :list="apply.warehouseApply.warehouseApplyDetailsList" :editable="false" @update="null"
            v-else-if="apply.applyType == 40" />
        </el-card>

      </div>
    </Index>

    <template #footer>
      <el-button :disabled="loading" plain @click="handelRevoke"
        v-if="apply.applyState == '10' && apply.applyEstablishUser === $store.state.user.user.userId">撤 回</el-button>
      <el-button :disabled="loading || applyId == null" plain @click="handleEidt"
        v-else-if="(apply.applyState == '50' || apply.applyState == '30') && apply.applyEstablishUser === $store.state.user.user.userId">
        编 辑
      </el-button>
      <template v-if="apply.applyState == 10 && editable">
        <el-button :disabled="loading" type="danger" @click="handelReject">驳 回</el-button>
        <el-button :disabled="loading" type="primary" @click="handelAgree">同 意</el-button>
      </template>
    </template>


    <el-dialog title="审批详情意见" v-model="dialogOpen" width="600px" append-to-body @close="handleCloseDialog"
      class="el-dialog-apply-opinion">
      <el-form ref="applyRef" :model="apply" :rules="rules" label-width="0px">
        <el-form-item label="" prop="opinion">
          <el-input maxlength="300" v-model="apply.opinion" placeholder="请输入意见" type="textarea" :rows="5" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :disabled="loading" @click="handleCloseDialog">取 消</el-button>
          <el-button :disabled="loading" type="primary" @click="formSubmit">
            <span v-if="applyState == 20">同 意</span>
            <span v-else-if="applyState == 30">驳 回</span>
          </el-button>
        </div>
      </template>
    </el-dialog>

  </el-drawer>

</template>

<script setup>
import {
  updateApply,
  getApply,
  getAlreadyApply,
  withdrawApply,
} from "@/api/workbench/apply";
import { clearApplyPurchaseDetails, updateApplyPurchaseDetails as _updateApplyPurchaseDetails } from "@/utils/applyPurchaseDetails";
import { clearSparePartApplyDetails, updateSparePartApplyDetails as _updateSparePartApplyDetails } from "@/utils/sparePartApplyDetails";
import { clearMaintenanceApplyDetails, updateMaintenanceApplyDetails as _updateMaintenanceApplyDetails } from "@/utils/maintenanceApplyDetails";


import Index from "./index";
import ApplyPurchaseDetailsIndex from "@/components/ApplyPurchaseDetails/index";
import SparePartApplyDetailsIndex from "@/components/SparePartApplyDetails/index";
import MaintenanceApplyDetailsIndex from "@/components/MaintenanceApplyDetails/index";
import WarehouseApplyIndex from "@/components/WarehouseApplyDetails/index";
import useApply from "@/hooks/useApply"; // hook


const emit = defineEmits(["update"]);


const { proxy } = getCurrentInstance();
const router = useRouter();

const open = ref(false);
const dialogOpen = ref(false);

const loading = ref(true);

const apply = ref({ applyPurchase: {}, sparePartApply: {}, maintenanceApply: {}, warehouseApply: {} });
const applyState = ref(null);
const editable = ref(true);
const rules = ref({
  opinion: [
    {
      required: true,
      message: "意见不能为空",
      trigger: "blur",
    },
  ],
})
const prop = defineProps({
  applyId: {
    type: [Number, String],
    default: null,
  },
  api: {
    type: [String],
    default: "getApply",
  },
});

const { applyId, api } = toRefs(prop);

// 显示弹框
function show() {
  open.value = true;
  nextTick(() => {
    getData(applyId.value);
  })
}

function getData(applyId) {
  loading.value = true;
  if (api.value == "getApply") {
    getApply(applyId).then(response => {
      apply.value = response.data;
      loading.value = false;
    })
  } else if (api.value == 'getAlreadyApply') {
    editable.value = false
    getAlreadyApply(applyId).then(response => {
      apply.value = response.data;
      loading.value = false;
    })
  }

}

function handleEidt() {
  // 驳回 、 撤回
  getAlreadyApply(apply.value.applyId).then(response => {
    switch (apply.value.applyType) {
      case 10:
      case "10":
        // 物料申购
        clearApplyPurchaseDetails(false);
        response.data.applyPurchase.applyPurchaseDetailsList.map(item => _updateApplyPurchaseDetails(item, false))
        router.push("/warehouse/warehouse?showApplyPurchaseDrawerSubmit=true");
        break;
      case 20:
      case "20":
        // 备件申领
        clearSparePartApplyDetails(false);
        response.data.sparePartApply.sparePartApplyDetailsList.map(item => _updateSparePartApplyDetails(item, false))
        router.push("/sparePart/sparePart?showSparePartApplySubmitDrawer=true");
        break;
      case 30:
      case "30":
        // 维保申请	
        clearMaintenanceApplyDetails(false);
        response.data.maintenanceApply.maintenanceApplyDetailsList.map(item => _updateMaintenanceApplyDetails(item, false))
        router.push("/maintentance/maintentance?showMaintenanceApplySubmitDrawer=true");
        break;
    }
  });

}

// 撤回
function handelRevoke() {
  proxy.$modal
    .confirm("是否撤回？")
    .then(() => {
      let id = apply.value.applyInfoid
      //// console.log(id)
      //// console.log(apply.value.applyType)
      //// console.log(apply.value.applyType == 10)
      // if (apply.value.applyType == 10) {
      //  // console.log(apply.value)
      //   id = apply.value.applyPurchaseId
      //  // console.log(id)
      // }
      // else if (apply.value.applyType == 20) {
      //   id = apply.value.sparePartApplyId
      //  // console.log(id)
      // } else if (apply.value.applyType == 30) {
      //   id = apply.value.maintenanceApplyId
      //  // console.log(id)
      // }

      //// console.log(id)
      withdrawApply(id).then(() => {
        proxy.$modal.msg("已撤回");
        getData(applyId.value);
        emit("update", true)
      })
    })
    .catch(() => { });
}

// 驳回
function handelReject() {
  // proxy.$modal
  //   .confirm("是否驳回？")
  //   .then(() => {
  //     proxy.$modal.msgError("已驳回");
  //   })
  //   .catch(() => { });
  applyState.value = 30
  dialogOpen.value = true;
}

// 同意
function handelAgree() {
  // proxy.$modal
  //   .confirm("是否同意？")
  //   .then(() => {
  //     proxy.$modal.msgSuccess("已同意");
  //   })
  //   .catch(() => { });
  applyState.value = 20
  dialogOpen.value = true;
}

// 关闭按钮
function handleClose() {
  open.value = false;
}

function formSubmit() {
  loading.value = true
  proxy.$refs["applyRef"].validate((valid) => {
    if (valid) {
      let form = JSON.parse(JSON.stringify(apply.value))
      form.applyState = applyState.value
      updateApply(form).then(() => {
        if (applyState.value == 20) {
          proxy.$modal.msgSuccess("已同意");
        } else if (applyState.value == 30) {
          proxy.$modal.msgError("已驳回");
        }
        handleCloseDialog();
        handleClose();
        emit("update", true)
        loading.value = false;
        useApply(false);
      }).catch(() => {
        loading.value = false;
      })
    }
    loading.value = false;
  });



}

function handleCloseDialog() {
  apply.value.opinion = "";
  dialogOpen.value = false;
}

defineExpose({
  show,
  handleClose,
});
</script>

<style lang="scss">
.apply-detail-drawer {
  line-height: 1.5rem;

  .el-drawer__body {
    max-height: calc(100vh - 45px - 32px - 62px);
    padding: 0;
  }
}
</style>