<template>
  <div>
    <MOSTY.PageTree  :searchType="'03'" @getDeptId="getdeptId">
      <template #titleright>
        <div class="toggle" :class="{ active: isOpen }" @click="isOpen = !isOpen">
          <span>统计</span>
          <el-icon>
            <DArrowLeft />
          </el-icon>
        </div>
      </template>
      <template #serach>
        <section v-show='isOpen' ref="getHeight">
          <section class="box-sjtj">
            <MOSTY.Assort :title="'安全预算统计'" style="padding: 0;" />
            <section class="flex">
              <section class="left-tj">
                <Sjtj :info="countlist" :isShowTip="false" :isShowBottom="false" :width="400" mb="6px" />
              </section>
            </section>
          </section>
        </section>
        <el-divider />
        <MOSTY.Search :searchArr="searchArr" @submit="onSearch" :noDisabledDate='true'>
          <!-- <template #searbox>
            <MOSTY.Department style="width: 250px" :searchType="'04'" placeholder="请选择使用部门" clearable :deptType="'01'"
              v-model="listQuery.orgid" />
          </template> -->
        </MOSTY.Search>
        <el-divider />
        <div class="btnBox">
          <!-- 只有当前登录的安全部门可以新增（） -->
          <el-button type="primary" @click="onAddys('ncadd', '年度预算调整新增')">
            <!--  v-if="ssdept.orgBizType == '04' || ssdept.orgBizType == '52'" -->
            <el-icon>
              <CirclePlus />
            </el-icon>

            <span>年度预算调整新增</span>
          </el-button>
          <el-button type="primary" @click="onAddys('nzadd', '中期预算调整新增')">
            <!--  v-if="ssdept.orgBizType == '04' || ssdept.orgBizType == '52'" -->
            <el-icon>
              <CirclePlus />
            </el-icon>
            <span>中期预算调整新增</span>
          </el-button>
          <!-- <el-button type="primary" @click="onAddys('ndadd', '年度预算调整新增')"
            v-if="ssdept.orgBizType == '04' || ssdept.orgBizType == '52'">
            <el-icon>
              <CirclePlus />
            </el-icon>
            <span>年度预算调整新增</span>
          </el-button> -->
          <el-button type="primary" v-loading="loadingShow" @click="onloadExcel">
            <el-icon>
              <Download />
            </el-icon>
            <span>导出</span>
          </el-button>
        </div>
      </template>
      <template #table>
        <section :style="{ 'height': totalHeight }">
          <MOSTY.Table :table-columns="tableColumns" :tableData="tableData" :tableloading="tableloading"
            :isSelect="false" :isSort="false" :tableHeight="'100%'" @SortChange="SortChange" :actionsW="300">
            <template #ctype="{ row }">
              <dict-tag v-if="row.ctype" :options="D_BZ_YSFYLB" :value="row.ctype" :tag="false" />
              <span v-else>无</span>
            </template>
            <template #cwkm="{ row }">
              <dict-tag v-if="row.cwkm" :options="D_TB_YSCWKU" :value="row.cwkm" :tag="false" />
              <span v-else>无</span>
            </template>
            <template #costFee="{ row }">
              {{ row.costFee || 0 }}
            </template>
            <template #actions="{ row }">
              <span v-if="row.state == '0' && row.verifyuserid == USERID" class="operesee"
                @click="ysshbtn(row, 'ncsh')"><el-icon>
                  <Edit />
                </el-icon>年度审核</span>
              <span v-if="row.state == '1' && row.middlestate == '1' && row.verifyuserid == USERID" class="operesee"
                @click="ysshbtn(row, 'nzsh')"><el-icon>
                  <Edit />
                </el-icon>中期审核</span>
              <!-- <span class="operesee"
                v-if="row.middlestate == '2' && row.yearstate != '2' && row.verifyuserid == USERID"
                @click="ysshbtn(row, 'ndsh')"><el-icon>
                  <Edit />
                </el-icon>年度预算调整审核
              </span> -->
              <span class="operedit" @click="xgInfo(row)"><el-icon>
                  <EditPen />
                </el-icon>修改</span>
              <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red"
                title="删除预算项目时，会同时删除预算项目下的使用记录。" @confirm="handledelete(row)">
                <template #reference>
                  <span class="operdel" size="small"><el-icon>
                      <Delete />
                    </el-icon>删除</span>
                </template>
              </el-popconfirm>
              <span class="operesee" v-if="row.middlestate == '2' || row.state == '1' || row.state == '0'"
                @click="seeInfo(row)">
                <el-icon>
                  <View />
                </el-icon>查看</span>
            </template>
          </MOSTY.Table>
        </section>
        <div class="fenye">
          <MOSTY.Pages :pageConfiger="pageConfiger" @changeNo="handleCurrentChange" @changeSize="handleSizeChange" />
        </div>
      </template>
    </MOSTY.PageTree>
    <!-- 新增 -->
    <div class="dialog-box" v-if="addysShow">
      <aqyslbinfo v-if="addysShow" @close="addysShow = false;" @resttab="resetTable" :saveBtnShow="saveBtnShow"
        :title="title" :sybmlist="sybmlist" :type="type" :id="rowid" :orgcode="orgids" />
    </div>
    <div class="dialog-box" v-if="addplanShow">
      <aqyslnd @close="addplanShow = false; type = null" @resttab='resetTable' :saveBtnShow="saveBtnShow" :title="title"
        :type="type" :id="rowid" :sybmlist="sybmlist" />
    </div>
  </div>
