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

        <!-- <div class="btnBox">

          <el-button v-if="isShowAuditBtn" type="primary" @click="AuditClick">
            <el-icon>
              <CirclePlus />
            </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 #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="row.state != 0" class="operedit" @click="auditTimeLine(row)"><el-icon>
                  <Edit />
                </el-icon>审核进度</span>

              <span v-if="row.state == 5" class="operedown" @click="toAudit(row)"><el-icon>
                  <EditPen />
                </el-icon>点击审核
              </span> -->
            </template>
          </MOSTY.Table>
        </section>
        <div class="fenye">
          <MOSTY.Pages :pageConfiger="pageConfiger" @changeNo="handleCurrentChange" @changeSize="handleSizeChange" />
        </div>
      </template>
      <!-- <template #footer> -->
      <!-- <div slot="footer">
        <el-button type="primary">返回</el-button>
      </div> -->
      <!-- </template> -->
    </MOSTY.PageTree>
    <!-- <div class="dialog-box" v-if="isShowAuditDialog"> -->
    <el-dialog :title="dialogTitle" v-model="isShowAuditDialog" width="90vw">
      <Audit :years="listQuery.years" :type="dialogType" :row="currRow" :title="dialogTitle"
        @close="auditDialogClose" />
    </el-dialog>
    <!-- </div> -->
    <AuditTimeLine v-if="isShowTimeLine" :years="listQuery.years" :row="currRow" @close="isShowTimeLine = false" />
  </div>
</template>

<script setup>
// 引入
import { reactive, onMounted, ref, getCurrentInstance, nextTick, watch, computed, defineProps } 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 Audit from '../AuditTable.vue';
import AuditTimeLine from '../AuditTimeLine.vue';
// import SubmitAllAudit from './SubmitAllAudit.vue';
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 props = defineProps(['years', 'row'])



const sybmlist = ref([])
const addplanShow = ref(false);
const addysShow = ref(false);
/** 当前层级 1省 2市 3县 */
const currLev = ref(3) // 1 省 2 市 3 县
/** 是否显示 审核弹框 */
const isShowAuditDialog = ref(false)
const isShowTimeLine = ref(false)
const isShowSubmitAllAudit = ref(false)
/** 当前时间是否是上半年 */
const isHalfYear = ref(new Date().getMonth() < 6);
/** 是否是县公司 */
const isxgs = ref(filterqx('isxgs') == '1')
/**市公司 */
const isgs = ref(filterqx('isgs') == '1')
/**省公司 */
const isSgs = ref(filterqx('isSgs') == '1')
/** 当前查看或审核行 */
const currRow = ref({})
const dialogType = ref('see') // see 查看  edit 编辑
const dialogTitle = ref('')
const searchArr = reactive([
  {
    showType: "year",
    prop: "years",
    width: '250px',
    defaultVal: new Date().getFullYear().toString(),

  },
  // {
  //   showType: "select",
  //   prop: "state",
  //   width: '250px',
  //   options: [
  //     { label: '年度预算', value: '0' },
  //     { label: '中期审核预算', value: '1' },

  //   ],
  //   placeholder: '请选择状态'
  // },
  // {
  //   showType: "select",
  //   prop: "state",
  //   width: '250px',
  //   //审批状态（0-未上报 1-县公司安全部门负责人 2-市州公司安全部门负责人审批 3-省局公司安全部门负责人审批 4-审批通过 5-被驳回
  //   options: [
  //     { label: '未上报', value: '0' },
  //     { label: '县公司安全部门负责人', value: '1' },
  //     { label: '市州公司安全部门负责人审批', value: '2' },
  //     { label: '省局公司安全部门负责人审批', value: '3' },
  //     { label: '审批通过', value: '4' },
  //     { label: '被驳回', value: '5' },
  //   ],
  //   placeholder: '请选择审核状态'
  // },

]);
const isShowAuditBtn = computed(() => {
  let arr = tableData.value
  if (!arr.length) return false
  let auth = arr.every((item) => {
    const state = item.state
    return state === '0' || (isxgs.value && state === '1') || (isgs.value && state === '2') //都是已上报
  })
  return auth
});

