<template>
  <div class="add-project-container">
    <div class="add-project-content" v-loading="loading">
      <routerBack
        :show-save="!loading && showSave"
        :loading="loading"
        :show-process="!!projectId"
        :process-info="processInfo"
        :lx-process-data="lxProcessData"
        :jc-process-data="jcProcessData"
        :flow-type="flowType"
        :current-state="currentFlowState"
        @save="() => saveClick('save')"
        @process="getProcessData"
      ></routerBack>

      <div class="tabs-content">
        <el-tabs v-model="pageActiveName" type="border-card">
          <el-tab-pane label="立项填报" name="立项填报">
            <div class="project-tab-content">
              <el-tabs v-model="lxTabActiveName">
                <el-tab-pane label="基本信息" name="基本信息">
                  <LixiangBasicInfo />
                </el-tab-pane>
                <el-tab-pane label="立项批复" name="立项批复">
                  <LixiangApproval />
                </el-tab-pane>
              </el-tabs>
            </div>
          </el-tab-pane>
          <el-tab-pane
            label="决策信息填报"
            name="决策信息填报"
            v-if="Number(lxType) >= 5"
            :lazy="true"
          >
            <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-tab-pane label="申请报告" name="申请报告">
                <JueceReport />
              </el-tab-pane>
            </el-tabs>
          </el-tab-pane>
        </el-tabs>
        <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"
                v-if="showSubmitLixiang"
                @click="saveClick('submit')"
                >发起立项填报</el-button
              >
              <el-button
                type="primary"
                v-if="showSubmitJuece"
                @click="saveClick('submit')"
                >发起决策信息填报</el-button
              >
            </template>
            <el-button type="primary" v-if="showSave" @click="saveClick('save')"
              >保存</el-button
            >
            <el-button
              type="primary"
              v-if="showFirstAudit"
              @click="auditDialogVisible = true"
              >初审</el-button
            >
            <el-button
              type="primary"
              v-if="showAuditLixiang"
              @click="auditDialogVisible = true"
              >审核</el-button
            >
            <el-button
              type="primary"
              v-if="showAuditJuece"
              @click="auditDialogVisible = true"
              >审核</el-button
            >
            <el-button
              type="primary"
              v-if="showApprove"
              @click="approveDialogVisible = true"
              >核准</el-button
            >
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      v-model="auditDialogVisible"
      title="审批意见"
      width="500"
      align-center
      @close="cancelAudit"
    >
      <el-form
        :model="auditFormData"
        ref="auditForm"
        :rules="auditRules"
        label-width="100"
      >
        <el-form-item label="是否同意" prop="approvalResult">
          <el-select
            v-model="auditFormData.approvalResult"
            placeholder="请选择"
            clearable
          >
            <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" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelAudit">取消</el-button>
          <el-button type="primary" @click="submitAudit">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="approveDialogVisible"
      title="核准意见"
      width="500"
      align-center
      @close="cancelApprove"
    >
      <el-form
        :model="approveFormData"
        ref="approveForm"
        :rules="approveRules"
        label-width="100"
      >
        <el-form-item label="是否同意" prop="approvalResult">
          <el-select
            v-model="approveFormData.approvalResult"
            placeholder="请选择"
            clearable
          >
            <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="approveFormData.approvalMessage" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelApprove">取消</el-button>
          <el-button type="primary" @click="submitApprove">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  reactive,
  ref,
  computed,
  onMounted,
  getCurrentInstance,
  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 LixiangBasicInfo from "./addProject/components/LixiangBasicInfo.vue";
import LixiangApproval from "./addProject/components/LixiangApproval.vue";
import JueceBasicInfo from "./addProject/components/JueceBasicInfo.vue";
import JueceFinance from "./addProject/components/JueceFinance.vue";
import JueceApproval from "./addProject/components/JueceApproval.vue";
import JueceReport from "./addProject/components/JueceReport.vue";
import { useResource } from "./addProject/composables/useResource.js";
import { useLixiangData } from "./addProject/composables/useLixiangData.js";
import { useJueceData } from "./addProject/composables/useJueceData.js";
import { useFinanceTables } from "./addProject/composables/useFinanceTables.js";
const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();
const userStore = useUserStore();
let token = ref("");
token.value = userStore.authToken || sessionStorage.getItem("authToken") || "";
const isTgbu = userStore?.isTgbu;

