<template>
  <div>
    <div class="tag-container">
      <span style="display:inline-block; margin-left: 20px; color: #000;height: 32px;">统计方式：</span>
      <el-select style="width: 240px;margin-left: 20px;" v-model="showType" placeholder="请选择统计方式">
        <el-option v-for="item in seeOptions" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <span v-if="showType == 2" style="display:inline-block; margin-left: 40px; color: #000;height: 32px;">统计维度：</span>
      <el-select v-if="showType == 2" style="width: 240px;margin-left: 20px;" v-model="wdType" placeholder="请选择统计维度">
        <el-option v-for="item in wdOptions" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <el-date-picker style="margin-left: 5px;" v-model="listQuery.years" type="year" format="YYYY" value-format="YYYY"
        placeholder="请选择年份" @change="onSearch" />
    </div>
    <div v-if="showType == 1" class="aqfytj-chart-container">
      <section class="left" :style="{ width: lfBoxWid }">
        <div class="title">
          <div style="display: flex; align-items: center">
            <div style="padding-top: 5px; margin-right: 5px">
              <el-icon style="color: var(--el-color-primary) !important">
                <List />
              </el-icon>
            </div>
            <span class="zzjgxx" v-if="iconChange">组织机构信息</span>
          </div>
          <!-- <el-icon @click="handleCollapse" v-show="iconChange">
            <DArrowLeft />
          </el-icon>
          <el-icon @click="handleCollapse" v-show="!iconChange">
            <DArrowRight />
          </el-icon> -->
        </div>
        <div class="treeBox" :style="{ height: treeHeight }">
          <MOSTY.DepartmentTree width="100%" placeholder="管理部门ID" clearable filterable :searchType="'03'"
            @getdeptData="getdeptId" />
        </div>
      </section>
      <div :style="{ 'width': rgBoxWid }" class="bigBox right">
        <div class="flex cwkmlb_box">
          <div class="chartsBox ww86">
            <!-- 多柱状图 -->
            <!-- <manyBars ids="barsSafeFee" :keys="keyTwo" :barTitle="barsTitle" :barNum="barsNum"></manyBars> -->
            <multPie ref="multPieRef" :chartOptArr="chartOptArr" />
            <div class="tc f18 mt5" style="color: #5FAC67;margin-top: -26px;">预算使用率</div>
          </div>
          <div class="charts-box-liquid">
            <!-- 水球图 -->
            <div style="margin-top: 10px;text-align: center;">剩余待执行费用</div>
            <div ref="liquidRef" class="liquidfill"></div>
          </div>
        </div>
        <div class="safe-production">
          <!-- 多柱状图 -->
          <manyBars ids="safeProduction" :keys="keyThree" :barTitle="safeBarsTitle" :barNum="safeBarsNum"></manyBars>
          <div class="tc f18 mt5" style="color: #5FAC67;">安全生产费用类别</div>
        </div>
      </div>
    </div>
    <!-- 表格 -->
    <section v-if="showType == 2" class="eltab3">
      <!-- 财务科目 -->
      <cwkmTable ref="cwkmTableRef" v-if="wdType == 1" :listQuery="listQuery" />
      <!-- 预算类别 -->
      <yslbTable ref="yslbTableRef" v-if="wdType == 2" :listQuery="listQuery" />
    </section>
  </div>

</template>

<script setup>
// 引入
import { reactive, onMounted, ref, nextTick } from "vue";
import manyBars from "@/views/dutyBook/anQuantrNew/echarts/manyBars.vue";
import { getApi } from "@/api/tobAcco_api.js";
import * as echarts from 'echarts'
import 'echarts-liquidfill';
import * as MOSTY from "@/components/MyComponents/index";
import cwkmTable from "./cwkmTable.vue";
import yslbTable from "./yslbTable.vue";
import multPie from "./multPie.vue";
import Big from "@/utils/big.js"
// 数据
const keyTwo = ref(1);
const tableloading = ref(false);
const liquidRef = ref();
const treeHeight = ref("");
/**table组件 */
const tableRef = ref();
const lfBoxWid = ref("300px");
const rgBoxWid = ref("calc(100% - 300px)");
const iconChange = ref(true);
const orgCode = ref("")
const orglevel = ref('')
const listQuery = reactive({
  years: new Date().getFullYear().toString(),
  orgid: null
});

