<template>
  <div>
    <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>
    <div class="bigBox" :style="{ height: bigHeight }">
      <!-- <MOSTY.FromPage :title="props.title" @closeDialog="CloseEvent">
        <template #content> -->
          <section :style="{height: `calc(84vh - 108px - ${type=='see'?0: 45}px)`}">
            <MOSTY.Table :table-columns="tableColumns" :tableData="tableData" :tableloading="tableloading"
              :isSelect="false" :isSort="false" :tableHeight="'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 #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="seeInfo(row)">
                  <el-icon>
                    <View />
                  </el-icon>查看</span>
                <span v-if="((isxgs &&row.state=='1')||(isgs &&row.state=='3')||(isSgs &&row.state=='5')) && type !== 'see'" class="operedit" @click="goAudit(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 v-if="type!='see'" style="display: flex;justify-content: center;">
          <el-button v-if="(isgs&&props.row.state==1 ) || (isSgs && props.row.state==3)" type="primary" @click="comfirm">
            <el-icon>
              <Check />
            </el-icon>
            <span>通过</span>
          </el-button>
          <el-button v-if="(isgs&&props.row.state>3) || (isSgs && props.row.state>5)" type="primary" @click="reject">
            <el-icon>
              <Close />
            </el-icon>
            <span>驳回</span>
          </el-button>
          <el-button type="primary" @click="CloseEvent">
            <el-icon>
              <DocumentDelete />
            </el-icon>
            <span>关闭</span>
          </el-button>
         </div>
        <!-- </template> -->
      <!-- </MOSTY.FromPage> -->
    </div>
    <!-- <div v-if="isShowAuditTcDialog" class="dialog-box"> -->
      <!-- <el-dialog :title="dialogTitle" v-model="isShowAuditTcDialog" width="90vw"> -->
        <AuditTC v-if="isShowAuditTcDialog" :years="props.years" :dialogType="dialogType" :row="currRow" :title="dialogTitle"
          @close="isShowAuditTcDialog = false" @resttab="resttab" />
      <!-- </el-dialog> -->
    <!-- </div> -->
  </div>
</template>

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

const { proxy } = getCurrentInstance();
const { D_BZ_YSFYLB, D_TB_YSCWKU } = proxy.$dict("D_BZ_YSFYLB", "D_TB_YSCWKU");
const emits = defineEmits(["close", 'resttab']);
const rowid = ref(null)
const addplanShow = ref(false)
const zzlx = ref('')
const showJkssbm = ref(false)
const useFatherDeptid = ref()
const currRow = ref({})
const dialogTitle = ref('')
const dialogType = ref('')
const loadingShow = ref(false);
/** 是否是县公司 */
const isxgs = ref(filterqx('isxgs') == '1')
/**市公司 */
const isgs = ref(filterqx('isgs') == '1')
/**省公司 */
const isSgs = ref(filterqx('isSgs') == '1')
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
const isShowAuditTcDialog = ref(false)
//表单数据
const ruleForm = ref({
  orgcode: getItem("deptId").ssdwid,
  orgname: getItem("deptId").ssdwmc,
})
//
const props = defineProps({
  // 判断展示字段
  years: {
    default: '',
    type: String
  },
  title: {
    default: '',
    type: String
  },
  /** 组件类型 see 查看明细 audit 审核 */
  type: {
    default: 'see',
    type: String
  },
  row: {
    type: Object,
    default: () => ({})
  },
  /** 是否是驳回 */
  isReject: {
    type: Boolean,
    default: false
  }
});
const pageConfiger = reactive({
  pageSize: 20,
  pageCurrent: 1,
  total: 0
})
const tableColumns = reactive([
  {
    title: "预算项目",
    prop: "budgettitle",
    fixed: 'left',
    width: '180',
  },
  {
    title: "财务科目",
    prop: "cwkm",
    width: '160',
    slot: true,
  },
  {
    title: "预算类别",
    prop: "ctype",
    width: '160',
    slot: true
  },
  {
    title: "使用部门",
    prop: "deptname",
    width: '160',
  },
  {
    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",
    // width: '120',
  },
  // {
  //   title: "年度调整增减数",
  //   prop: "yeartzzj",
  //   width: '200',
  // },
  // {
  //   title: "年度归口审核增减数",
  //   prop: "yeargkshzj",
  //   width: '200',
  // },
  {
    title: "状态",
    prop: "state",
    fixed: 'right',
    width: '180',
    slot: true
  },
  {
    title: "操作",
    prop: "actions",
    fixed: 'right',
    slot: true
  }
])
// 数据
// const activeNames = ref(["1"]);
const ssdept = getItem("deptId").ssbmid
// const ShowfileList = ref(true); //是否展示文件列表
const ruleFormRef = ref();
const orgcode = ref(props.orgcode);
const isdisabled = ref(false)
const showshbtn = ref(false)
const disabled2 = ref(false)
const bigHeight = ref('calc(85vh - 60px)'); //整个高度
const delrow = ref({}); //删除文件列表
const tableloading = ref(false);
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 20
});
const tableData = ref([]);
const FromData = ref({
  years: new Date().getFullYear().toString(),
  verifyorgname: '',
  verifyorgid: '',
  verifyusername: '',
  verifyuserid: '',
  files: ''
})


