<template>
  <a-card>
    <a-form-model ref="search" v-bind="formItemLayout" :class="$style.form">
      <a-row>
        <a-col :span="6">
          <a-form-model-item label="查询公司选择">
            <audit-unit-select
              ref="cRelSelect"
              v-model="orgList"
              :read-only="false"
              :single="false"
              @change="changecompany"
            />
          </a-form-model-item>
        </a-col>

        <a-col :span="6">
          <a-form-model-item label="年份">
            <AuditYearTime v-model="year" />
          </a-form-model-item>
        </a-col>

        <!-- 搜索重置 -->
        <a-col :span="6">
          <a-form-model-item>
            <a-button style="margin-left: 15px" type="primary" @click="handlerSearch">
              搜索
            </a-button>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
    <div :class="$style.zbType">
      <a-button type="link" size="large">所选指标值：{{ zbName }}</a-button>
      <a-button type="primary" @click="goBack">返回重选</a-button>
    </div>
    <a-card>
      <!-- <sd-table
        :columns="columns"
        :scroll="{ x: '100%' }"
        :data-source="tableData"
        :row-key="(record, i) => record.key"

        :pagination="false"
      >
      </sd-table> -->
      <vxe-table
        ref="xTable"
        :key="tableKey"
        border
        :column-config="{ resizable: true }"
        :data="tableData"
        align="center"
        :tree-config="{}"
      >
        <template v-for="(item, i) in columns">
          <!-- 如果有children 则显示colgroup -->
          <vxe-colgroup
            v-if="item?.children?.length > 0"
            :key="i"
            :title="item.title"
            :field="item.dataIndex"
            align="center"
            :fixed="fixedType(i)"
          >
            <template v-for="(item1, i1) in item.children">
              <vxe-column
                :key="i1"
                :field="item1.dataIndex"
                :title="item1.title"
                align="center"
                min-width="240"
              >
              </vxe-column>
            </template>
          </vxe-colgroup>
          <vxe-column
            v-else
            :key="i"
            :title="item.title"
            :field="item.dataIndex"
            align="center"
            :fixed="fixedType(i)"
          ></vxe-column>
        </template>
      </vxe-table>
    </a-card>
    <a-card>
      <div :class="$style.barLineType">
        <span
          :style="{
            fontSize: '18px',
            color: action === 1 ? '#1890ff' : '#333',
            marginRight: '10px',
          }"
          @click="onTypeChange(1)"
          >柱状图</span
        >
        <span
          :style="{ fontSize: '18px', color: action === 2 ? '#1890ff' : '#333' }"
          @click="onTypeChange(2)"
          >折线图</span
        >
      </div>
      <div id="barLine" :class="$style.barLine"></div>
    </a-card>
  </a-card>
</template>

<script>
import components from './_import-components/audit-contrast-view-import'
import echarts from 'echarts'
import AuditYearTime from './audit-year-time.vue'
import auditUnitSelect from './audit-unit-select'
import auditPortraitService from './audit-portrait-service'
import { message } from 'ant-design-vue'
import VXETable from 'vxe-table'
import 'vxe-table/lib/style.css'
import Vue from 'vue'
Vue.use(VXETable)