const cwkmTableRef = ref();
const yslbTableRef = ref();
const loadingshow = ref(false);
/** 展示类型 1图形 2表格  */
const showType = ref(1);
/** 多饼图 */
const multPieRef = ref()
const seeOptions = [
  { label: "统计图形", value: 1 },
  { label: "统计表格", value: 2 },
];
/**维度 */
const wdType = ref(1);
const wdOptions = [
  { label: "财务科目", value: 1 },
  { label: "预算类别", value: 2 },
];
// 柱状图数据
const barsTitle = ref([]);
const keyThree = ref(1);
const safeBarsTitle = ref([]);
const barsNum = reactive([
  {
    name: "预算（单位：万元）",
    data: [0, 0, 0],
    color: "#F2CA6B"
  },
  {
    name: "已执行（单位：万元）",
    data: [0, 0, 0],
    color: "#5FAC67"
  },
]);
const safeBarsNum = reactive([
  {
    name: "预算（单位：万元）",
    data: [0, 0, 0],
    color: "#F2CA6B"
  },
  {
    name: "已执行（单位：万元）",
    data: [0, 0, 0],
    color: "#5FAC67"
  },
]);

const chartOptArr = [
  { "label": "安全设施费用", "value": "1" },
  { "label": "应急救援费用", "value": "2" },
  { "label": "安全防护用品费用", "value": "3" },
  { "label": "安全信息化费用", "value": "4" },
  { "label": "安全宣传教育培训费", "value": "5" },
  { "label": "安全奖励费用", "value": "6" },
  { "label": "安全保险", "value": "7" },
  { "label": "安全咨询服务费", "value": "8" },
  { "label": "其他", "value": "9" }
]
const ctype = ref('')
const tableData = ref([
]);
const getdeptId = (val) => {
  listQuery.orgid = val.id;
  // aqtrBar()
  aqscBar()
  setWaveChartData()

}
//查询
function onSearch() {
  // aqtrBar()
  aqscBar()
  setWaveChartData()
  if (cwkmTableRef.value) cwkmTableRef.value.getTableData()
  if (yslbTableRef.value) yslbTableRef.value.getTableData()
}
const handleCollapse = () => {
  iconChange.value = !iconChange.value;
  if (iconChange.value) {
    lfBoxWid.value = "330px";
    rgBoxWid.value = "calc(100% - 330px)";
  } else {
    lfBoxWid.value = "40px";
    rgBoxWid.value = "calc(100% - 40px)";
  }
};
/**
 * 设置表格宽度
 * @param {Number} value 设置水位，值为0到1之间
 */
const setWaveChart = (value) => {
  if (!liquidRef.value || value == null) return
  const cssText = document.documentElement.style.cssText;
  let color = cssText.match(/--el-color-primary: (.*);/)[1] || '#007457';
  color = color.split(';')[0]
  const chart = echarts.init(liquidRef.value);
  const option = {
    series: [
      {
        type: 'liquidFill',
        // 水波图的配置
        data: [value], // 设置水位，值为0到1之间
        radius: '90%', // 设置图的大小
        color: [color],
        outline: {
          borderDistance: 0, // 外边框距离
          itemStyle: {
            borderWidth: 2, // 外边框宽度
            borderColor: color // 外边框颜色
          }
        },
        backgroundStyle: {
          color: '#fff' // 背景色
        },
        label: {
          show: true,
          fontSize: 16,
          fontWeight: 'bold',
          color: '#333',
          formatter: `${value * 100}%`,
        }
      },
    ],
  };
  chart.setOption(option);
}
const setWaveChartData = () => {
  getApi(listQuery, '/mosty-jcgl/ysTj/residue').then((res) => {
    if (res) {
      if (res >= 0 && res <= 100) setWaveChart(res / 100)
    }
  })
}