</template>

<script setup>
// 引入
import { reactive, onMounted, ref, getCurrentInstance, nextTick, watch } from 'vue'
import aqyslbinfo from "./commponents/aqyslbinfo.vue";
import { ElMessage } from "element-plus";
import * as MOSTY from "@/components/MyComponents/index";
import { getApi, deleteApi, putApi, postApi } from "@/api/tobAcco_api.js";
import aqyslnd from "./commponents/aqyslnd.vue";
import { exportXlsx, downloadImg } from "@/excel/Export2Excel.js";
import { getItem } from "@/utils/storage";
import { filterYear } from "@/utils/auth.js";
import { numAdd } from "@/utils/tools.js";
import Sjtj from '@/views/dataReportWork/aqjypx/components/sjtj.vue'
import {
  getDept
} from "@/api/user-manage";
const { proxy } = getCurrentInstance();
const { D_BZ_YSFYLB, D_TB_YSCWKU } = proxy.$dict("D_BZ_YSFYLB", "D_TB_YSCWKU");
const sybmlist = ref([])
const addplanShow = ref(false);
const addysShow = ref(false);
const searchArr = reactive([
  {
    showType: "year",
    prop: "years",
    width: '250px',
    defaultVal: new Date().getFullYear().toString(),

  },
  {
    showType: "selectTree",
    prop: "ctype",
    width: '250px',
    options: 'D_BZ_YSFYLB',
    placeholder: '请选择预算类别'
  },
  {
    showType: "selectTree",
    prop: "cwkm",
    width: '250px',
    options: 'D_TB_YSCWKU',
    placeholder: '请选择财务科目'
  },

]);
const countlist = reactive([
  { title: '总预算', num: 0.0000 + '万元', dm: 'budgetmoney', icon: 'ccss/icon_02.png' },
  { title: '总使用', num: 0.0000 + '万元', dm: 'totalcost', icon: 'ccss/icon_03.png' },
  { title: '总剩余', num: 0.0000 + '万元', dm: 'symoney', icon: 'ccss/icon_04.png' }
])
const loadingShow = ref(false);
const tableloading = ref(false)
const USERID = getItem("USERID")
const ssdept = getItem("deptId")
const title = ref('');//弹窗标题
const type = ref('01');//控制弹窗参数(01:年初预算调整审核新增)
const rowid = ref(null)
const listQuery = reactive({
  pageCurrent: 1,
  pageSize: 20,
  years: new Date().getFullYear().toString(),
  orgid: null,
  ctype: null
});
const isOpen = ref(false);
const tableData = ref([])