const userInfo =
  userStore.userInfo ||
  (sessionStorage.getItem("userInfo") &&
    JSON.parse(sessionStorage.getItem("userInfo"))) ||
  {};

console.log(userInfo, "userInfo");
let canAudit = ref(false);
userInfo.roles.map((item) => {
  if (["xmlx_sp", "xmjc_sp"].includes(item.key)) {
    canAudit.value = true;
  }
});

const hasApproveRole = userInfo.roles?.some((item) => {
  return ["tgbzfz", "tgbjbr", "xmssdwbmz"].includes(item.key);
});

const isTouGuanBu = userInfo.departs?.some((d) => d.name === "投资管理部门");
const currentFlowState = computed(() => {
  const lxState = Number(formData.projectLzType) || 0;
  const jcState = Number(jcFormData.projectLzType) || 0;
  return jcState >= 7 ? jcState : lxState;
});
const flowType = computed(() => {
  if (isTouGuanBu && currentFlowState.value >= 1 && currentFlowState.value <= 6)
    return "simple";
  return "complex";
});

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

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

const lxType = computed(() => formData.projectLzType?.toString());
const jcType = computed(() => jcFormData.projectLzType?.toString());
const isDaibanUser = computed(() =>
  formData?.daibanUsers?.includes(userInfo?.id),
);

// 表单禁用状态：基于流程节点 + 待办人判断
const lxFormDisabled = computed(() => {
  if (isPreview) return true;
  if (!lxType.value) return false;
  if (lxType.value === "1") return formData.projectCreator !== userInfo?.id;
  if (["2", "3", "4", "5"].includes(lxType.value)) return !isDaibanUser.value;
  return true;
});
const jcFormDisabled = computed(() => {
  if (isPreview) return true;
  if (["5", "7", "8"].includes(jcType.value)) return !isDaibanUser.value;
  return true;
});

const showSave = computed(
  () => !isPreview && (!formData.id || formData.projectCreator === userInfo?.id),
);
const showSubmitLixiang = computed(
  () => lxType.value === "1" && formData.projectCreator === userInfo?.id,
);
const showSubmitJuece = computed(
  () =>
    jcType.value === "7" && formData.projectCreator === userInfo?.id,
);
const showFirstAudit = computed(
  () => isDaibanUser.value && lxType.value === "3",
);
const showAuditLixiang = computed(
  () => isDaibanUser.value && hasApproveRole && lxType.value === "4",
);
const showAuditJuece = computed(
  () => isDaibanUser.value && jcType.value === "8",
);
const showApprove = computed(
  () => isDaibanUser.value && hasApproveRole && lxType.value === "2",
);

// 下载文件
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 lixiang = useLixiangData(formData, resource.gdlxList);
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("lxShared", {
  formData,
  isPreview,
  formDisabled: lxFormDisabled,
  activeCollapse,
  ...lixiang,
  downloadFile,
  ElMessageBox,
  ...resource,
  windowConfig: proxy.windowConfig,
  token,
});

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

// 获取项目信息
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);

      Object.assign(lixiang.swlzbData, data.projectJsgms);
      Object.assign(lixiang.gdxxData, data.projectGdxxs.concat([{}]));
      lixiang.changeGdxxSums();
      Object.assign(lixiang.zcclData.value, data.lxzl);
      Object.assign(lixiang.tzzeqkjData, data.projectXmtzzes);
      Object.assign(lixiang.cwpjzbData, data.projectCwpjzbs);
      Object.assign(lixiang.hxbjtjData, data.projectBjtjs);
      Object.assign(lixiang.lxpfwjData.value, data.lxpfwj);
      Object.assign(lixiang.spyjTableData, data.projectSpyjs);
      Object.assign(lixiang.shclData.value, data.xgshcl);

      // 关联筛选
      resource.szjList.value =
        resource.jnwList.filter((item) => item.key == data.jnw)[0]?.children ||
        [];
      resource.dsgjList.value =
        resource.szjList.value.filter((item) => item.key == data.sjnzjjw)[0]
          ?.children || [];
      resource.qxgjList.value =
        resource.dsgjList.value.filter((item) => item.key == data.dsjngjjw)[0]
          ?.children || [];
      resource.tzsxejflList.value =
        resource.tzsxyjflList.filter((item) => item.key == data.tzsxyjfl)[0]
          ?.children || [];
      resource.tzsxxfbkList.value =
        resource.tzsxtzbkList.filter((item) => item.key == data.tzbk)[0]
          ?.children || [];
      resource.tzmdejflList.value =
        resource.tzmdyjflList.filter((item) => item.key == data.tzmdyjfl)[0]
          ?.children || [];
      resource.tzznejflList.value =
        resource.tzznyjflList.filter((item) => item.key == data.tzznyjfl)[0]
          ?.children || [];

      if (Number(formData.projectLzType) >= 5) {
        pageActiveName.value = "决策信息填报";
      }

      // 决策
      let jcData = res.juece || {};
      Object.assign(jcFormData, jcData);
      if (res.juece) {
        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.jcTzzeqkjData, jcData.projectXmtzzes);
        Object.assign(juece.jcCwpjzbData, jcData.projectCwpjzbs);
        Object.assign(juece.jcHxbjtjData, jcData.projectBjtjs);
        Object.assign(juece.jcztshqkData, jcData.projectJczts);
        Object.assign(juece.tzztshqkData, jcData.projectTzzts);
        Object.assign(juece.jcspyjData, jcData.projectSpyjs);
        Object.assign(juece.bhqkData, jcData.bhqk);
        Object.assign(juece.jxjlData, jcData.jxjlList);
        Object.assign(juece.jlrData, jcData.jlrList);
        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();
  resource.initResourceData();
});

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

