<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      class="demo-ruleForm"
      ref="queryForm"
      size="small"
      :inline="true"
    >
      <el-form-item label="单位">
        <el-select
          v-model="queryParams.orgName"
          placeholder="请选择..."
          @clear="delValue"
          clearable
          ref="select"
          style="width: 300px"
        >
          <el-option hidden key="id" :value="queryParams.orgName" :label="queryParams.selectName"></el-option>
          <el-tree
            :data="options"
            :props="defaultProps"
            @node-click="handleNodeClick"
            :expand-on-click-node="false"
            :check-on-click-node="true"
            ref="tree"
            node-key="id"
            :default-expand-all="true"
            :filter-node-method="filterNode"
          >
            <span slot-scope="{ data }">
            <span>{{ data.deptName }}</span>
          <el-tag
            size="mini"
            style="margin: 0 10px"
            v-show="filterorgType(data.tag)"
          >{{ filterorgType(data.tag) }}</el-tag
          >
        </span>
          </el-tree>
        </el-select>
      </el-form-item>
      <el-form-item label="查询期间">
        <el-date-picker v-model="queryParams.year" type="year" value-format="yyyy" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handSech">查询</el-button>
      </el-form-item>
    </el-form>

    <div class="table" >
      <el-table
        v-loading="loading"
        :data="taxCategoryList"
      >
        <el-table-column type="index" label="序号" align="center"></el-table-column>
        <el-table-column min-width="200px" label="税目" align="center" prop="itemName"></el-table-column>
        <el-table-column min-width="200px" label="1季度" align="center">
          <el-table-column prop="tax1Fee" label="计税金额" align="center"></el-table-column>
          <el-table-column prop="tax1" label="应纳税额" align="center"></el-table-column>
        </el-table-column>
        <el-table-column min-width="200px" label="2季度" align="center">
          <el-table-column prop="tax2Fee" label="计税金额" align="center"></el-table-column>
          <el-table-column prop="tax2" label="应纳税额" align="center"></el-table-column>
        </el-table-column>
        <el-table-column min-width="200px" label="3季度" align="center">
          <el-table-column prop="tax3Fee" label="计税金额" align="center"></el-table-column>
          <el-table-column prop="tax3" label="应纳税额" align="center"></el-table-column>
        </el-table-column>
        <el-table-column min-width="200px" label="4季度" align="center">
          <el-table-column prop="tax4Fee" label="计税金额" align="center"></el-table-column>
          <el-table-column prop="tax4" label="应纳税额" align="center"></el-table-column>
        </el-table-column>
      </el-table>
    </div>

    <div class="chart-wrapper">
      <div id="EchartContainer"></div>
      <div id="pepContainer"></div>
    </div>
  </div>
</template>

<script>
import {
  getTaxCategoryList,
  getYearTaxList,
} from '@/api/utils'
import {listDept} from "@/api/system/dept";
import  moment from 'moment'
import * as echarts from 'echarts';

