<template>
  <el-dialog :title="title" v-model="isShowDialog" width="90vw" :before-close="beforeClose">

    <div style="height: 80vh;overflow-y: auto;">
      <div style="display: flex;justify-content: end;margin-bottom: 5px;">
        <!-- <el-button type="primary" v-loading="loadingShow" @click="onloadExcel">
          <el-icon>
            <Download />
          </el-icon>
          <span>导出</span>
        </el-button> -->
      </div>
      <MOSTY.PageTree :searchType="'03'" :isShowLeftTree="false">

        <template #serach>
        </template>
        <template #table>
          <section :style="{ 'height': totalHeight }">
            <MOSTY.Table :table-columns="tableColumns" :tableData="tableData" :tableloading="tableloading"
              :isSelect="false" :isSort="false" :tableHeight="'100%'" :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 #state="{ row }">
                <dict-tag v-if="row.state" :options="stateOpt" :value="row.state" :tag="true" />
                <span v-else>无</span>
              </template>
              <template #actions="{ row }">
                <span class="operesee" @click="seeDetail(row)"><el-icon>
                    <Compass />
                  </el-icon>查看明细</span>
                <span v-if="isEdit" class="operedit" @click="seeDetail(row, 'edit')"><el-icon>
                    <EditPen />
                  </el-icon>使用登记
                </span>
                <!-- <span v-if="isEdit && row.state == '6'" class="operedit" @click="seeDetail(row, 'edit')"><el-icon>
                    <EditPen />
                  </el-icon>使用登记
                </span> -->
              </template>
            </MOSTY.Table>
          </section>
          <div class="fenye" :style="{ top: totalHeight + 'px' }">
            <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
              :current-page="listQuery.page" :page-sizes="[2, 5, 10, 20]" :page-size="listQuery.size"
              layout="total, prev, pager, next, sizes, jumper" :total="pageConfiger.total"></el-pagination>
          </div>
        </template>

      </MOSTY.PageTree>
      <pageList v-if="isShowPageList" :isEdit="isEditTc" :title="`${currRow.budgettitle || ''}-详情`"
        :years="listQuery.years" :row="currRow" @close="pageListClose" />
    </div>
  </el-dialog>

</template>

<script setup>
// 引入
import { reactive, onMounted, ref, getCurrentInstance, nextTick, watch, computed, defineProps, defineEmits } from 'vue'
import { ElMessage } from "element-plus";
import * as MOSTY from "@/components/MyComponents/index";
import { getApi, deleteApi, putApi, postApi } from "@/api/tobAcco_api.js";
import { exportXlsx, downloadImg } from "@/excel/Export2Excel.js";
import { getItem } from "@/utils/storage";
import { filterYear, filterqx } from "@/utils/auth.js";
import { numAdd } from "@/utils/tools.js";
import pageList from './pageList.vue';
import Big from "@/utils/big.js"

const { proxy } = getCurrentInstance();
const { D_BZ_YSFYLB, D_TB_YSCWKU } = proxy.$dict("D_BZ_YSFYLB", "D_TB_YSCWKU");
const props = defineProps(['years', 'row', 'isEdit'])
const emits = defineEmits(['close'])

const xgsTCTitle = ref('')
const isShowPageList = ref(false)
const isEditTc = ref(false)

const loadingShow = ref(false);
/** 是否显示 审核弹框 */
const isShowAuditDialog = ref(false)
/** 当前查看或审核行 */
const currRow = ref({})


const beforeClose = () => {
  emits('close')
}

const tableloading = ref(false)
const title = ref('');//弹窗标题
const isShowDialog = ref(true);

const listQuery = reactive({
  pageCurrent: 1,
  pageSize: 20,
  years: props.years,
  deptId: props.row.orgid,
});
const isOpen = ref(false);

/**
 * @typedef {Object} YsType - 预算数据类型定义
 * @property {string} id - 主键ID
 * @property {string} adjust - 中期是否调整 (1-是, 0-否)
 * @property {number} budget - 预算（已审核）年初批复
 * @property {number} budgetmoney - 预算金额
 * @property {string} budgettitle - 预算标题
 * @property {string} bz - 备注
 * @property {number} costFee - 已使用金额
 * @property {string} ctype - 预算类别 (D_BZ_YSFYLB)
 * @property {string} cwkm - 财务科目 (D_TB_YSCWKU)
 * @property {string} deptid - 使用部门ID
 * @property {string} deptname - 使用部门名称
 * @property {string} files - 附件路径
 * @property {number} gkshzj - 归口审核增减数
 * @property {number} lastyearmoney - 去年使用金额
 * @property {number} operation - 作业量
 * @property {string} orgid - 使用单位ID
 * @property {string} orgname - 使用单位名称
 * @property {number} quotastandard - 定额标准
 * @property {string} state - 审批状态 (0-未上报, 1-县公司安全部门负责人, 2-市州公司安全部门负责人审批, 3-省局公司安全部门负责人审批, 4-审批通过, 5-已上报, 6-审批通过)
 * @property {string} type - 类型 (01-年度预算填报, 02-中期预算填报)
 * @property {number} tzzj - 调整增减数
 * @property {string} years - 年份
 * @property {string} yssm - 预算说明
 */

