<template>
  <div class="fyys-container">
    <MOSTY.PageTree :searchType="'03'" :isShowLeftTree="false">
      <template #serach>
        <el-divider v-if="showtabs" />
        <MOSTY.Search v-if="showtabs" :searchArr="searchArr" @submit="onSearch" />
        <el-divider />
        <section class="button">
          <el-button type="primary" :loading="loadingshow" @click="onloadExcel">
            <el-icon>
              <Download />
            </el-icon>
            <span>导出</span>
          </el-button>
          <!-- <el-button type="primary" @click="onBlack" v-if="!showtabs">
            <el-icon>
              <ArrowLeft />
            </el-icon>
            <span>返回</span>
          </el-button> -->
        </section>
      </template>
      <template #table>
        <div v-if="showtabs">
          <section class="fyys-table-container">
            <MOSTY.Table :table-columns="tableColumn" :tableData="tableData" :tableloading="tableloading"
              :isSelect="false" :isSort="true" style="width: 100%;">
              <template #ctype="{ row }">
                <dict-tag v-if="row.ctype" :options="D_BZ_YSFYLB" :value="row.ctype" :tag="false" />
                <span v-else>无</span>
              </template>
              <template #cost_fee="{ row }">
                {{ row.cost_fee || 0 }}
              </template>
              <template #actions="{ row }">
                <span v-if="row.orgid.replace('XN', '') == ssdwid || row.orgid.replace('XN', '') == ssbmid"
                  class="operedit" @click="seeInfotable(row, 'edit')"><el-icon>
                    <Edit />
                  </el-icon>使用登记</span>

                <span class="operesee" @click="seeInfotable(row)"><el-icon>
                    <View />
                  </el-icon>查看明细</span>
              </template>
            </MOSTY.Table>
          </section>
          <!-- <div class="fenye">
            <MOSTY.Pages :pageConfiger="pageConfiger" @changeSize="handleSizeChange" @changeNo="handleCurrentChange">
            </MOSTY.Pages>
          </div> -->
        </div>
        <div v-else>
          <section class="fyys-table-container2">
            <MOSTY.Table :table-columns="tableColumn2" :tableData="tableDatasy" :tableloading="tableloading"
              :isSelect="false" :isSort="true" style="width: 100%;">
              <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 #cost_fee="{ row }">
                {{ row.cost_fee || 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 class="operedit" @click="seeDetail(row, 'edit')"><el-icon>
                    <EditPen />
                  </el-icon>使用登记
                </span>
                <!-- <span v-if="row.state == '6'" class="operedit" @click="seeDetail(row, 'edit')"><el-icon>
                    <EditPen />
                  </el-icon>使用登记
                </span> -->
              </template>
            </MOSTY.Table>
          </section>
          <!-- <div class="fenye">
            <MOSTY.Pages :pageConfiger="pageConfiger2" @changeSize="handleSizeChanges" @changeNo="handleCurrentChanges">
            </MOSTY.Pages>
          </div> -->
          <div class="fenye" :style="{ top: totalHeight + 'px' }">
            <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
              :current-page="pageConfiger.pageCurrent" :page-sizes="[2, 5, 10, 20]" :page-size="pageConfiger.pageSize"
              layout="total, prev, pager, next, sizes, jumper" :total="pageConfiger.total"></el-pagination>
          </div>
        </div>
      </template>
    </MOSTY.PageTree>

    <!-- 市公式弹框 -->
    <sgsTC v-if="isShowSgs" :row="currRow" :isEdit="isEditTc" :years="listQuery.years" :title="`${currRow.orgname}-详情`"
      @close="sgTcClose" />
    <xgsTC v-if="isShowXgs" :row="currRow" :isEdit="isEditTc" :years="listQuery.years" :title="`${currRow.orgname}-详情`"
      @close="xgsTcClose" />
    <YsPage v-if="isShowYsPage" :row="currRow" :isEdit="isEditTc" :years="listQuery.years"
      :title="`${currRow.orgname}-详情`" @close="ysPageClose" />
    <!-- 预算项目下级 -->
    <pageList v-if="isShowPageList" :isEdit="isEditTc" :title="`${currRow.budgettitle || ''}-详情`"
      :years="listQuery.years" :row="currRow" @close="pageListClose" />
  </div>
</template>

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

const { proxy } = getCurrentInstance();
const { D_BZ_YSFYLB, D_TB_YSCWKU } = proxy.$dict("D_BZ_YSFYLB", "D_TB_YSCWKU");
/**单位id */
const ssdwid = getItem("deptId").ssdwid;
/** 部门id */
const ssbmid = getItem("deptId").ssbmid;
const addplanShow = ref(false);
const showadds = ref(false);
const loadingshow = ref(false);
const isShowSgs = ref(false);
/** 是否是编辑模式 */
const isEditTc = ref(false)

/** 展示县公司下的所有 */
const isShowXgs = ref(false);
const isShowYsPage = ref(false);
const isShowPageList = ref(false);
/** 是否展示到部门级别 */
/** 是否是县公司 */
const isxgs = ref(filterqx('isxgs') == '1')
/**市公司 */
const isgs = ref(filterqx('isgs') == '1')
/**省公司 */
const isSgs = ref(filterqx('isSgs') == '1')
const currRow = ref({});
/** 是否是安全部 */
const isAqbm = filterqx('isaqbm') == '1'
/** 是否是领导 */
const isldbz = filterqx('isldbz') == '1'
/** 是否展示部门table (领导或者安全部门展示) */
const showtabs = ref(isAqbm || isldbz);
const tableloading = ref(false);
const title = ref(""); //弹窗标题
const rowid = ref(null);
const listQuery = reactive({
  pageCurrent: 1,
  pageSize: 20,
  years: new Date().getFullYear().toString(),
  orgid: null,
  ctype: null
});

const searchArr = reactive([
  {
    showType: "select",
    prop: "year",
    defaultVal: new Date().getFullYear(),
    width: '250px',
    options: filterYear(5),
  },

]);
const tableData = ref([]);
const tableDatasy = ref([]);
// 树的展开与折叠
/* const tableColumn = ref([
  {
    title: "部门",
    prop: "orgname",
    width: '200',
    sortable: true
  },
  {
    title: "年初预算调整金额(万元)",
    prop: "budgetmoney",
    width: '200',
  },
  {
    title: "年初批复",
    prop: "budget",
    width: '200',
  },
  {
    title: "中期调整增减数",
    prop: "tzzj",
    width: '200',
  },
  {
    title: "中期归口审核增减数",
    prop: "gkshzj",
    width: '200',
  },
  {
    title: "总金额",
    prop: "total",
    width: '200',
  },
  {
    title: "已使用金额",
    prop: "cost_fee",
  },
  {
    title: "剩余金额",
    prop: "syFee",
  },
  {
    title: "操作",
    prop: "actions",
    fixed: 'right',
    slot: true
  }
]) */
const tableColumn = ref([

  {
    title: "部门",
    prop: "orgname",
    // width: '180',
  },
  {
    title: "年初批复预算",
    prop: "first_approved_budget", //  budgetmoney
    // width: '120',
  },
  {
    title: "中期调整增减数",
    prop: "tzzj",
    // width: '120',
  },
  {
    title: "预算金额",
    prop: "budget",
    width: '120',
  },
  {
    title: "使用金额(万元)",
    prop: "cost_fee",
    // slot: true
  },
  {
    title: "剩余金额(万元)",
    prop: "budgetmoney",
  },


  // {
  //   title: "中期归口审核增减数",
  //   prop: "gkshzj",
  // },

  {
    title: "操作",
    prop: "actions",
    fixed: 'right',
    slot: true
  }
])
const pageConfiger = reactive({
  pageSize: 20,
  pageCurrent: 1,
  total: 0
})
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 tableColumn2 = ref([
  {
    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: "first_approved_budget", //  budgetmoney
    width: '120',
  },
  {
    title: "中期调整增减数",
    prop: "tzzj",
    width: '120',
  },
  {
    title: "预算金额",
    prop: "budget",
    width: '120',
  },
  {
    title: "使用金额(万元)",
    prop: "cost_fee",
    width: '120',
    slot: true
  },
  {
    title: "剩余金额(万元)",
    prop: "budgetmoney", //  symoney
    width: '120',
  },

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

  // {
  //   title: "年初批复",
  //   prop: "budget",
  //   width: '120',
  // },

  // {
  //   title: "中期归口审核增减数",
  //   prop: "gkshzj",
  // },

  // {
  //   title: "状态",
  //   prop: "state",
  //   slot: true
  // },

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

onMounted(() => {
  getDataList();
});

const seeDetail = (row, type) => {
  currRow.value = row
  isEditTc.value = type === 'edit'
  console.log(isEditTc.value, ' isEditTc.valueYindex')
  isShowPageList.value = true
}
//分页
const handleSizeChange = (currentSize) => {
  listQuery.pageSize = currentSize;
  pageConfiger.pageSize = currentSize;
  getDataList();
};
const handleCurrentChange = (currentPage) => {
  listQuery.pageCurrent = currentPage;
  pageConfiger.pageCurrent = currentPage;
  getDataList();
};
const sgTcClose = () => {
  isShowSgs.value = false
  getDataList()
}
const xgsTcClose = () => {
  isShowXgs.value = false
  getDataList()
}
const ysPageClose = () => {
  isShowYsPage.value = false
  getDataList()
}
const pageListClose = () => {
  isShowPageList.value = false
  getDataList()
}

//查询
function onSearch(obj) {
  listQuery.pageCurrent = 1;
  listQuery.years = obj.year;
  getDataList();
}
function getTableData1() {
  tableloading.value = true;
  const params = {
    years: listQuery.years,
  }
  // tableData.value = [];
  getApi(params, "/mosty-jcgl/ysCost/getList")
    .then((res) => {
      if (res) {
        tableData.value = res;
        tableData.value.forEach(async (item) => {
          item.budgetmoney = item.budgetmoney ? item.budgetmoney : 0;
          item.budget = item.budget ? item.budget : 0;
          item.tzzj = item.tzzj ? item.tzzj : 0;
          item.gkshzj = item.gkshzj ? item.gkshzj : 0;
          item.total = item.budget + item.tzzj + item.gkshzj;
          item.total = Math.round(item.total * 10000) / 10000;
          item.syFee = Math.round((item.total - item.cost_fee) * 10000) / 10000;
        });
        pageConfiger.total = res.total;
      }
    }).finally(() => {
      tableloading.value = false;
    })
}
function getTableData2() {
  tableloading.value = true;
  const params = {
    pageCurrent: pageConfiger.pageCurrent,
    pageSize: pageConfiger.pageSize,
    years: listQuery.years,
    deptId: ssbmid,
  }
  getApi(params, "/mosty-jcgl/ys/getYsPage")
    .then((res) => {
      tableDatasy.value = []
      if (res) {
        tableDatasy.value = Array.isArray(res?.records) ? res?.records : [];
        tableDatasy.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;
      }
    }).finally(() => {
      tableloading.value = false;
    })
}
function getDataList() {
  if (showtabs.value) {
    getTableData1();
  } else getTableData2();
}

//新增安全预算使用
function onAddys() {
  title.value = "添加使用";
  rowid.value = null;
  addplanShow.value = true;
}
//修改使用金额
function xgsyje(val) {
  title.value = "修改预算";
  rowid.value = val.id;
  addplanShow.value = true;
}
//查看预算
function cksyye(val) {
  title.value = "查看预算";
  rowid.value = val.id;
  addplanShow.value = true;
}
//查看
function seeInfotable(val, type) {
  currRow.value = val;
  const { orglevel, orgid } = val;

  isEditTc.value = type === 'edit';
  console.log(isEditTc.value, ' isEditTc.valueYindex')
  if (!val) return
  // 本级
  if (orgid.indexOf('XN') > -1) {
    isShowXgs.value = true;
  } else {
    // 省公司 点击进入-》 下级 【某市公司】所有内容
    if (isSgs.value) {
      isShowSgs.value = true;
      // 市公司 点击进入-》 下级 【某县公司】
    } else if (isgs.value) {
      isShowXgs.value = true;
      // 县公司 点击进入-》 下级 【某部门】 的所有内容
    } else if (isxgs.value) {
      isShowYsPage.value = true;
    }
  }
}
function delRow(val) {
  // postApi({}, `/mosty-jcgl/budgets/del/${val.id}`).then((res) => {
  //   ElMessage.success("删除成功");
  //   getDataList();
  // });
}
// //使用情况
// function seefyInfo(val) {
//   budgetid.value = val.id;
//   showadds.value = true;
//   showtabs.value = false;
//   param.budgetid = val.id;
//   // getsyqklist();
// }
// //使用情况列表
// function getsyqklist() {
//   getApi(param, "	/mosty-jcgl/ysCost/getPageList")
//     .then((res) => {
//
//       if (res.records) {
//         tableloading.value = false;
//         tableDatasy.value = res.records;
//         pageConfiger.total = res.total || 0;
//       }
//     })
// }

// //返回
// function onBlack() {
//   showtabs.value = true;
//   resetTable();
// }


function onloadExcel() {
  if (showtabs.value) {
    onloadExcel1()
  } else {
    onloadExcel2()
  }
}
//导出Excel
function onloadExcel1() {
  loadingshow.value = true
  let title = {
    orgname: "部门",
    budgetmoney: "年初预算调整金额(万元)",
    budget: "年初批复",
    tzzj: "中期调整增减数",
    // gkshzj: "中期归口审核增减数",
    total: "总金额",
    cost_fee: "已使用金额",
    syFee: "剩余金额"
  };
  let obj = {
    years: listQuery.years
  }
  getApi(obj, "/mosty-jcgl/ysCost/getList").then(async (res) => {
    if (res) {
      let data = res;
      if (data) {
        for (let i = 0; i < data.length; i++) {
          data[i].budgetmoney = data[i].budgetmoney ? data[i].budgetmoney : 0;
          data[i].budget = data[i].budget ? data[i].budget : 0;
          data[i].tzzj = data[i].tzzj ? data[i].tzzj : 0;
          data[i].gkshzj = data[i].gkshzj ? data[i].gkshzj : 0;
          data[i].total = data[i].budget + data[i].tzzj + data[i].gkshzj;
          data[i].total = Math.round(data[i].total * 10000) / 10000;
          data[i].syFee = Math.round((data[i].total - data[i].cost_fee) * 10000) / 10000;
        }
        let tablename = "安全费用使用列表.xlsx";
        exportXlsx(title, data, '安全费用使用列表', tablename);
      }
    }
  }).finally(() => {
    loadingshow.value = false
  });
}
//导出Excel
function onloadExcel2() {
  let title = {
    budgettitle: '预算项目',
    // cwkm: '财务科目',
    ctype: '预算类别',
    deptname: '使用部门',
    costFee: '使用金额',
    symoney: '剩余金额',
    budgetmoney: '年初预算调整金额',
    budget: '年初批复',
    tzzj: '中期调整增减数',
    // gkshzj: '中期归口审核增减数',
    state: '状态',
    // yeartzzj: '年度调整增减数',
    // yeargkshzj: '年度归口审核增减数',
  }
  let obj = { ...listQuery };
  obj.pageSize = 10000
  loadingshow.value = true
  getApi(obj, '/mosty-jcgl/ys/exportYsList').then(async (res) => {
    if (res) {
      let data = res
      if (data) {
        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)
          data[i].symoney = numAdd("reduce", 4, data[i].pfjeall, data[i].costFee);
        }
        let tablename = "预算填报列表.xlsx"
        exportXlsx(title, data, '预算填报列表', tablename);
      }
    }

  }).finally(() => {
    loadingshow.value = false
  });
}
</script>

<style lang="scss" scoped>
.fyys-container {
  padding-right: 10px;

  .bigBox .zy-right {
    border: 1px solid red;
    margin-left: none;
  }
}

.fyys-table-container {
  height: calc(100vh - 350px);
}

.fyys-table-container2 {
  height: calc(100vh - 300px);
}

.bigBox {
  display: flex;

  .title {
    height: 39px;
    line-height: 39px;
    font-size: 18px;
    color: #0f3916;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .el-icon {
      cursor: pointer;
    }
  }

  .left {
    width: 300px;
    background: #ffffff;
    box-shadow: 0px 2px 10px 0px rgba(107, 107, 107, 0.1);
    border-radius: 0px 0px 0px 0px;
    opacity: 1;

    .treeBox {
      overflow: auto;
    }
  }

  .right {
    padding: 0 10px;
    margin-left: 14px;
    background: #fff;

  }
}


.button {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 12px;
}

.sectabs3 {
  height: calc(100vh - 369px);
}
</style>