const getTableData = () => {
  const params = {
    pageCurrent: listQuery.value.pageCurrent,
    pageSize: listQuery.value.pageSize,
    deptid: props.row?.orgid,
    years: props.years,
  }
  getApi(params, '/mosty-jcgl/ys/getDeptItem').then(res => {
    let arr = Array.isArray(res?.records) ? res?.records : [];
    tableData.value = arr.map(item => {
      // item.state = item.state || '0'
      item.costFee = item.costFee || 0 //使用金额
      // item.symoney = numAdd(item.symoney, 0)
      item.budgetmoney = item.budgetmoney || 0 //年初预算调整金额
      item.budget = item.budget || 0 //年初批复
      item.tzzj = item.tzzj || 0 //中期调整增减数

      item.gkshzj = item.gkshzj || 0 // 年度归口审核增减数
      let total = item.budget + item.tzzj + item.gkshzj
      item.symoney = total - item.costFee

      item.symoney = Math.round(item.symoney * 10000) / 10000
      return item
    })
    pageConfiger.total = res?.total || 0;
  })
}
//导出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)
          // data[i].symoney = numAdd("reduce", 4, data[i].pfjeall, data[i].costFee);
          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);
        loadingShow.value = false
      }
    }

  }).catch(err => {
    loadingShow.value = false
  })
}
const resttab = () => {
  getTableData();
  emits('resttab')
}



//记录详情
const seeInfo = (row) => {


  currRow.value = row;
  dialogType.value = 'see'
  dialogTitle.value = row.budgettitle + '-详情'
  isShowAuditTcDialog.value = true
}
const goAudit = (row) => {

  currRow.value = row;
  dialogType.value = 'audit'
  dialogTitle.value = row.budgettitle + '-审核'
  isShowAuditTcDialog.value = true
}
// 方法
const bigHeightFn = () => {
  bigHeight.value = window.innerHeight - 147 + "px";
};
const comfirm = () => {
  proxy.$modal.confirm('确定通过审核？', '提示')
    .then(() => {
      const params = {
        years: props.years,
        orgid: props.row.orgid,
        // desc: '',
        type: '01',
        id: props.row.id,
      }
      postApi(params, `/mosty-jcgl/ys/hzAudit`).then((res) => {
        ElMessage.success("通过审核成功");
        // resetTable();
        emits("close");
        emits("resttab")
      })
    })
    .catch(() => {
      // catch error
    })

}
const reject = () => {
  ElMessageBox.prompt('请输入驳回原因', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /\S/,
    inputErrorMessage: '请输入驳回原因',
  }).then(({ value }) => {
    const params = {
      years: props.years,
      orgid: props.row.orgid,
      desc: value,
      type: '02',
      id: props.row.id,
    }
    postApi(params, `/mosty-jcgl/ys/hzAudit`).then((res) => {
      ElMessage.success("驳回成功");
      // resetTable();
      emits("close");
      emits("resttab")
    })
  })
}
//关闭综合配置表
const CloseEvent = () => {
  emits("close");
  emits("resttab")

};
//保存
const addHander = async (formEl) => {

}





//分页
const handleSizeChange = (currentSize) => {
  listQuery.value.pageSize = currentSize;
  pageConfiger.pageSize = currentSize;
  getTableData();
};
const handleCurrentChange = (currentPage) => {
  listQuery.value.pageCurrent = currentPage;
  pageConfiger.pageCurrent = currentPage;
  getTableData();
};
// 初始化
onMounted(() => {
  getTableData();
});

</script>

<style lang="scss" scoped>
.bigBox {
  display: block;

  ::v-deep .content {
    height: calc(84vh - 100px);
  }
}


::v-deep .el-collapse {
  padding: 20px !important;
}

.el-form {
  margin: 0 auto;
}

.from_box {
  width: 100%;
  margin: 0 auto;
  color: #000;
}

.demo-ruleForm {
  display: block;
}

.txbj {
  display: flex;
  font-size: #000;
}
</style>