// 保存数据
const saveClick = (type) => {
  if (!formData.projectLzType || Number(formData.projectLzType) <= 4) {
    let url = formData.id
      ? type === "submit"
        ? "startLixiang"
        : "saveProjectPreLixiang"
      : "createProject";
    let gdxxNewArr = JSON.parse(JSON.stringify(lixiang.gdxxData));
    gdxxNewArr.splice(-1);
    let params = {
      ...formData,
      projectJsgms: lixiang.swlzbData,
      projectGdxxs: gdxxNewArr,
      lxzl: lixiang.zcclData.value,
      projectXmtzzes: lixiang.tzzeqkjData,
      projectCwpjzbs: lixiang.cwpjzbData,
      projectBjtjs: lixiang.hxbjtjData,
      lxpfwj: lixiang.lxpfwjData.value,
      projectSpyjs: lixiang.spyjTableData,
      xgshcl: lixiang.shclData.value,
    };
    if (type === "submit") {
      params.buttonType = "submit";
    }
    proxy.$post({
      url: "/api/project/" + url,
      data: params,
      callback: (data) => {
        router.push("/projectDraft");
        router.back(-1);
      },
    });
  } else if (
    jcFormData.projectLzType.toString() === "5" ||
    jcFormData.projectLzType.toString() === "7" ||
    jcFormData.projectLzType.toString() === "8" ||
    jcFormData.projectLzType.toString() === "9"
  ) {
    let url = type === "submit" ? "startJuece" : "saveJuece";
    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,
      bhqk: juece.bhqkData,
      jxjlList: juece.jxjlData,
      jlrList: juece.jlrData,
    };
    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) => {
        router.push("/projectArgument");
      },
    });
  }
};

// 办理过程数据
const processInfo = computed(() => ({
  projectName: formData.projectName,
}));
const processTableData = ref([]);
const lxProcessData = computed(() =>
  processTableData.value.filter((r) => !r.actionName?.includes("决策"))
);
const jcProcessData = computed(() =>
  processTableData.value.filter((r) => r.actionName?.includes("决策"))
);
const getProcessData = () => {
  proxy.$post({
    url: "/api/project/getProFlowRecord",
    data: { projectId },
    callback: (data) => {
      processTableData.value = data || [];
    },
  });
};

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

// 核准
let approveFormData = ref({});
let approveForm = ref();
let approveDialogVisible = ref(false);
const approveRules = {
  approvalResult: [
    { required: true, message: "请选择核准意见", trigger: "change" },
  ],
};
const cancelApprove = () => {
  approveFormData.value = {};
  approveForm.value.resetFields();
  approveDialogVisible.value = false;
};
const submitApprove = () => {
  approveForm.value.validate((valid) => {
    if (valid) {
      proxy.$post({
        url: "/api/project/approvalLixiangByDepartHeader",
        data: {
          id: formData.id,
          ...approveFormData.value,
        },
        callback: (data) => {
          router.back(-1);
        },
      });
    }
  });
};
</script>