export default {
  name: 'StampDutyStatistics',

  components:{
  },
  data() {
    return {
      dialogVisible:false,
      taxCategoryList:[],
      yearTaxList: [],
      barTaxList: [],
      peps:[],
      options:[],
      defaultProps: {
        children: "children",
        label: "name",
      },
      queryParams:{
        selectName: '',
        orgName:'',
        year:moment().format('YYYY'),
      },
      // 标签数组
      tagList: [

      ],
      // 遮罩层
      loading: false,
      pageNo:1,
      pageSize:10,
      total:0,
      ruleForm:{},
      spanArr:[],
      pos:0,
    };
  },

  async mounted() {
    this.getList();
    this.getListM();
  },

  computed:{

  },
  methods: {
    handSech(){
      this.getList()
    },
    delValue() {
      this.queryParams.orgName = ''
      this.queryParams.selectName = '';
    },
    // 结构树点击事件
    handleNodeClick(data) {
      console.log(data,'----')
      this.queryParams.orgName = data.deptId; // select绑定值为点击的选项的value
      this.queryParams.selectName = data.deptName; // input中显示值为label
      this.treeFilter = ""; // 点击后搜索框清空
      this.$refs.select.blur(); // 点击后关闭下拉框，因为点击树形控件后select不会自动折叠
    },
    // 模糊查询（搜索过滤），实质为筛选出树形控件中符合输入条件的选项，过滤掉其他选项
    filterNode(value, data) {
      if (!value) return true;
      let filterRes = data.label.indexOf(value) !== -1;
      return filterRes;
    },
    // 选项卡标签（可忽略，增值迭代需求）
    filterorgType(val) {
      let arr = this.tagList.filter((item) => {
        return item.value == val;
      });
      return arr.length ? arr[0].label : "";
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 1) {
        /*
        将需要合并的行数赋值给 _row，注意这里由上一个方法的输出可以知道，这里的值可以是 3或者0
        当为 3 时，表示将当下的第 rowIndex+1 行与第 columnIndex+1 列所指向的单元格向下合并 _row 格
        当为 0 时，表示将当下的第 rowIndex+1 行与第 columnIndex+1 列所指向的单元格隐藏
        */
        const _row = this.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        }
      }else {
        // return {
        //   rowspan: 0,
        //   colspan: 0
        // }
      }
    },
    getSpanArr(data) {
      for (let i = 0; i < data.length; i++) {
        // 如果是第一个数据，就将列表spanArr添加一个1，表示暂时只有一个名字相同的、且将索引pos赋值为0
        if (i === 0) {
          this.spanArr.push(1);
          this.pos = 0
        } else {
          // 判断当前元素与上一个元素是否相同
          if (data[i].groupName === data[i - 1].groupName) {
            // 如果相同就将索引为 pos 的值加一
            this.spanArr[this.pos] += 1;
            // 且将数组添加 0
            this.spanArr.push(0);
          } else {
            // 如果元素不同了，就可以通过索引为 pos 的值知晓应该需要合并的行数
            // 同时，我们再次添加一个值1，表示重新开始判断重复姓名的次数
            this.spanArr.push(1);
            // 同时 索引加一
            this.pos = i;
          }
        }
      }
    },
    headerStyle({ row, column,rowIndex,columnIndex}) {
      if (rowIndex === 1) {
        //这里为了是将第二列的表头隐藏，就形成了合并表头的效果
        return {display: 'none'}

      }
      return "background:#f5f7fa"

    },
    delect(row){
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        adsMatHyxtStampTaxInvoiceDelc(row).then(res => {
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getList()
          } else {
            this.$message({
              type: 'error',
              message: '删除失败，请重试!'
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      })
    },
    moment,
    /** 查询部门列表 */
    getList() {
      this.loading = true;
      const { orgName, year } = this.queryParams
      let data={
        homeOrgNo: orgName,
        year,
      }
      getTaxCategoryList(data).then((response) => {
        if(response && response.data){
          this.loading = false;
          this.taxCategoryList = response.data.list;
          this.barTaxList = response.data.bar;
          this.peps = response.data.peps;
          this.initPep();
          this.initChart();

        }else {
          this.taxCategoryList =[]
          this.barTaxList = [];
          this.peps = [];
          this.loading = false;
        }
      });
    },
    getListM() {
      listDept().then((response) => {
        this.options = this.handleTree(response.data, "deptId");
      });
    },
    handleSizeChange(val) {
      this.pageSize=val
      this.getList()
    },
    handleCurrentChange(val) {
      this.pageNo=val
      this.getList()
    },
    async getYearTaxList() {
      const { orgName, year } = this.queryParams
      let body={
        orgName,
        year,
      }
      const response = await getYearTaxList(body)
      if(response && response.data){
        this.loading = false;
        this.yearTaxList = response.data.list;

      }else {
        this.yearTaxList =[];

        this.loading = false;
      }
    },
    initChart() {
      const yearList = this.barTaxList.map(i => i.year)
      const taxFeeList = this.barTaxList.map(i => i.taxFee)
      const taxList = this.barTaxList.map(i => i.tax)


      const chartDom = document.querySelector('#EchartContainer');
      const myChart = echarts.init(chartDom);
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
        },
        xAxis: {
          type: 'category',
          data: yearList
        },
        yAxis: [
          {
            name: '计税金额',
            type: 'value',
          },
          {
            name: '应纳税额',
            type: 'value',
            splitLine: {
              show: false
            }
          },
        ],

        series: [
          {
            data: taxFeeList,
            type: 'bar',
            yAxisIndex: 0,
          },
          {
            data: taxList,
            type: 'bar',
            yAxisIndex: 1,
          },
        ]
      };

      option && myChart.setOption(option);
    },
    initPep(){
      const chartDom = document.querySelector('#pepContainer');
      const myChart = echarts.init(chartDom);
      const option = {
        title: {
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
        },
        series: [
          {
            type: 'pie',
            radius: '50%',
            data:this.peps,
            label: {
              normal: {
                show: true,
                formatter: '{b}: {d}%'
              }
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            startAngle: 280 // 设置起始角度
          },
        ]
      };

      option && myChart.setOption(option);
    }
  },
};
</script>

<style lang="scss" scoped>
//.table{
//  height: 100% !important;
//}
::v-deep .el-table{
  height: 70vh !important;
  overflow-y: scroll;
}

.app-container {
  overflow: auto;

  .chart-wrapper {
    width: 100%;
    height: 50%;
    display: flex;
    #EchartContainer {
      width: 60%;
    }
    #pepContainer {
      width: 40%;
    }
  }
}

</style>