export default {
  name: 'AuditContrastView',
  metaInfo: {
    title: '对比',
  },
  components: {
    ...components,
    AuditYearTime,
    auditUnitSelect,
  },
  data() {
    return {
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 18 },
      },
      zbName: '',
      orgList: [],
      year: [],
      columns: [],
      tableData: [],
      action: 1,
      myChart: null,
      queryParams: null,
      tableKey: 1,
    }
  },
  created() {
    // this.initEcharts()
    this.initSearchData()
  },
  methods: {
    fixedType(i) {
      if (i === 0) return 'left'
    },
    // 初始化search数据
    initSearchData() {
      // 获取当前公司信息
      this.queryParams = JSON.parse(this.$route.query.params || '{}')
      this.orgList = this.queryParams.orgList || []
      this.year = this.queryParams.year || []
      this.zbName = this.queryParams.zbName || ''

      this.initTableData()
    },
    initTableData() {
      /**
       * mdg_orgCode
       */
      // private List<String> mdgOrgCodes;
      // /**
      //  * 年
      //  */
      // private List<Integer> year;

      // /**
      //  *指标
      //  */
      // private String metricName;
      // 获取表格数据
      const params = {
        mdgOrgCodes: this.orgList.map((res) => res.orgCode),
        year: this.year,
        metricName: this.queryParams.zbCode,
      }
      auditPortraitService.listMetricCompare(params).then((res) => {
        this.columns = [
          {
            fixed: 'left',
            children: [
              {
                // 公司名称
                title: '公司名称',
                dataIndex: 'orgName',
                fixed: 'left',
                width: '280px',
                // 自定义渲染 如果超长则显示tooltip
                customRender: (text) => {
                  return {
                    children: (
                      <a-tooltip title={text}>
                        <div style='width:100%;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;'>
                          {text}
                        </div>
                      </a-tooltip>
                    ),
                  }
                },
              },
            ],
          },
        ]
        this.tableData = res.data.data.map((val, i) => {
          const obj = {}
          obj.key = i
          obj.orgName = val.org_name
          obj.orgCode = val.org_code
          val.values.map((item1) => {
            const isValue = this.zbName.includes('率')
            if (isValue) {
              obj[`zbz${item1.year}`] = (item1.value * 100).toFixed(2) || ''
            } else {
              obj[`zbz${item1.year}`] = item1.value
            }
            // 如果是NaN则显示原本的值
            if (isNaN(obj[`zbz${item1.year}`])) {
              obj[`zbz${item1.year}`] = item1.value
            }
          })

          return obj
        })
        if (res.data.data.length === 0) {
          return message.warning('暂无数据')
        }

        res.data.data[0].values.map((item1) => {
          this.columns.push({
            // 2020 指标值
            align: 'center',
            title: item1.year,
            children: [
              {
                title: '指标值',
                dataIndex: `zbz${item1.year}`,
                align: 'center',
                width: '180px',
              },
            ],
          })
        })
        this.tableKey++
        this.initEcharts()
      })
    },
    changecompany(val) {
      this.orgList = val
    },
    handlerSearch() {
      this.initTableData()
    },
    resetSearch() {
      this.orgList = []
      this.year = []
    },
    goBack() {
      // 返回上一页
      // window.history.go(-1)
      // 关闭当前页面
      window.close()
    },
    //
    onTypeChange(type) {
      this.action = type
      // 折线图
      this.initEcharts()
    },
    initEcharts() {
      const unitList = this.tableData.map((res) => res.orgName)
      //
      // 单位 CNY 如果colTitle含率则单位为%
      const dw = this.zbName.includes('率') ? '%' : '万元'
      // 根据公司分割数据

      const year = Object.keys(this.tableData[0] || {}).filter((val) => val.includes('zbz'))
      const yearList = year.map((val) => val.replace('zbz', ''))

      const seriesData = yearList.map((val, i) => {
        return {
          name: val,
          data: this.tableData.map((res) => res[`zbz${val}`]),
          type: this.action === 1 ? 'bar' : 'line',
          // 柱子宽度
          barMaxWidth: 50,
          // 柱子颜色 三选择一
          itemStyle: {
            color: i % 2 === 0 ? '#1890ff' : '#E76F00',
          },
          // 柱子间距
        }
      })
      this.myChart = echarts.init(document.getElementById('barLine'))
      const option = {
        title: {
          text: this.zbName,
          textStyle: {
            rich: {
              a: {
                fontSize: 16,
                fontWeight: 600,
              },
            },
          },
          top: '0%',
          left: '45%',
        },
        tooltip: {
          trigger: 'item',
          // 带单位
          formatter: '{a} <br/>{b} : {c}' + dw,
        },

        grid: {
          left: '5%',
          containLabel: true,
        },
        //  x轴滚动
        dataZoom: [
          {
            type: 'slider',
            show: true,
            xAxisIndex: [0],
            startValue: 0, // 起始值
            endValue: 10, // 结束值
          },
          {
            type: 'inside',
            xAxisIndex: [0],
            start: 0,
            end: 10,
          },
        ],
        xAxis: {
          type: 'category',
          data: unitList,
          // 每组数据间隔
          axisTick: {
            alignWithLabel: true,
          },
          axisLabel: {
            show: true, // 是否显示刻度标签，默认显示
            interval: 0, // 坐标轴刻度标签的显示间隔，在类目轴中有效；默认会采用标签不重叠的策略间隔显示标签；可以设置成0强制显示所有标签；如果设置为1，表示『隔一个标签显示一个标签』，如果值为2，表示隔两个标签显示一个标签，以此类推。
            inside: false, // 刻度标签是否朝内，默认朝外
            margin: 6, // 刻度标签与轴线之间的距离
            // 文字大小
            fontSize: 18,
            // formatter: '{value}', // 刻度标签的内容格式器
            // 旋转15
            rotate: -15,
          },
          //
        },

        yAxis: {
          name: dw,
          type: 'value',
          minInterval: 1,
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#111',
            },
          },
        },
        // tooltip: {
        //   trigger: 'axis',
        //   axisPointer: {
        //     type: 'shadow',
        //   },
        // },
        // 图例
        legend: {
          data: [year],
          textStyle: {
            align: 'right',
          },
          top: '2%',
          right: '2%',
        },
        series: seriesData,
      }
      this.myChart.setOption(option)
      window.addEventListener('resize', () => {
        this.myChart.resize()
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.bar-line {
  width: 100%;
  height: 600px;
}
.zb-type {
  margin: 10px 0;
}
.bar-line-type {
  span {
    cursor: pointer;
  }
}
</style>
