<script setup>
import feedback from "@/utils/feedback";
import {getToken} from "@/utils/token";
import {BASE_PATH} from "@/api/request";
import useUserStore from "@/stores/modules/user";
import {timeFormat} from "@/utils/util";
import reportFile from '@/components/reportFile/index.vue';
import useCatchStore from '@/stores/modules/catch'
import reportAudit from '@/components/reportAudit/start.vue';
import reportAuditFinish from '@/components/reportAudit/finish.vue';
import reportAuditReject from '@/components/reportAudit/reject.vue';
import {getDetail, removeReportProject, saveReportProject,getExcelContrilPrice,upFinalizationPathFun} from "@/api/report/index";
import {useRoute, useRouter} from "vue-router";
import {getReportFlow} from "@/api/report/flow";
import useTabsStore from "@/stores/modules/multipleTabs";
import {listPolice} from "@/api/system/police";
import {fileDict,fileEndDict} from "@/enums/fileTableDictEnum";
import {recessedData} from "@/api/entryWindow/index";

import { getDictValue,getDepartContent } from "@/utils/util";
import {ElLoading} from "element-plus";
const {addTab, removeTab, tabList} =
    useTabsStore();

const filesData = ref([])
const router = useRouter();
const preview = ref(false);
const dialog = ref(false)
const actionRow = ref({})
const userStore = useUserStore();
const catchStore = useCatchStore();
const dict = catchStore.getDicts(["procurementMethod","AuditUnitPresetting","ReviewePresetSetting"]);
let formDataRef = ref()
let formReviewRef = ref()
const loading = ref(false)
const route = useRoute();
const finishDialog = ref(false)
const rejectDialog = ref(false)
const endDialog =ref(false)
const isAudit = ref(false)
const isEndData = ref(false)
let activeName = ref("initial")
const addFileDialog = ref(false)

let formData = ref({
  project: {
    projectType: null,
    node: 'initial'
  },
  files: {
    initial: [],
    exploration: [],
    cross: []
  },
  review: {
    isExploration:'2',
    isCross:'1'
  }
})
const fileTable = ref({
  request: false,
  type: "普通附件",
  fileName: null,
  fileNode: null
})
const addFileTableLoading = ref(false)

const catchSotre = useCatchStore();
const departs = catchStore.getDepartsAll();

const isDisabled = ref(false)
const isAuditButton = ref(false)
const datePicker = ref()
const serviceTime = ref([])


//获取详情
const getDetailFun = async (val) => {

  loading.value = true;

  formData.value = await getDetail({"id": val});
  if (route.query.disabledVal) {
    isDisabled.value = true
  }

  //报审
  if ((!['initial'].includes(formData.value.project.node))) {
    isDisabled.value = true;
  }

  if (route.query.node && !['initial'].includes(route.query.node)) {
    isDisabled.value = true;
  }
  if (route.query.isAudit) {
    isAuditButton.value = true
  }
  if(formData.value.project.isRecessed == 1){
    isDisabled.value = false;
  }
  //编辑
  if (route.query.isAudit && userStore.user) {
    //一审审计员
    if (formData.value.project.node === 'first') {
      formData.value.review.firstAuditor = userStore.user.nickName;
      rulesDataTwo.value.firstMoney = [
        {required: true, message: '请选择一审金额', trigger: 'blur'},

      ];
      rulesDataTwo.value.firstReduceMoney = [
        {required: true, message: '请选择一审审减金额', trigger: 'blur'},
      ];
      rulesDataTwo.value.firstTime = [
        {required: true, message: '请选择一审日期', trigger: 'blur'},
      ];
      rulesDataTwo.value.firstAuditor = [
        {required: true, message: '请输入一审审计人', trigger: 'blur'}
      ];

    }
    //二审审计员
    if (formData.value.project.node === 'second') {
      formData.value.review.secondAuditor = userStore.user.nickName;
      rulesDataTwo.value.secondMoney = [
        {required: true, message: '请选择二审金额', trigger: 'blur'},
      ];
      rulesDataTwo.value.secondReduceMoney = [
        {required: true, message: '请选择二审审减金额', trigger: 'blur'},
      ];
      rulesDataTwo.value.secondTime = [
        {required: true, message: '请选择二审日期', trigger: 'blur'},
      ];
      rulesDataTwo.value.secondAuditor = [
        {required: true, message: '请输入二审审计人', trigger: 'blur'}
      ];
      if(!formData.value.review.secondMoney){
        formData.value.review.secondMoney = formData.value.review.firstMoney || 0;
        formData.value.review.secondReduceMoney = formData.value.review.firstReduceMoney || 0;
      }
    }
    // 三审审计员
    if (formData.value.project.node === 'third') {
      formData.value.review.thirdlyAuditor = userStore.user.nickName;
      rulesDataTwo.value.thirdlyMoney = [
        {required: true, message: '请选择三审金额', trigger: 'blur'},

      ];
      rulesDataTwo.value.thirdlyReduceMoney = [
        {required: true, message: '请选择三审审减金额', trigger: 'blur'},
      ];
      rulesDataTwo.value.thirdlyTime = [
        {required: true, message: '请选择三审日期', trigger: 'blur'},
      ];
      rulesDataTwo.value.thirdlyAuditor = [
        {required: true, message: '请输入三审审计人', trigger: 'blur'}
      ];
      if(!formData.value.review.thirdlyMoney){
        formData.value.review.thirdlyMoney = formData.value.review.secondMoney || 0;
        formData.value.review.thirdlyReduceMoney = formData.value.review.secondReduceMoney || 0
      }
    }
    // 定案表审核
    if (formData.value.project.node === 'original') {
      rulesData.value.referenceNumber = [
        {required: true, message: '请输入文号', trigger: 'blur'}
      ];
      rulesData.value.publicationDate = [
        {required: true, message: '请选择发文日期', trigger: 'blur'}
      ];
    }
  }
  query.value.applicantId =formData.value.project?.applicantId;
  // query.value.departId = formData.value.project?.auditUnitId
  getPoliceList();
  await nextTick(() => {
    if (datePicker.value) {
      datePicker.value.handleClose()
    }
  })
  loading.value = false;

}

