<template>
  <div class="add-project-container">
    <div class="add-project-content" v-loading="loading">
      <routerBack
        :loading="loading"
        @save="() => saveClick('save')"
      ></routerBack>
      <div class="tabs-content">
        <div class="project-tab-content">
          <el-tabs v-model="jcTabActiveName">
            <el-tab-pane label="基本信息" name="基本信息">
              <JueceBasicInfo />
            </el-tab-pane>
            <el-tab-pane label="财务评价" name="财务评价">
              <JueceFinance />
            </el-tab-pane>
            <el-tab-pane label="重新决策批复" name="重新决策批复">
              <JueceApproval />
            </el-tab-pane>
          </el-tabs>
        </div>

        <div class="add-project-header">
          <div class="header-left"></div>
          <div class="header-right">
            <el-button type="default" @click="backClick">返回</el-button>
            <template v-if="!loading && !isPreview">
              <el-button type="primary" @click="saveClick('save')"
                >保存</el-button
              >
              <el-button
                type="primary"
                v-if="
                  jcFormData.projectLzType == '9' ||
                  jcFormData.projectLzType == '11' ||
                  jcFormData.projectLzType == '13'
                "
                @click="saveClick('zaiSubmit')"
                >重新决策</el-button
              >
            </template>
          </div>
        </div>
      </div>
    </div>

    <!-- 审核表单区域 -->
    <div
      class="audit-section"
      v-if="
        isPreview &&
        canAudit &&
        (formData.projectLzType == '3' ||
          formData.projectLzType == 3 ||
          jcFormData.projectLzType == '8' ||
          jcFormData.projectLzType == 8 ||
          jcFormData.projectLzType == '11' ||
          jcFormData.projectLzType == 11 ||
          jcFormData.projectLzType == '12' ||
          jcFormData.projectLzType == 12) &&
        formData.del !== 1
      "
    >
      <el-collapse v-model="activeCollapse">
        <el-collapse-item title="审批操作" name="审批操作">
          <el-form
            :model="auditFormData"
            ref="auditForm"
            :rules="auditRules"
            label-width="150"
          >
            <el-form-item label="是否同意" prop="approvalResult">
              <el-select
                v-model="auditFormData.approvalResult"
                placeholder="请选择审批意见"
                clearable
                style="width: 200px"
              >
                <el-option :value="true" label="同意"></el-option>
                <el-option :value="false" label="不同意"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="审批意见" prop="approvalMessage">
              <el-input
                type="textarea"
                v-model="auditFormData.approvalMessage"
                :rows="4"
                placeholder="请输入审批意见"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitAudit"
                >提交审批</el-button
              >
              <el-button @click="cancelAudit">重置</el-button>
            </el-form-item>
          </el-form>
        </el-collapse-item>
      </el-collapse>
    </div>
  </div>
</template>

<script setup>
import {
  reactive,
  ref,
  onMounted,
  getCurrentInstance,
  computed,
  provide,
} from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { useUserStore } from "@/stores/user.js";
import Decimal from "decimal.js";
import routerBack from "@/components/common/routerBack.vue";
import JueceBasicInfo from "@/views/projectManage/addProject/components/JueceBasicInfo.vue";
import JueceFinance from "@/views/projectManage/addProject/components/JueceFinance.vue";
import JueceApproval from "@/views/projectManage/addProject/components/JueceApproval.vue";
import { useResource } from "@/views/projectManage/addProject/composables/useResource.js";
import { useJueceData } from "@/views/projectManage/addProject/composables/useJueceData.js";
import { useFinanceTables } from "@/views/projectManage/addProject/composables/useFinanceTables.js";
import { useProjectDetail } from "@/composables/useProjectDetail";

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

const { projectDisabled, cachedInfo } = useProjectDetail();
const userStore = useUserStore();
let token = ref("");
token.value = userStore.authToken || sessionStorage.getItem("authToken") || "";

const userInfo =
  userStore.userInfo ||
  (sessionStorage.getItem("userInfo") &&
    JSON.parse(sessionStorage.getItem("userInfo"))) ||
  {};
let canAudit = ref(false);
userInfo.roles.map((item) => {
  if (["xmlx_sp", "xmjc_sp"].includes(item.key)) {
    canAudit.value = true;
  }
});

const jcTabActiveName = ref("基本信息");
const activeCollapse = reactive([
  "项目基本信息",
  "项目所在地",
  "审批操作",
  "计量币种",
  "实施时间",
  "投资分类",
  "特别关注、特别监管类等信息",
  "建设规模（实物量指标）",
  "股东信息",
  "项目必要性及可行性",
  "立项资料",
  "项目投资总额（全口径）",
  "财务评价指标",
  "核心边界条件",
  "项目立项信息",
  "审批意见",
  "政府审批（核准、备案）情况",
  "我方担保及股权融资情况",
  "我方担保及债权融资情况",
  "工程带动情况",
  "风险管理",
  "里程碑节点",
  "投评决策资料",
  "决策主体审核情况",
  "投资主体审核情况",
  "项目批复信息",
  "其他",
  "投决计划",
  "项目投资资金流量表",
  "项目资本金现金流量表",
  "能建方现金流量表",
  "利润表",
]);

