<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> -->
        <el-button v-if="props.isEdit" type="primary" @click="onAdd">
          <el-icon>
            <Plus />
          </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 #actions="{ row }">
                <span class="operesee" @click="seeDetail(row)"><el-icon>
                    <Compass />
                  </el-icon>查看明细</span>
                <span v-if="props.isEdit" class="operedit" @click="editRow(row)"><el-icon>
                    <EditPen />
                  </el-icon>编辑</span>
                <el-popconfirm v-if="props.isEdit" confirm-button-text="是" cancel-button-text="否" icon-color="red"
                  title="确定要删除?" @confirm="handleDel(row)">
                  <template #reference>
                    <span class="operdel" size="small">
                      <el-icon>
                        <Delete />
                      </el-icon>
                      删除</span>
                  </template>
                </el-popconfirm>
              </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>
      <addEdit :title="addEditTcTitle" v-if="isShowAddEditTC" :ysRow="props.row" :ysid="props.row.id"
        :rowid="currRow.id" :type="dialogType" @close="addEditClose" />
    </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 addEdit from './addEdit.vue';

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

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

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


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 tableloading = ref(false)
const USERID = getItem("USERID")
const ssdept = getItem("deptId")
// const title = ref('');//弹窗标题
const isShowDialog = ref(true);

const type = ref('01');//控制弹窗参数(01:年初预算调整审核新增)
const rowid = ref(null)
const listQuery = reactive({
  pageCurrent: 1,
  pageSize: 20,
  years: props.years,
  ysid: props.row?.id,
  // orgid: props.row.orgid,
});
const isOpen = ref(false);
const tableData = ref([])

const pageConfiger = reactive({
  pageSize: 20,
  pageCurrent: 1,
  total: 0
})
const tableColumns = reactive([
  {
    title: "标题",
    prop: "costDetailTitle",
    sortable: true
  },
  {
    title: "使用金额",
    prop: "costFee",
    sortable: true
  },
  {
    title: "时间",
    prop: "xtCjsj",
    sortable: true
  },
  {
    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(() => {
    totalHeight.value = `calc(80vh - 100px)`
  })
}, {
  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 getDataList() {
  tableloading.value = true;
  const params = {
    ...listQuery,
    // deptid: props.row?.orgid,
  }
  getApi(params, "/mosty-jcgl/ysCost/getPageList")
    .then((res) => {
      tableData.value = []
      if (res) {
        tableData.value = Array.isArray(res?.records) ? res?.records : [];
        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.cost_fee = item.cost_fee ? item.cost_fee : 0;
          item.syFee = Math.round((item.total - item.cost_fee) * 10000) / 10000;
        });
        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();
};


//导出Excel
function onloadExcel() {
  let title = {
    budgettitle: '预算项目',
    cwkm: '财务科目',
    ctype: '预算类别',
    orgname: '使用部门',
    costFee: '使用金额(万元)',
    symoney: '剩余金额(万元)',
    budgetmoney: '年初预算调整金额(万元)',
    budget: '年初批复',
    tzzj: '中期调整增减数',
    gkshzj: '中期归口审核增减数',
    state: '状态',
  }
  loadingShow.value = true
  const params = {
    pageCurrent: 1,
    pageSize: 9999999,
    deptid: props.row?.orgid,
    years: props.years,
  }
  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].budget + data[i].tzzj + data[i].gkshzj
          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(err => {
    loadingShow.value = false
  })
}
const seeDetail = (row) => {
  console.log('row: ', row);
  currRow.value = row
  addEditTcTitle.value = `${row.costDetailTitle}-查看详情`
  dialogType.value = 'detail'
  isShowAddEditTC.value = true
}
const editRow = (row) => {
  currRow.value = row
  addEditTcTitle.value = `${row.costDetailTitle}-编辑`
  dialogType.value = 'edit'
  isShowAddEditTC.value = true
}
const handleDel = (row) => {
  postApi({}, `/mosty-jcgl/ysCost/delCost/${row.id}`).then((res) => {
    ElMessage.success("删除成功");
    getDataList();
  })
}
const onAdd = () => {
  currRow.value = {}
  isShowAddEditTC.value = true
  addEditTcTitle.value = `新增`
  dialogType.value = 'add'
}
const addEditClose = () => {
  isShowAddEditTC.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>