//审查内容是否允许编辑
const isAuditEdit = (val,label=null) => {
  if(formData.value.project.isRecessed == 1 && label === null){
    return false;
  }
  if (route.query.node) {
    return true;
  } else {
    if (val instanceof Array) {
      return !val.includes(formData.value.project.node)
    }
    return (formData.value.project.node !== val)
  }
}


const isAuditShow = (val,label=null) => {
  if(formData.value.project.isRecessed == 1 && label === null){
    return false;
  }
  if (route.query.node) {
    return true;
  } else {
    if (val instanceof Array) {
      return val.includes(formData.value.project.node)
    }
    return (formData.value.project.node == val)
  }
}
//删除附件
const delFileData = async (row,index) => {
  await feedback.confirm(`确认删除附件 ？`)
  if(row.request){
    row.fileData =[]
  }else{
    formData.value.files[activeName.value].splice(index,1)
  }
  row.fileData=[]
}
const rulesData = ref({
  reportType: [{required: true, message: '请选择报审类型', trigger: 'blur'}],
  reportName: [{required: true, message: '请输入项目名称', trigger: 'blur'}],
  projectType: [{required: true, message: '请选择项目类别', trigger: 'blur'}],
  auditUnitId: [{required: true, message: '请选择审计单位', trigger: 'blur'}],
  projectUnitId: [{required: true, message: '请选择项目单位', trigger: 'blur'}],
  projectPrincipal: [{required: true, message: '请选择报审类型', trigger: 'blur'}],
  projectPhone: [{required: true, message: '请选择负责人联系方式', trigger: 'blur'}],
  purchaseMethod: [{required: true, message: '请选择采购方式', trigger: 'blur'}],
  reportMoney: [{required: true, message: '请选择报审金额', trigger: 'blur'}],
  projectApprovalMoney: [{required: true, message: '请选择立项金额', trigger: 'blur'}],
  projectApprovalLead: [{required: true, message: '请选择报审领导', trigger: 'blur'}],
  applicant: [{required: true, message: '请输入报审人', trigger: 'blur'}],
  applicantTime: [{required: true, message: '请输入报审日期', trigger: 'blur'}],
  contractTime: [{required: true, message: '请输入合同签订日期', trigger: 'blur'}],
  contractMount: [{required: true, message: '请输入合同金额', trigger: 'blur'}],
  serviceUnit: [{required: true, message: '请输入服务单位', trigger: 'blur'}],
  serviceUnitManager: [{required: true, message: '请输入服务单位负责人', trigger: 'blur'}],
  serviceTime: [{required: true, message: '请输入报审日期', trigger: 'blur'}],
  serviceUnitPhone: [{required: true, message: '请输入服务单位联系电话', trigger: 'blur'}],
  projectApprovalTime: [{required: true, message: '请输入立项日期', trigger: 'blur'}],
  applyGovernmentTime: [{required: true, message: '请选择申报政府采购日期', trigger: 'blur'}],
  purchaseTime: [{required: true, message: '请选择采购日期', trigger: 'blur'}],
})
const rulesDataTwo = ref({
  reviewStatus: [
    {required: true, message: '请输入审查情况', trigger: 'blur'}
  ],
  reviewGist: [
    {required: true, message: '请输入审查依据', trigger: 'blur'}
  ],
  reviewContent: [
    {required: true, message: '请输入审计内容', trigger: 'blur'}
  ],
  isExploration: [
    {required: true, message: '请选择是否勘察', trigger: 'blur'}
  ],
  isCross: [
    {required: true, message: '请选择是否对审', trigger: 'blur'}
  ]
})
const files = ref([])
//关闭弹窗
const closeFile = () => {
  preview.value = false;
}

//获取流程
const reportFlowDialog = ref(false)
const reportFlowTable = ref([])
const  reportFlowLoading = ref(false)
const getReportFlowFun = async () => {
  reportFlowDialog.value = true
  reportFlowLoading.value=true
  const res = await getReportFlow({id:formData.value.project.id,code:'report'});
  reportFlowLoading.value=false
  reportFlowTable.value = res;
}

//保存数据
const saveFun = async () => {

  if (['initial', 'review'].includes(formData.value.project.node)) {
    await formDataRef.value.validate();
  } else if (["first", "second", "third"].includes(formData.value.project.node)) {
    await formReviewRef.value.validate();
  }
  loading.value = true;

  const res = await saveReportProject(formData.value);
  feedback.msgSuccess("保存成功");
  formData.value = res;
  await nextTick(() => {
    if (datePicker.value) {
      datePicker.value.handleClose()
    }
  })



  loading.value = false;
  return true;
}
//保存并且恢复
const saveUpRecessed =async ()=>{
  loading.value = true;

  const res = await saveReportProject(formData.value);
  formData.value = res;
  await nextTick(() => {
    if (datePicker.value) {
      datePicker.value.handleClose()
    }
  })
  //todo恢复入窗
  await feedback.confirm("确定要进窗吗？");
  const data = await  recessedData({id:formData.value.project.id});
  feedback.msgSuccess("已重新进窗")
  getDetailFun(formData.value.project.id)
  loading.value = false;
  return true;
}