let formData = reactive({});
let jcFormData = reactive({});
let loading = ref(false);
const isPreview = !!route.query.isPreview;
let projectId = route.query.projectId;

const formDisabled = computed(() => {
  if (isPreview) return true;
  return false;
});

// 下载文件
const downloadFile = (data) => {
  let a = document.createElement("a");
  a.href = `${proxy.windowConfig.baseUrl}/api/file/download/${data.id}`;
  a.download = data.originalname;
  document.body.appendChild(a);
  a.click();
  a.remove();
};

// 模板下载
const downloadTemplate = async (type) => {
  fetch(
    proxy.windowConfig.baseUrl +
      "/api/template/getExcelTemplate2?tampName=" +
      type,
    {
      headers: {
        Authorization: token.value,
      },
    },
  )
    .then((res) => res.blob())
    .then((blob) => {
      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      let name =
        type === "tjjh"
          ? "投决计划"
          : type === "xmtzzjll"
            ? "项目投资资金流量表"
            : type === "xmzbjxjll"
              ? "项目资本金现金流量表"
              : type === "njfxjll"
                ? "能建方现金流量表"
                : type === "lrb"
                  ? "利润表"
                  : "";
      link.download = name + "模板.xlsx";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
    });
};

// Composables
const resource = useResource(formData, jcFormData);
const juece = useJueceData(jcFormData, resource.gdlxList);
const finance = useFinanceTables();

// 计算对象总和
const getObjSums = (obj, objkey) => {
  return Object.entries(obj).reduce(
    (acc, [key, item]) => acc.plus(new Decimal(item[objkey] || 0)),
    new Decimal(0),
  );
};

// Provide for child components
provide("jcShared", {
  jcFormData,
  formData,
  isPreview,
  formDisabled,
  activeCollapse,
  ...juece,
  ...finance,
  getObjSums,
  downloadFile,
  downloadTemplate,
  ElMessageBox,
  ...resource,
  windowConfig: proxy.windowConfig,
  token,
});

// 按zb名称将后端数据合并到前端默认树结构中
function mergeTzzeData(defaultData, backendData) {
  if (!backendData || !backendData.length) return;
  const map = {};
  function flatten(items) {
    for (const item of items) {
      if (item.zb) map[item.zb] = item;
      if (item.children && item.children.length) flatten(item.children);
    }
  }
  flatten(backendData);
  function fill(items) {
    for (const item of items) {
      const src = map[item.zb];
      if (src) {
        item.id = src.id;
        item.rmbjj = src.rmbjj;
      }
      if (item.children && item.children.length) fill(item.children);
    }
  }
  fill(defaultData);
}

// 获取项目信息
const getProjectInfo = () => {
  loading.value = true;
  proxy.$post({
    url: "/api/project/getProjectInfo",
    data: {
      id: projectId,
    },
    callback: (res) => {
      loading.value = false;
      let data = res.lixiang || {};
      if (data.del === 1) {
        ElMessage.warning("该条数据已被删除");
      }
      Object.assign(formData, data);

      // 决策
      let jcData = res.zaijuece || res.juece || {};
      Object.assign(jcFormData, jcData);
      if (res.zaijuece) {
        Object.assign(juece.jcSwlzbData, jcData.projectJsgms);
        Object.assign(juece.dbzqData, jcData.projectZqrzs);
        Object.assign(juece.fxglData, jcData.projectFxgls);
        Object.assign(juece.jcGdxxData, jcData.projectGdxxs.concat([{}]));
        juece.changeJcGdxxSums();
        Object.assign(juece.lcbjdData, jcData.projectLcbjds);
        Object.assign(juece.lcbspData.value, jcData.lcbjhspb);
        Object.assign(juece.kyclData.value, jcData.kycl);
        Object.assign(juece.jjzbcsData.value, jcData.jjzbcbcscl);
        Object.assign(juece.tpzcclData.value, jcData.qtxgzccl);
        Object.assign(juece.tpbczcclData.value, jcData.bcxgzccl);
        Object.assign(juece.shyaData.value, jcData.shya);
        Object.assign(juece.jcHxbjtjData, jcData.projectBjtjs);
        mergeTzzeData(juece.jcTzzeqkjData, jcData.projectXmtzzes);
        Object.assign(juece.jcCwpjzbData, jcData.projectCwpjzbs);
        Object.assign(juece.jcztshqkData, jcData.projectJczts);
        Object.assign(juece.tzztshqkData, jcData.projectTzzts);
        Object.assign(juece.jcspyjData, jcData.projectSpyjs);
        finance.importTjjh(jcData.tjjh);
        finance.importXmtzzjll(jcData.xmtzzjll);
        finance.importXmzbjxjll(jcData.xmzbjxjll);
        finance.importNjfxjll(jcData.njfxjll);
        finance.importLrb(jcData.lrb);
      }
      // 关联筛选
      resource.jcSzjList.value =
        resource.jnwList.filter((item) => item.key == jcData.jnw)[0]
          ?.children || [];
      resource.jcDsgjList.value =
        resource.jcSzjList.value.filter((item) => item.key == jcData.sjnzjjw)[0]
          ?.children || [];
      resource.jcQxgjList.value =
        resource.jcDsgjList.value.filter(
          (item) => item.key == jcData.dsjngjjw,
        )[0]?.children || [];
      resource.jcTzsxejflList.value =
        resource.tzsxyjflList.filter((item) => item.key == jcData.tzsxyjfl)[0]
          ?.children || [];
      resource.jcTzsxxfbkList.value =
        resource.tzsxtzbkList.filter((item) => item.key == jcData.tzbk)[0]
          ?.children || [];
      resource.jcTzmdejflList.value =
        resource.tzmdyjflList.filter((item) => item.key == jcData.tzmdyjfl)[0]
          ?.children || [];
      resource.jcTzznejflList.value =
        resource.tzznyjflList.filter((item) => item.key == jcData.tzznyjfl)[0]
          ?.children || [];
    },
  });
};