//安全投入统计柱状图
function aqtrBar() {
  // getApi(listQuery, '/mosty-jcgl/ysTj/cwkmStatistics').then((res) => {
  //   if (res) {


  //   }
  // })
}
//安全生产费用类别统计柱状图 和 安全生产费用类别统计饼图
function aqscBar() {
  getApi(listQuery, '/mosty-jcgl/ysTj/yslbStatistics').then((res) => {
    res = Array.isArray(res) ? res : []
    /**
       * @typedef {Object} ChartOpt
       * @property {string} ct 类型 ，如 安全设施费用、应急救援、安全防护用品
       * @property {number} cost_fee 已使用
       * @property {number} budget 预算
       * @property {string} no_use 未使用
       * @property {number} usePercent 使用率
       * @property {string} usePercentStr 使用率字符串
       * @property {string} label 标签
       */
    /** @type {Array<ChartOpt>} 表格数据 */
    const arr = Array.isArray(res) ? res : []
    const chartOptArr = arr.map(item => {

      item.cost_fee = isNaN(item.cost_fee) ? 0 : item.cost_fee
      item.budget = isNaN(item.budget) ? 0 : item.budget
      item.no_use = new Big(item.budget).minus(item.cost_fee).round(2).toNumber()
      if (item.budget == 0 || item.cost_fee == 0) {
        item.usePercent = 0
      } else {
        item.usePercent = new Big(item.cost_fee).div(item.budget).times(100).round(2).toNumber()
      }
      item.usePercentStr = item.usePercent.toString() + '%'
      item.label = item.ct
      return item
    })


    /** 设置【柱状图】数据 */
    const setBarData = (arr) => {
      safeBarsTitle.value = arr.map(item => item.label) // 标题
      safeBarsNum[1].data = arr.map(item => item.cost_fee)
      safeBarsNum[0].data = arr.map(item => item.budget)
      keyThree.value++
    }
    /** 设置【饼图】数据 */
    const setPieData = (arr) => {
      multPieRef.value && multPieRef.value.initChart(chartOptArr)
    }
    setBarData(chartOptArr)// 柱状图设置
    setPieData(arr)   // 饼图设置
  })
}
// 树高度计算
const treeHeightFn = () => {
  treeHeight.value = window.innerHeight - 287 + "px";
};
// 方法
onMounted(() => {
  treeHeightFn()
  loadingshow.value = true;
});
</script>

<style lang="scss" scoped>
.tag-container {
  padding-top: 5px;
  width: 100%;
  background-color: #fff;
}

.aqfytj-chart-container {
  margin-top: 5px;
  display: flex;
}

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

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

  .treeBox {
    overflow: auto;
  }
}

.bigBox {
  background-color: #fff;
  padding: 10px;
}

.right {
  padding-right: 10px;
  box-sizing: border-box;
  margin-left: 14px;
  background: #fff;
  width: 83%;
}

.chartsBox {
  margin-top: 10px;
  height: calc(50vh - 130px);
  justify-content: space-around;

  border: 1px solid #efefef;
  border-radius: 10px;
  padding: 10px 0 0px 0;
}

.titleBox {
  height: 50px;
}

.cwkmlb_box {
  // width: calc(100% - 40px);
  justify-content: space-between;
  color: #333;
}

.linkClick {
  color: var(--el-color-primary);
  cursor: pointer;
  text-decoration: underline;
}

.eltab3 {
  // height: calc(100vh - 236px);
}

.charts-box-liquid {
  // flex:1;
  height: calc(50vh - 130px);
  width: 12%;
  margin-top: 10px;
  border: 1px solid #efefef;
  border-radius: 10px;
}

.liquidfill {
  width: 100%;
  height: 100%;
}

.safe-production {
  // height: calc(100vh - 620px);
  height: calc(50vh - 130px);
  margin-top: 20px;
  padding: 10px 0 40px 0;
  border: 1px solid #efefef;
  border-radius: 10px;
}
</style>