//提交数据
const submitFun = async () => {
  await saveFun()
  dialog.value = true
}
//审核通过以后，展示详情
const submitFeedback = () => {
  dialog.value = false
  getDetailFun(formData.value.project.id)
  closeFun();
}

//获取单位为简称
// 获取单位为简称 - 性能优化：使用Map缓存查找结果
const departNameCache = new Map();
function getDepartShortName(departData, id, rowName) {
  // 优先从缓存获取
  const cacheKey = `${id}_${rowName}`;
  if (departNameCache.has(cacheKey)) {
    formData.value.project[rowName] = departNameCache.get(cacheKey);
    return;
  }
  if (departData) {
    for (let i = 0; i < departData.length; i++) {
      let s = departData[i];
      if (s.id === id) {
        formData.value.project[rowName] = s.shortName;
        departNameCache.set(cacheKey, s.shortName);
        break;
      }
      if (s.children) {
        const childResult = findDepartInChildren(s.children, id);
        if (childResult) {
          formData.value.project[rowName] = childResult;
          departNameCache.set(cacheKey, childResult);
          break;
        }
      }
    }
  }
}
// 辅助函数：递归查找子部门
function findDepartInChildren(children, id) {
  for (let i = 0; i < children.length; i++) {
    let s = children[i];
    if (s.id === id) {
      return s.shortName;
    }
    if (s.children) {
      const result = findDepartInChildren(s.children, id);
      if (result) return result;
    }
  }
  return null;
}

//获取tab名
const handleClick = (tab, event) => {
  activeName.value = tab.props.name
  filesData.value = []
}


//关闭
const closeFun = () => {
  if(route.query.disabledVal){
    useTabsStore().removeTab('/entryWindow', router);
    router.push({path:route.query.backPath})
  }
  if (route.query.node) {
    useTabsStore().removeTab('/report/edit/controlPrice', router);
    router.push({path:route.query.backPath})
  } else {
    useTabsStore().removeTab('/report/edit/controlPrice', router);
    router.push({path:"/work", query:{"load": true}})
  }
}

//入窗审批界面关闭
const closeAudit = () => {
  dialog.value = false
  finishDialog.value = false;
  rejectDialog.value = false
}
//根据输入值获取信息
const inputGetList = (val) => {
  query.value.name = val;
  getPoliceList()
}
//审核人
const query = ref({
  current: 1,
  size:100,
  departBranch: true
});
let polices = ref([])

function getPoliceList() {
  // query.value.departId = formData.value.project.auditUnitId;
  listPolice(query.value).then((data) => {
    polices.value = data.records;
  });
}

let date = ref()


//删除数据
const removeFun = async () => {
  await feedback.confirm("是否确认删除数据？");
  const res = await removeReportProject(route.query.id);
  closeFun();

}
//提交审批
const approveFun = async () => {
  if (!['initial', 'review'].includes(formData.value.project.node)) {
    const promise = await saveFun();
    if (promise) {
      finishDialog.value = true
      isAudit.value = true
    }
  }
  finishDialog.value = true
  isAudit.value = true
}
//结束
const endFun =async ()=>{
  endDialog.value = true
  isAudit.value = true
}

//驳回
const rejectFun = () => {
  isAudit.value = false
  rejectDialog.value = true;
}
//一审、二审、三审是否显示
const isShowFun = (list = []) => {
  if (route.query.node) {
    if (['Lead', 'original', 'audit','end'].includes(route.query.node)) {
      return true
    } else {
      return list.includes(route.query.node)
    }
  } else {
    if (['Lead', 'original', 'audit','end'].includes(formData.value.project.node)) {
      return true
    } else {
      return list.includes(formData.value.project.node)
    }
  }
}
//tab是否显示
function FileTabShowFun (){
  let show = true;
  if(!formData.value.project.node){
    return false;
  }
  let data =  formData.value.project.node;
  switch (data){
    case "initial":
    case "review":
      show=false;
      break
    default:
      show=true;
      break
  }

  return show;
}
//打开文件上传界面，记录文件上传行index
const  upFileDialog =ref(false)
let fileIndex = ref(0);
// 上传界面的打开
const showUpFileDialog = (index)=>{
  upFileDialog.value=true;
  fileIndex.value=index;
}
let  importLoading;
function beforeUpload() {
  importLoading = ElLoading.service({
    lock: true,
    text: "数据导入中",
    background: "rgba(0, 0, 0, 0.7)",
  });
}

//添加附件
const addFileTable =()=>{
  fileTable.value.fileNode =activeName.value
  addFileDialog.value=true;
}

const addFileSubmit = ()=>{
  addFileTableLoading.value=true;
  if(!formData.value.files[activeName.value]){
    formData.value.files[activeName.value] = []
  }
  formData.value.files[activeName.value].push(fileTable.value)
  addFileDialog.value=false;
  addFileTableLoading.value=false;
}
const fileDialogClose = ()=>{
  fileTable.value={
    request: false,
    type: "普通附件",
    fileName: null,
    fileNode: null,
    fileData:[]
  }
  addFileDialog.value=false;
}