const pageConfiger = reactive({
  pageSize: 20,
  pageCurrent: 1,
  total: 0
})
const tableColumns = reactive([
  {
    title: "使用部门",
    prop: "usedeptname",
    fixed: 'left',
    width: '200',
  },
  {
    title: "预算项目",
    prop: "budgettitle",
    width: '200',
  },
  {
    title: "财务科目",
    prop: "cwkm",
    width: '180',
    slot: true,
  },
  {
    title: "预算类别",
    prop: "ctype",
    width: '200',
    slot: true
  },
  {
    title: "使用金额(万元)",
    prop: "costFee",
    width: '200',
    slot: true
  },
  {
    title: "剩余金额(万元)",
    prop: "symoney",
    width: '200',
  },
  {
    title: "年初预算调整金额(万元)",
    prop: "budgetmoney",
    width: '200',
  },

  {
    title: "年初批复",
    prop: "budget",
    width: '200',
  },
  {
    title: "中期调整增减数",
    prop: "tzzj",
    width: '200',
  },
  {
    title: "中期归口审核增减数",
    prop: "gkshzj",
    width: '200',
  },
  // {
  //   title: "年度调整增减数",
  //   prop: "yeartzzj",
  //   width: '200',
  // },
  // {
  //   title: "年度归口审核增减数",
  //   prop: "yeargkshzj",
  //   width: '200',
  // },
  {
    title: "操作",
    prop: "actions",
    fixed: 'right',
    slot: true
  }
])

const deptid = ref(null)
const orgids = ref(null)
const totalHeight = ref(null)
const getHeight = ref(null)
watch(() => isOpen.value, (val) => {
  nextTick(() => {
    if (val) {
      totalHeight.value = `calc(100vh - ${379 + getHeight.value.offsetHeight}px)`
      return
    }
    totalHeight.value = `calc(100vh - 379px)`
  })
}, {
  deep: true,
  immediate: true
})

onMounted(() => {
  nextTick(() => {
    totalHeight.value = `calc(100vh - ${379 + getHeight.value.offsetHeight}px)`
  })
  getTotaldata()
})
//获取年初查询年初统计
function getTotaldata() {
  getApi(listQuery, "/mosty-jcgl/budgets/getNcBudgetsSum").then((res) => {
    countlist[0].num = res.budget ? `${Number(res.budget).toFixed(4)}万元` : `${0.0000}万元`;
    countlist[1].num = res.totalcost ? `${Number(res.totalcost).toFixed(4)}万元` : `${0.0000}万元`;
    countlist[2].num = res.budget != 0 ? `${numAdd("reduce", 4, res.budget, res.totalcost)}万元` : `${0.0000}万元`;
  });
}
//刷新
function resetTable(val) {
  listQuery.pageSize = 20
  listQuery.pageCurrent = 1
  listQuery.orgid = orgids.value;
  listQuery.ctype = ''
  deptid.value = ''
  listQuery.years = new Date().getFullYear().toString()
  getDataList();
  getTotaldata()
}
//获取部门参数
const getdeptId = (val) => {
  listQuery.orgid = val.id;
  orgids.value = val.id
  listQuery.pageCurrent = 1
  getDataList();
  getTotaldata()
}
//查询
function onSearch(obj) {
  listQuery.pageCurrent = 1
  listQuery.ctype = obj.ctype;
  listQuery.years = obj.years;
  listQuery.cwkm = obj.cwkm;
  getDataList();
  getTotaldata()
}
//ALL_查询安全投入列表
function getDataList() {
  tableloading.value = true
  getApi(listQuery, '/mosty-jcgl/budgets/getNcBudgetsPage').then((res) => {
    if (res.records) {
      tableloading.value = false;
      tableData.value = res.records;
      tableData.value.forEach(async (item) => {
        item.budget = item.budget ? item.budget : 0;
        item.budgetmoney = item.budgetmoney ? item.budgetmoney : 0;
        item.tzzj = item.tzzj ? item.tzzj : 0;
        item.gkshzj = item.gkshzj ? item.gkshzj : 0;
        item.yeargkshzj = item.yeargkshzj ? item.yeargkshzj : 0;
        item.yeartzzj = item.yeartzzj ? item.yeartzzj : 0;
        item.pfjeall = numAdd("add", 4, item.budget, item.gkshzj, item.yeargkshzj)
        item.symoney = numAdd("reduce", 4, item.pfjeall, item.costFee);
      })
      pageConfiger.total = res.total;
    }
  }).catch((err) => {
    tableData.value = []
    tableloading.value = false;
  }).finally(() => {
    tableloading.value = false;
  })
}
//添加预算
function onAddys(types, val) {

  title.value = val;
  type.value = types;
  rowid.value = null;
  if (types == 'ndadd') {
    addplanShow.value = true
  } else {
    addysShow.value = true;
  }

}
//年初预算调整审核
function ysshbtn(val, types) {
  type.value = types;
  rowid.value = val.id;
  if (types == 'ncsh') {
    title.value = "年度审核预算"; // “年初”改为“年度”， 年度去掉
    addysShow.value = true;
  } else if (types == 'nzsh') {
    title.value = "中期审核预算";
    addysShow.value = true;
  } else {
    // title.value = '年度预算调整审核';
    // addplanShow.value = true
  }
}