onMounted(() => {
  projectId && getProjectInfo();
  if (cachedInfo) {
    formData.projectName = cachedInfo.projectName || "";
    formData.projectId = cachedInfo.projectId || "";
  }
  resource.initResourceData();
});

// 返回列表页
const backClick = () => {
  router.back(-1);
};

// 保存数据
const saveClick = (type) => {
  let url = type === "zaiSubmit" ? "startZaiJuece" : "saveZaiJuece";
  let gdxxNewArr = JSON.parse(JSON.stringify(juece.jcGdxxData));
  gdxxNewArr.splice(-1);
  let params = {
    ...jcFormData,
    projectJsgms: juece.jcSwlzbData,
    projectZqrzs: juece.dbzqData,
    projectFxgls: juece.fxglData,
    projectGdxxs: gdxxNewArr,
    projectLcbjds: juece.lcbjdData,
    lcbjhspb: juece.lcbspData.value,
    kycl: juece.kyclData.value,
    jjzbcbcscl: juece.jjzbcsData.value,
    qtxgzccl: juece.tpzcclData.value,
    bcxgzccl: juece.tpbczcclData.value,
    shya: juece.shyaData.value,
    projectXmtzzes: juece.jcTzzeqkjData,
    projectCwpjzbs: juece.jcCwpjzbData,
    projectBjtjs: juece.jcHxbjtjData,
    projectJczts: juece.jcztshqkData,
    projectTzzts: juece.tzztshqkData,
    projectSpyjs: juece.jcspyjData,
  };
  // 获取动态表格数据
  let tjjhArr = finance.getTjjhData();
  if (tjjhArr.length) {
    params.tjjh = tjjhArr;
  }
  let xmtzzjllArr = finance.getXmtzzjllData();
  if (xmtzzjllArr.length) {
    params.xmtzzjll = xmtzzjllArr;
  }
  let xmzbjxjllArr = finance.getXmzbjxjllData();
  if (xmzbjxjllArr.length) {
    params.xmzbjxjll = xmzbjxjllArr;
  }
  let njfxjllArr = finance.getNjfxjllData();
  if (njfxjllArr.length) {
    params.njfxjll = njfxjllArr;
  }
  let lrbArr = finance.getLrbData();
  if (lrbArr.length) {
    params.lrb = lrbArr;
  }
  proxy.$post({
    url: "/api/project/" + url,
    data: params,
    callback: (data) => {
      ElMessage.success("保存成功");
    },
  });
};

// 审核
let auditFormData = ref({});
let auditForm = ref();
const auditRules = {
  approvalResult: [
    { required: true, message: "请选择审批意见", trigger: "change" },
  ],
};
const cancelAudit = () => {
  auditFormData.value = {};
  auditForm.value?.resetFields();
};
const submitAudit = () => {
  auditForm.value.validate((valid) => {
    if (valid) {
      let url =
        formData.projectLzType.toString() === "3"
          ? "approvalLixiang"
          : jcFormData.projectLzType.toString() === "8"
            ? "approvalJuece"
            : jcFormData.projectLzType.toString() === "12" ||
                jcFormData.projectLzType.toString() === "11"
              ? "approvalZaiJuece"
              : "";
      proxy.$post({
        url: "/api/project/" + url,
        data: {
          id: formData.id,
          ...auditFormData.value,
        },
        callback: (data) => {
          ElMessage.success("审批成功");
          auditFormData.value = {};
          auditForm.value?.resetFields();
          router.back(-1);
        },
      });
    }
  });
};
</script>

<style scoped lang="less"></style>