//添加附件按钮是否显示
function addFileFun(val) {
  let show = true;
  switch (val) {
    case "initial":
      if (route.query.node) {
        show = route.query.node === 'initial';
      } else {
        show = formData.value.project.node === "initial"
      }
      break
    case "exploration":
    case "cross":
    case "audit":
      if (route.query.node) {
        show = false;
      } else {
        show = ["initial", "review", "Lead", "original", "audit","end"].indexOf(formData.value.project.node) < 0;
      }
      break;
  }
  if(formData.value.project.isRecessed == 1){
    return  true;
  }

  return show;
}
/**
 * 附件上传或删除
 * @param node 按钮所属tab
 * */
function disableFileBtn(node){
  //报审附件 initial
  //审核附件 audit
  //勘察附件 exploration
  //对审附件 cross
  let disable;
    switch (node){
      case "initial":
        //只在编辑环境可以使用
        disable = isDisabled.value;
        break;
      case "audit":
        disable =(['first','second','third','Lead'].indexOf(formData.value.project.node) < 0);
        break;
      case "exploration":
        disable =(['first','second','third','Lead'].indexOf(formData.value.project.node) < 0);
        break;
      case "cross":
        disable =(['first','second','third','Lead'].indexOf(formData.value.project.node) < 0);
        break;
      default:
        disable=true;
        break
    }
    //判断数据情况
    if(formData.value.project.isRecessed == 1){
      return  false;
    }
    return disable;

}




//定案表导出
const getExcelContrilPriceFun = async ()=>{
  if(formData.value.review.finalizationPath){
    window.open(`${BASE_PATH}/file/stream/${formData.value.review.finalizationPath}`);
  }else{
    let name =formData.value.project.reportName +  formData.value.project.reportType+"定案表.xls"
    const res = await  getExcelContrilPrice(formData.value.project.id, name);
  }
}

const isCityAudit = computed(()=>{
  if( formData.value?.project?.projectApprovalMoney){
    return  formData.value?.project?.projectApprovalMoney >= 200000
  }else{
    return  false;
  }
})




async function handleSuccess(result, file){
  importLoading.close();
  if (result.code !== 200) {
    feedback.msgError("上传失败");
    return;
  }

  formData.value.review.finalizationPath = result.data.filePath;
  const res = await  upFinalizationPathFun(formData.value);
  feedback.msgSuccess("导入完成")
}


// const DepartList  = ref(null)
//获取上级单位（判断超级管理员、是否二级单位）
const getSuperiorUnitByUnitFun = ()=>{
  let {project} = formData.value;
  let auditUnitId = getDictValue(dict.AuditUnitPresetting,"市局审计单位");
  let departId =  userStore.user.departId;

  //获取 二级单位列表，判断当前登陆人是否为二级单位
  let departList =  catchSotre.getDepartsAll();
  let departIds = departList.map(s=>s.id);
  if(departIds.indexOf(departId) >= 0){
    project.auditUnitId=auditUnitId;
  }
  // else{
  //   //获取它的上层单位
  //   const depart = getDepartContent(departs,departId);
  //   if(depart){
  //     DepartList.value =getDepartContent(departs,depart.pid)
  //   }
  //   project.auditUnitId =( depart!= null?depart.pid:auditUnitId);
  // }
  //
  // //判断是否是超级管理员
  // if(departId){
  //   if(auditUnitId === departId){
  //     DepartList.value=null;
  //     project.auditUnitId=auditUnitId;
  //   }else{
  //
  //   }
  // }else{
  //   project.auditUnitId=auditUnitId;
  // }
  getDepartShortName(departs,auditUnitId,'auditUnit');
}



//  监控是否为创建
watch(() => route.query.id, (val) => {
  if (val) {
    getDetailFun(val);
  } else {
    //初始化数据
    if (userStore.user) {
      query.value.applicantId = userStore.user.userName;
      formData.value.project.projectUnitId = userStore.user?.departId;
      formData.value.project.applicantId = userStore.user.userName;
      formData.value.project.applicant = userStore.user.nickName;
      formData.value.project.applicantTime =timeFormat(new Date(),'yyyy-mm-dd hh:MM:ss');
      getSuperiorUnitByUnitFun();
    }
  }
}, {deep: true, immediate: true})
//报审人姓名
watch(()=>formData.value.project.applicantId,(val)=>{
  if(val && polices.value.length > 0 && polices.value.filter(s=>s.idCode === val) > 0){
    formData.value.project.applicant =polices.value.filter(s=>s.idCode === val)[0].name;
  }
},{deep:true,immediate:true})



//监测是否是结算项目报审
watch(() => route.query.isEnd, (val) => {
  if(val){
    isEndData.value = val === 'true';
    if (isEndData.value) {
      formData.value.project.reportType = '结算项目'
    } else {
      formData.value.project.reportType = '项目控制价'
    }
  }else{
    //关闭窗口
    useTabsStore().removeTab('/report/edit/controlPrice', router);
  }

}, {deep: true, immediate: true})
//附件列表
watch(() => formData.value.project.projectType, (val) => {
  if (!(route.query.node || route.query.isAudit)) {
    let fileDataList = isEndData ? fileEndDict : fileDict;
    if (val) {
      let data = fileDataList.value.filter(s => s.type.includes(val))
      formData.value.files.initial = data ? data[0].fileData : fileDataList.value[0].fileData
    } else {
      formData.value.files.initial = fileDataList.value[0].fileData
    }
  }
}, {immediate: true, deep: true})
//监测单位，获取单位简称
watch(() => formData.value.project.projectUnitId, (val) => {
  if (val) {
    getDepartShortName(departs, val, 'projectUnit')
  }
}, {immediate: true, deep: true})
//监测审计单位，获取审计单位简称
watch(() => formData.value.project.auditUnitId, (val) => {
  if (val) {
    getPoliceList();
    getDepartShortName(departs, val, 'auditUnit')
  }
}, {immediate: true, deep: true})
//一审审减金额
watch(()=>formData.value.review.firstMoney,(val)=>{
  if( val){
    formData.value.review.firstReduceMoney =  formData.value.project.reportMoney  - formData.value.review.firstMoney
  }

},{deep:true})