const listQueryObj = ref({
  lev1Data: {},
  lev2Data: {},
  lev3Data: {},
})
const tableColumnsFilter = computed(() => {
  let arr = []
  if (listQuery.cwkm) {
    arr = tableColumns.filter((item) => {
      return item.prop !== 'cwkm'
    })
  } else {
    arr = tableColumns.filter((item) => {
      return item.prop !== 'ctype'
    })
  }
  return arr
})
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' },
];
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: 'orgname',
    width: '200',
    fixed: 'left',
  },
  {
    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: "costFee",
    width: '120',
    slot: true
  },
  {
    title: "剩余金额(万元)",
    prop: "symoney",
    width: '120',
  },
  {
    title: "年初预算调整金额(万元)",
    prop: "budgetmoney",
    width: '120',
  },

  {
    title: "年初批复",
    prop: "budget",
    width: '120',
  },
  {
    title: "中期调整增减数",
    prop: "tzzj",
    width: '120',
  },
  {
    title: "中期归口审核增减数",
    prop: "gkshzj",
  },
  // {
  //   title: "年度调整增减数",
  //   prop: "yeartzzj",
  //   width: '200',
  // },
  // {
  //   title: "年度归口审核增减数",
  //   prop: "yeargkshzj",
  //   width: '200',
  // },
  {
    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('calc(80vh - 100px)')
const getHeight = ref(null)

const auditDialogClose = () => {
  isShowAuditDialog.value = false
  getDataList()
}
onMounted(() => {
  nextTick(() => {
    // totalHeight.value = `calc(100vh - ${379 + getHeight.value.offsetHeight}px)`
  })
  // if (isSgs.value) currLev.value = 1;
  // if (isgs.value) currLev.value = 2;
  // if (isxgs.value) currLev.value = 3;
  getDataList()
  // setAuditBtn()
  // 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()
  // setAuditBtn()
}

//查询
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
  // /ys/getDeptItem
  const deptid = props.row?.orgid
  const params = {
    pageCurrent: listQuery.pageCurrent,
    pageSize: listQuery.pageSize,
    deptid: deptid,
    years: props.years,
  }
  getApi(params, '/mosty-jcgl/ys/getDeptItem').then((res) => {
    if (res) {
      tableloading.value = false;
      tableData.value = Array.isArray(res?.records) ? 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)
        let total =  item.budgetmoney +  item.budget +  item.tzzj
        item.symoney = total - item.costFee
        item.symoney = Math.round(item.symoney * 10000) / 10000
      })
      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/ys/del/${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();
};
function AuditClick() {
  proxy.$modal.confirm('确定汇总提交审核？', '提示')
    .then(() => {
      postApi({}, `/mosty-jcgl/ys/hzSubmit?years=${listQuery.years}`).then((res) => {
        ElMessage.success("汇总提交审核成功");
        // resetTable();
        getDataList();
      })
    })
    .catch(() => {
      // catch error
    })
}
function submitAudit() {
  const url = isxgs ? '/ys/hzSubmit' : '/ys/hzAudit'
  postApi({}, url).then((res) => {
    ElMessage.success("提交审核成功");
    getDataList()
  });
}
//导出Excel
function onloadExcel() {
  let title = {
    orgname: '部门',
    budgettitle: '预算项目',
    cwkm: '财务科目',
    ctype: '预算类别',
    deptname: '使用部门',
    costFee: '使用金额(万元)',
    symoney: '剩余金额(万元)',
    budgetmoney: '年初预算调整金额(万元)',
    budget: '年初批复',
    tzzj: '中期调整增减数',
    gkshzj: '中期归口审核增减数',
    state: '状态',
  }
  const params = {
    pageCurrent: 1,
    pageSize:9999999,
    deptid: props.row?.orgid,
    years: props.years,
  }
  loadingShow.value = true
  getApi(params, '/mosty-jcgl/ys/getDeptItem').then(async (res) => {
    if (res) {
      let data = Array.isArray(res?.records)? res?.records : [];
      if (data.length) {
        for (let i = 0; i < data.length; i++) {
          data[i].deptname = data[i].deptname || ''
          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].state = stateOpt.find(item => item.value == data[i].state)?.label || ''
          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)
          let total =  data[i].budgetmoney +  data[i].budget +  data[i].tzzj
          data[i].symoney = total - data[i].costFee
          data[i].symoney = Math.round(data[i].symoney * 10000) / 10000
        }
        let tablename = `${props.row.orgname}-详情.xlsx`
        exportXlsx(title, data, `${props.row.orgname}-详情`, tablename);
      } else {
        ElMessage.warning("暂无数据");
      }
    }

  }).finally(() => {
    loadingShow.value = false
  })
}
const seeDetail = (row) => {
  currRow.value = row
  dialogType.value = 'see'
  isShowAuditDialog.value = true
  dialogTitle.value = `${row.orgname}-查看详情`
}
const auditTimeLine = (row) => {
  currRow.value = row
  isShowTimeLine.value = true
}
const toAudit = (row) => {
  currRow.value = row
  dialogType.value = 'audit'
  isShowAuditDialog.value = true
  dialogTitle.value = `${row.orgname}-审核`
}

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