/** @type {YsType[]} 表格数据 */
const tableData = ref([])

const pageConfiger = reactive({
  pageSize: 20,
  pageCurrent: 1,
  total: 0
})
const tableColumns = reactive([
  {
    title: "预算项目",
    prop: "budgettitle",
    fixed: 'left',
    width: '180',
  },
  // {
  //   title: "财务科目",
  //   prop: "cwkm",
  //   width: '180',
  //   slot: true,
  // },
  {
    title: "预算类别",
    prop: "ctype",
    width: '200',
    slot: true
  },
  {
    title: "使用部门",
    prop: "deptname",
    width: '180',
  },


  // {
  //   title: "年初预算调整金额(万元)",
  //   prop: "budgetmoney",
  // },

  {
    title: "年初批复",
    prop: "firstApprovedBudget", //  , budget
  },
  {
    title: "中期调整增减数",
    prop: "tzzj",
  },
  {
    title: "使用金额(万元)",
    prop: "costFee",
    slot: true
  },
  {
    title: "剩余金额(万元)",
    prop: "symoney",
  },
  // {
  //   title: "中期归口审核增减数",
  //   prop: "gkshzj",
  // },

  // {
  //   title: "状态",
  //   prop: "state",
  //   fixed: 'right',
  //   slot: true
  // },
  {
    title: "操作",
    prop: "actions",
    fixed: 'right',
    slot: true
  }
])

const deptid = ref(null)
const orgids = ref(null)
const totalHeight = ref(null)
const getHeight = ref(null)
const stateOpt = [
  { label: '未上报', value: '0', elTagType: 'ysshpf-oper-red' },
  { label: '部门已上报', value: '1' },
  { label: '县安全部门负责人审批', value: '2' },
  { label: '市安全部门负责人汇总', value: '3' },
  { label: '市安全部门负责人审核', value: '4' },
  { label: '省安全部门负责人审核', value: '5' },
  { label: '审批通过', value: '6' },
];
watch(() => isOpen.value, (val) => {
  nextTick(() => {
    totalHeight.value = `calc(80vh - 70px)`
  })
}, {
  deep: true,
  immediate: true
})
const auditDialogClose = () => {
  isShowAuditDialog.value = false
  getDataList()
}
onMounted(() => {
  getDataList()
})
//获取年初查询年初统计

//刷新
function resetTable(val) {
  listQuery.pageSize = 20
  listQuery.pageCurrent = 1
  // listQuery.orgid = orgids.value;
  // listQuery.ctype = ''
  deptid.value = ''
  listQuery.years = new Date().getFullYear().toString()
  getDataList();
}

//查询
function onSearch(obj) {
  listQuery.pageCurrent = 1
  // listQuery.ctype = obj.ctype;
  listQuery.years = obj.years;
  // listQuery.cwkm = obj.cwkm;
  getDataList();
  // getTotaldata()
}
/**获取剩余金额 */
function getSyMoney(row = {}) {
  // 剩余金额 = 年初批复 + 中期调整 - 使用金额
  return row.budgetmoney || 0
  // return new Big(row.firstApprovedBudget || 0).plus(row.tzzj || 0).minus(row.costFee || 0).round(4).toString()
}


function getDataList() {
  tableloading.value = true;
  const params = {
    ...listQuery,
    // deptid: props.row?.orgid,
  }
  getApi(params, "/mosty-jcgl/ys/getYsPage")
    .then((res) => {
      tableData.value = []
      if (res) {
        tableData.value = Array.isArray(res?.records) ? res?.records : [];
        tableData.value.forEach((/** @type {YsType} */ item) => {
          item.budget = item.budget ? item.budget : 0;
          item.firstApprovedBudget = item.firstApprovedBudget ? item.firstApprovedBudget : 0;
          item.budgetmoney = item.budgetmoney ? item.budgetmoney : 0;
          item.tzzj = item.tzzj ? item.tzzj : 0;
          item.gkshzj = item.gkshzj ? item.gkshzj : 0;
          item.pfjeall = numAdd("add", 4, item.budget, item.gkshzj, item.tzzj)
          // 剩余金额 = 年初批复 + 中期调整 - 使用金额
          item.symoney = getSyMoney(item)
          // item.symoney = numAdd("reduce", 4, item.pfjeall, item.costFee);
        })
        pageConfiger.total = res.total;
      }
    }).finally(() => {
      tableloading.value = false;
    })
}


//分页
const handleSizeChange = (currentSize) => {
  listQuery.pageSize = currentSize;
  pageConfiger.pageSize = currentSize;
  getDataList();
};
const handleCurrentChange = (currentPage) => {
  listQuery.pageCurrent = currentPage;
  pageConfiger.pageCurrent = currentPage;
  getDataList();
};



const seeDetail = (row, type) => {
  console.log('row: ', row);
  currRow.value = row
  isEditTc.value = type === 'edit'
  console.log(isEditTc.value, ' isEditTc.valueYSpage')
  isShowPageList.value = true
}
const pageListClose = () => {
  isShowPageList.value = false
  getDataList()
}

</script>

<style lang="scss" scoped>
::v-deep .bigBox {
  height: initial;
}

::v-deep .bigBox .zy-right {
  margin-left: 0;
}

.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>