//修改预算
function xgInfo(val) {
  rowid.value = val.id
  if (val.state == '0') {
    title.value = "年度修改预算"; // “年初”改为“年度”， 年度去掉
    type.value = "ncexit";
    addysShow.value = true;
  } else if (val.state == '1' && val.middlestate == '1') {
    title.value = '中期预算调整调整修改';
    type.value = 'nzexit';
    addysShow.value = true;
  } else if (val.middlestate == '2' && val.yearstate != '2') {

    title.value = '年度预算调整调整修改';
    type.value = 'ndexit';
    addplanShow.value = true
  }
}

//查看预算
function seeInfo(val) {
  rowid.value = val.id
  if (val.state == '0') {
    title.value = "年度预算调整详情"; // “年初”改为“年度”， 年度去掉
    type.value = "ncdetails";
    addysShow.value = true;
  } else if (val.state == '1' && val.middlestate == '1') {
    title.value = '中期预算调整详情';
    type.value = 'nzdetails';
    addysShow.value = true;
  } else if (val.middlestate == '2') {
    title.value = '年度填报详情';
    type.value = 'nddetails';
    addplanShow.value = true
  }

}

//删除
function handledelete(val) {
  postApi({}, `/mosty-jcgl/budgets/ncDel/${val.id}`).then((res) => {
    ElMessage.success("删除成功");
    resetTable();
  });
}
//分页
const handleSizeChange = (currentSize) => {
  listQuery.pageSize = currentSize;
  pageConfiger.pageSize = currentSize;
  getDataList();
};
const handleCurrentChange = (currentPage) => {
  listQuery.pageCurrent = currentPage;
  pageConfiger.pageCurrent = currentPage;
  getDataList();
};
//导出Excel
function onloadExcel() {
  let title = {
    usedeptname: '使用部门',
    budgettitle: '预算项目',
    ctype: '预算类别',
    cwkm: '财务科目',
    costFee: '使用金额',
    symoney: '剩余金额',
    budgetmoney: '年初预算调整金额',
    budget: '年初批复',
    tzzj: '中期调整增减数',
    gkshzj: '中期归口审核增减数',
    yeartzzj: '年度调整增减数',
    yeargkshzj: '年度归口审核增减数',
  }
  let obj = { ...listQuery };
  obj.pageSize = 10000
  loadingShow.value = true
  getApi(obj, '/mosty-jcgl/budgets/ncExportData').then(async (res) => {
    if (res) {
      let data = res
      if (data) {
        for (let i = 0; i < data.length; i++) {
          data[i].ctype = proxy.$getDictVal(data[i].ctype, D_BZ_YSFYLB);
          data[i].cwkm = proxy.$getDictVal(data[i].cwkm, D_TB_YSCWKU);
          data[i].budget = data[i].budget ? data[i].budget : 0
          data[i].budgetmoney = data[i].budgetmoney ? data[i].budgetmoney : 0
          data[i].tzzj = data[i].tzzj ? data[i].tzzj : 0
          data[i].gkshzj = data[i].gkshzj ? data[i].gkshzj : 0
          data[i].yeartzzj = data[i].yeartzzj ? data[i].yeartzzj : 0
          data[i].yeargkshzj = data[i].yeargkshzj ? data[i].yeargkshzj : 0
          data[i].pfjeall = numAdd("add", 4, data[i].budget, data[i].totalcost, data[i].yeargkshzj)
          data[i].symoney = numAdd("reduce", 4, data[i].pfjeall, data[i].costFee);
        }
        let tablename = "预算填报列表.xlsx"
        exportXlsx(title, data, '预算填报列表', tablename);
        loadingShow.value = false
      }
    }

  }).catch(err => {
    loadingShow.value = false
  })
}



</script>

<style lang="scss" scoped>
.btnBox {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 12px;
}

.toggle {
  height: 40px;
  cursor: pointer;
  display: flex;
  align-items: center;
  color: #0f3916;

  .el-icon {
    transform: rotate(90deg);
    transition: all 0.25s ease;
  }

  &.active {
    .el-icon {
      transform: rotate(-90deg);
    }
  }
}
</style>