//二审审减金额
watch(()=>formData.value.review.secondMoney,(val)=>{
  if(val){
    formData.value.review.secondReduceMoney = formData.value.project.reportMoney - formData.value.review.secondMoney
  }

},{deep:true})

//三审审减金额
watch(()=>formData.value.review.thirdlyMoney,(val)=>{
  if(val){
    formData.value.review.thirdlyReduceMoney = formData.value.project.reportMoney - formData.value.review.thirdlyMoney
  }

},{deep:true})



</script>

<template>
  <div class="wrapper" v-loading="loading">
    <main>
      <el-header>

        <h2 style="text-align: center">{{ isEndData ? '结算项目报审' : '控制价项目报审' }}</h2>
      </el-header>
      <el-main>
        <div class="flex v-center" style="height:30px;margin-bottom: 10px">
          <h5>报审信息</h5>
        </div>
        <div>
          <el-form :loading="loading" :model="formData.project" ref="formDataRef" :rules="rulesData" label-width="140">
            <el-row>
              <el-col :span="6">
                <el-form-item label="报审类型" prop="reportType">
                  <el-select disabled="true" v-model="formData.project.reportType">
                    <el-option value="项目控制价" label="项目控制价"></el-option>
                    <el-option value="结算项目" label="结算项目"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="项目名称" prop="reportName">
                  <el-input :disabled="isDisabled" v-model="formData.project.reportName"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="项目类别">
                  <el-select :disabled="isDisabled" v-model="formData.project.projectType">
                    <el-option value="服务类" label="服务类"></el-option>
                    <el-option value="工程类" label="工程类"></el-option>
                    <el-option value="货物类" label="货物类"></el-option>
                    <el-option value="信息化类" label="信息化类"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="审计单位" prop="auditUnitId">
                  <depart-tree-select :auth="false" :disabled="isDisabled" v-model="formData.project.auditUnitId"
                                      :size="'default'" placeholder="" clearable/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="项目单位" prop="projectUnitId">
                  <depart-tree-select :auth="false" :disabled="isDisabled" v-model="formData.project.projectUnitId"
                                      :size="'default'" placeholder="" clearable/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="项目负责人" prop="projectPrincipal">
                  <el-input :disabled="isDisabled" v-model="formData.project.projectPrincipal"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="负责人联系方式" prop="projectPhone">
                  <el-input :disabled="isDisabled" v-model="formData.project.projectPhone"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item v-if="isEndData" label="报审金额（元）" prop="reportMoney">
                  <el-input :disabled="isDisabled" type="number" v-model="formData.project.reportMoney"></el-input>
                </el-form-item>
                <el-form-item v-else label="采购方式" prop="purchaseMethod">
                  <el-select :disabled="isDisabled" v-model="formData.project.purchaseMethod">
                    <el-option v-for="(item,index) in dict.procurementMethod" :key="index"
                               :label="item.dictLabel"
                               :value="item.dictValue"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item v-if="isEndData" label="立项日期" prop="projectApprovalTime">
                  <el-date-picker
                      value-format="YYYY-MM-DD HH:mm:ss"
                      :disabled="isDisabled"
                      v-model="formData.project.projectApprovalTime"
                      style="width: 100%"
                      type="date"
                      placeholder="选择立项日期"
                  />
                </el-form-item>
                <el-form-item v-else label="报审金额（元）" prop="reportMoney">
                  <el-input :disabled="isDisabled" type="number" v-model="formData.project.reportMoney"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="立项金额（元）" prop="projectApprovalMoney">
                  <el-input :disabled="isDisabled" type="number"
                            v-model="formData.project.projectApprovalMoney"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="立项审批领导" prop="projectApprovalLead">
                  <el-input :disabled="isDisabled" v-model="formData.project.projectApprovalLead"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="报审人" prop="applicant">
                  <!--                <el-input :disabled="isDisabled" v-model="formData.project.applicant"></el-input>-->
                  <el-select :disabled="isDisabled" remote v-model="formData.project.applicantId"    :remote-method="inputGetList"
                             filterable>
                    <el-option v-for="(item,index) in polices" :key="index" :value="item.idCode"
                               :label="item.name"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6" v-if="isEndData && formData.project.projectApprovalMoney >= 200000 ">
                <el-form-item label="申报政府采购日期" prop="applyGovernmentTime">
                  <el-date-picker
                      value-format="YYYY-MM-DD HH:mm:ss"
                      :disabled="isDisabled"
                      v-model="formData.project.applyGovernmentTime"
                      style="width: 100%"
                      type="date"
                      placeholder="选择申报政府采购日期"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6" v-if="isEndData">
                <el-form-item label="采购方式" prop="purchaseMethod">
                  <el-select :disabled="isDisabled" v-model="formData.project.purchaseMethod">
                    <el-option v-for="(item,index) in dict.procurementMethod" :key="index"
                               :label="item.dictLabel"
                               :value="item.dictValue"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6" v-if="isEndData">
                <el-form-item label="采购日期" prop="purchaseTime">
                  <el-date-picker
                      value-format="YYYY-MM-DD HH:mm:ss"
                      :disabled="isDisabled"
                      v-model="formData.project.purchaseTime"
                      style="width: 100%"
                      type="date"
                      placeholder="选择采购日期"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="报审日期" prop="applicantTime">
                  <el-date-picker
                      value-format="YYYY-MM-DD HH:mm:ss"
                      :disabled="isDisabled"
                      v-model="formData.project.applicantTime"
                      style="width: 100%"
                      type="date"
                      placeholder="选择报审日期"
                  />
                </el-form-item>
              </el-col>
              <el-col v-if="!isEndData && !isAuditEdit(['original','audit'],'文号')" :span="6">
                <el-form-item label="文号" prop="referenceNumber">
                  <el-input  :disabled="isAuditEdit(['original','audit'])" v-model="formData.project.referenceNumber" />
                </el-form-item>
              </el-col>
              <el-col v-if="!isEndData && !isAuditEdit(['original','audit'],'发文日期')" :span="6">
                <el-form-item label="发文日期" prop="publicationDate">
                  <el-date-picker
                      value-format="YYYY-MM-DD HH:mm:ss"
                      :disabled="isAuditEdit(['original','audit'])"
                      v-model="formData.project.publicationDate"
                      style="width: 100%"
                      type="date"
                      placeholder="选择发文日期"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="isEndData">
              <el-col :span="6">
                <el-form-item label="合同签订日期" prop="contractTime">
                  <el-date-picker
                      value-format="YYYY-MM-DD HH:mm:ss"
                      :disabled="isDisabled"
                      v-model="formData.project.contractTime"
                      style="width: 100%"
                      type="date"
                      placeholder="选择报合同签订日期"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="合同金额" prop="contractMount">
                  <el-input :disabled="isDisabled" type="number" v-model="formData.project.contractMount"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="服务单位" prop="serviceUnit">
                  <el-input :disabled="isDisabled" v-model="formData.project.serviceUnit"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="服务单位负责人" prop="serviceUnitManager">
                  <el-input :disabled="isDisabled" v-model="formData.project.serviceUnitManager"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="isEndData">
              <el-col :span="6">
                <el-form-item label="服务日期" prop="serviceTime">
                  <el-date-picker
                      value-format="YYYY-MM-DD HH:mm:ss"
                      ref="datePicker"
                      :disabled="isDisabled"
                      v-model="formData.project.serviceTime"
                      type="daterange"
                      range-separator="-"
                      start-placeholder="开始服务日期"
                      end-placeholder="结束服务日期"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="服务单位联系电话" prop="serviceUnitPhone">
                  <el-input :disabled="isDisabled" v-model="formData.project.serviceUnitPhone"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6" v-if="!isAuditEdit(['original','audit'])">
                <el-form-item label="文号" prop="referenceNumber">
                  <el-input :disabled="isAuditEdit(['original','audit'])" v-model="formData.project.referenceNumber" />
                </el-form-item>
              </el-col>
              <el-col :span="6" v-if="!isAuditEdit(['original','audit'])">
                <el-form-item label="发文日期" prop="publicationDate">
                  <el-date-picker
                      value-format="YYYY-MM-DD HH:mm:ss"
                      :disabled="isAuditEdit(['original','audit'])"
                      v-model="formData.project.publicationDate"
                      style="width: 100%"
                      type="date"
                      placeholder="选择发文日期"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <hr style="border-color: rgba(232,232,232,0.67);opacity: 0.2">
        <div class="flex v-center" style="height:30px;margin-bottom: 10px">
          <h5>审计信息</h5>
        </div>
        <el-form
            v-if="!(['initial','review'].includes(formData.project.node) || ['initial','review'].includes(route.query.node))"
            :model="formData.review" ref="formReviewRef" :rules="rulesDataTwo" label-width="160">
          <!--        一审  -->
          <el-row :gutter="20" v-if="isShowFun(['first','second','third']) ">
            <el-col :span="6">
              <el-form-item label="一审金额(元)" prop="firstMoney">
                <el-input :disabled="isAuditEdit('first')" type="number" v-model="formData.review.firstMoney"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="一审审减金额(元)" prop="firstReduceMoney">
                <el-input :disabled="isAuditEdit('first')" type="number"
                          v-model="formData.review.firstReduceMoney"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="一审日期" prop="firstTime">
                <el-date-picker
                    value-format="YYYY-MM-DD HH:mm:ss"
                    :disabled="isAuditEdit('first')"
                                v-model="formData.review.firstTime"
                                style="width: 100%"
                                type="date"
                                placeholder="选择一审日期"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="一审审计员" prop="firstAuditor">
                <el-input :disabled="isAuditEdit('first')" v-model="formData.review.firstAuditor"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <!--        二审-->
          <el-row :gutter="20" v-if="isShowFun(['second','third'])">
            <el-col :span="6 ">
              <el-form-item label="二审金额(元)" prop="secondMoney">
                <el-input :disabled="isAuditEdit('second')" type="number"
                          v-model="formData.review.secondMoney"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="二审审减金额(元)" prop="secondReduceMoney">
                <el-input :disabled="isAuditEdit('second')" type="number"
                          v-model="formData.review.secondReduceMoney"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="二审日期" prop="secondTime">
                <el-date-picker
                    value-format="YYYY-MM-DD HH:mm:ss"
                    :disabled="isAuditEdit('second')"
                    v-model="formData.review.secondTime"
                    style="width: 100%"
                    type="date"
                    placeholder="选择二审日期"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="二审审计员" prop="secondAuditor">
                <el-input :disabled="isAuditEdit('second')" v-model="formData.review.secondAuditor"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <!--        三审-->
          <el-row :gutter="20" v-if="isShowFun(['third'])">
            <el-col :span="6">
              <el-form-item label="三审金额(元)" prop="thirdlyMoney">
                <el-input :disabled="isAuditEdit('third')" type="number"
                          v-model="formData.review.thirdlyMoney"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="三审审减金额(元)" prop="thirdlyReduceMoney">
                <el-input :disabled="isAuditEdit('third')" type="number"
                          v-model="formData.review.thirdlyReduceMoney"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="三审日期" prop="thirdlyTime">
                <el-date-picker
                    value-format="YYYY-MM-DD HH:mm:ss"
                    :disabled="isAuditEdit('third')"
                    v-model="formData.review.thirdlyTime"
                    style="width: 100%"
                    type="date"
                    placeholder="选择三审日期"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="三审审计员" prop="thirdlyAuditor">
                <el-input :disabled="isAuditEdit('third')" v-model="formData.review.thirdlyAuditor"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <!--审查依据-->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="审查情况" prop="reviewStatus">
                <el-input :disabled="isAuditEdit(['first','third','second'])" type="textarea" :rows="5"
                          v-model="formData.review.reviewStatus"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="审查依据" prop="reviewGist">
                <el-input :disabled="isAuditEdit(['first','third','second'])" type="textarea" :rows="5"
                          v-model="formData.review.reviewGist"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <!--审查内容-->
          <el-row :gutter="20">
            <el-col>
              <el-form-item label="审计内容" prop="reviewContent">
                <el-input :disabled="isAuditEdit(['first','third','second'])" type="textarea" :rows="5"
                          v-model="formData.review.reviewContent"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="勘察情况" prop="isExploration">
                <el-radio-group :disabled="isAuditEdit(['first','third','second'])"
                                v-model="formData.review.isExploration">
                  <el-radio value="1">已勘察</el-radio>
                  <el-radio value="2">未勘察</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="对审情况" prop="isCross">
                <el-radio-group :disabled="isAuditEdit(['first','third','second'])" v-model="formData.review.isCross">
                  <el-radio value="1">已对审</el-radio>
                  <el-radio value="2">未对审</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
           <el-col :span="12">

             <el-form-item label="定案表"  v-if="isAuditShow(['original','audit','end']) ">
               <div class="flex between">
                 <div >
                   <el-button  type="primary" link @click="getExcelContrilPriceFun">导出定案表</el-button>
                 </div>
                 <div  v-if="!isAuditEdit(['original']) ">
                   <el-upload
                       :multiple="false"
                       :show-file-list="false"
                       :action="`${BASE_PATH}/file/upload`"
                       :headers="{ Authorization: getToken() }"
                       :before-upload="beforeUpload"
                       @success="handleSuccess"
                   >
                     <el-button type="primary" link>
                       导入定案表
                     </el-button>
                   </el-upload>
                 </div>
               </div>
             </el-form-item>
           </el-col>
          </el-row>
        </el-form>

        <div class="table-container">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="报审附件" name="initial"></el-tab-pane>
            <el-tab-pane v-if="FileTabShowFun()" label="审核附件" name="audit"></el-tab-pane>
            <el-tab-pane v-if="formData.review?.isExploration === '1'" label="勘察附件" name="exploration"></el-tab-pane>
            <el-tab-pane v-if="formData.review?.isCross === '1'" label="对审附件" name="cross"></el-tab-pane>
            <el-tab-pane v-if="formData.review?.isCross === '1'" label="审计报告" name="sjbg"></el-tab-pane>
          </el-tabs>
          <el-table :data="formData.files[activeName]" preserve-expanded-content    style="z-index:9">
            <el-table-column type="expand">
              <template #default="props">
                <div v-if="props.row?.fileData">
                  <file-list   v-model:files="props.row.fileData" :removeEnable="false" ></file-list>
                </div>
                <div v-else>
                  <p style="color: darkgray;text-align: center">无附件</p>
                </div>
              </template>
            </el-table-column>
            <el-table-column width="100" type="index" label="序号" :index="(index)=> index+1"></el-table-column>
            <el-table-column label="附件类型" prop="type" width="150"></el-table-column>
            <el-table-column label="上传" width="200">
              <template #default="{$index,row}">
                <el-button type="primary" :disabled="disableFileBtn(activeName)" @click="showUpFileDialog($index)"
                >上传
                  <template #icon>
                    <icon name="el-icon-upload-filled"/>
                  </template>
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="删除" width="200">
              <template #default="{row,$index}">
                <el-button type="default" :disabled="disableFileBtn(activeName)"  @click="delFileData(row,$index)">删除
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="资料名称" prop="fileName" ></el-table-column>
            <el-table-column label="文件上传情况" prop="name"  show-overflow-tooltip>
              <template #default="{row}" >
                  <el-tag v-if="row.fileData && row.fileData.length > 0" type="success">已上传</el-tag>
                  <el-tag v-else>未上传</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="上传人"  prop="crtUser"></el-table-column>
            <el-table-column label="上传时间"  prop="crtTime"></el-table-column>

          </el-table>
          <div v-if="addFileFun(activeName)"
               class="mb-10"
               style="display: flex;justify-content: center;align-items: center;width: 100%">
            <el-button type="primary" style="width: 80vw;height: 30px;margin-top: 20px" @click="addFileTable()">新增附件</el-button>
          </div>
        </div>

        <div class="flex end mt-20" v-if="formData.project && formData.project.isRecessed == 1">
          <el-button type="primary" :loading="loading" @click="saveFun">保存</el-button>
          <el-button type="primary" :loading="loading" @click="saveUpRecessed">重新进窗</el-button>
        </div>
        <div v-else-if="isAuditButton" class="flex end mt-20">
          <el-button @click="closeFun">关闭</el-button>
          <el-button type="primary" @click="getReportFlowFun">审批记录</el-button>
          <el-button type="primary" @click="removeFun">删除</el-button>
          <el-button v-if="!isAuditEdit('audit')" type="primary" @click="endFun" >结束</el-button>
          <el-button v-else type="primary" @click="approveFun">提交</el-button>
          <el-button type="danger" @click="rejectFun">驳回</el-button>
        </div>
        <div v-if="route.query.disabledVal" class="flex end mt-20">
          <el-button type="danger" @click="removeFun">删除</el-button>
          <el-button @click="closeFun">关闭</el-button>
        </div>
        <div class="flex end mt-20" v-else >
          <el-button v-if="!isDisabled" type="primary" @click="submitFun">提交</el-button>
          <el-button v-if="!isDisabled" type="primary" @click="saveFun">保存</el-button>
          <el-button v-if="!isAuditButton && !isDisabled" @click="closeFun">取消</el-button>

          <el-button v-if="!isAuditButton && isDisabled" type="primary" @click="getReportFlowFun">审批记录</el-button>
        </div>

      </el-main>
    </main>
  </div>

  <el-dialog v-model="addFileDialog" title="上传附件" width="60vw" @close="fileDialogClose">
    <el-form label-width="120">
      <el-row>
       <el-col :span="24">
         <el-form-item label="资料名称">
           <el-input v-model="fileTable.fileName"></el-input>
         </el-form-item>
       </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <file-upload   v-model:files="fileTable.fileData"  :uploadDrag="true" ></file-upload>
        </el-col>
      </el-row>
      <footer class="flex end">
        <el-button size="default"  :loading="addFileTableLoading" type="primary" @click="addFileSubmit">确认</el-button>
        <el-button  @click="addFileDialog = false" >关闭</el-button>
      </footer>
    </el-form>
  </el-dialog>


  <el-dialog v-model="reportFlowDialog" title="审批记录" width="80vw">
    <div class="table-container">
      <el-table :data="reportFlowTable" v-loading="reportFlowLoading">
        <el-table-column width="50" type="index" label="序号" :index="(index)=> index+1"></el-table-column>
        <el-table-column label="操作" prop="reportCode"></el-table-column>
        <el-table-column label="办理人" prop="approver"></el-table-column>
        <el-table-column label="提交时间" prop="areportTime">
          <template #default="{row}">
            {{ timeFormat(row.areportTime,'yyyy-mm-dd hh:MM:ss') }}
          </template>
        </el-table-column>
        <el-table-column label="完成时间" prop="approverTime">
          <template #default="{row}">
            {{ timeFormat(row.approverTime,'yyyy-mm-dd hh:MM:ss') }}
          </template>
        </el-table-column>
        <el-table-column label="办理结果" prop="approverState">
          <template #default="{row}">
            <el-tag type="primary" v-if="row.approverState === '开始'">开始</el-tag>
            <el-tag type="success" v-if="row.approverState === '结束'">完成</el-tag>
            <el-tag type="danger" v-if="row.approverState === '驳回'">驳回</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="办理意见" prop="approverMessage" show-overflow-tooltip></el-table-column>
        <el-table-column label="办理状态" prop="approverState"></el-table-column>
      </el-table>
    </div>
  </el-dialog>

  <el-dialog v-model="upFileDialog" title="材料上传" destroy-on-close>
    <file-upload   v-model:files="formData.files[activeName][fileIndex].fileData"  :uploadDrag="true" ></file-upload>
    <footer class="flex end">
      <el-button type="primary" @click="upFileDialog = false" size="large">确认</el-button>
      <el-button @click="upFileDialog = false" size="large">关闭</el-button>
    </footer>
  </el-dialog>

  <report-file :preview="preview" :activeFile="actionRow" @closeFile="closeFile"/>
  <report-audit @submitFeedback="submitFeedback" @closeFun="closeAudit" :reportId="formData.project.id" :isCityAudit="isCityAudit"
                :dialog="dialog"/>
  <report-audit-finish @submitFeedback="submitFeedback" @closeFun="closeAudit" :node="formData.project.node"
                       :reportId="formData.project.id" :dialog="finishDialog" :isAudit="true"></report-audit-finish>
  <report-audit-reject @submitFeedback="submitFeedback" @closeFun="closeAudit" :node="formData.project.node"
                       :reportId="formData.project.id" :dialog="rejectDialog" :isAudit="false"></report-audit-reject>
  <report-audit-end  @submitFeedback="submitFeedback" @closeFun="closeAudit" :node="formData.project.node"
                     :reportId="formData.project.id" :dialog="endDialog" :isAudit="true"
  ></report-audit-end>
</template>

<style  lang="scss">
.el-table .el-table__cell{
  position: initial !important;
}

</style>
