<template>
  <a-spin :spinning="isshowLoading5" :tip="tiptext" size="large" style="background: #f0f2f5">
    <a-layout style="height: 100vh;padding: 20px;overflow: scroll">
      <a-card style="margin-bottom: 20px">
        <!-- 推送时间，业务时间，单位名称 -->
        <!-- 审计线索统计 -->
        <div :class="$style.title">
          <a-form-model layout="inline">
            <a-form-model-item>
              <div :class="$style.time">
                <a-row>
                  <a-col :span="6">
                    <a-select v-model="searchForm.timeType">
                      <a-select-option key="1" value="1">推送时间</a-select-option>
                      <a-select-option key="2" value="2">业务时间</a-select-option>
                    </a-select>
                  </a-col>
                  <a-col :span="18" style="padding-top: 1px;">
                    <a-range-picker v-model="searchForm.timeArr" />
                  </a-col>
                </a-row>
              </div>
            </a-form-model-item>

            <a-form-model-item label="单位名称">
              <div style="width:200px">
                <a-select
                  v-if="isUnitType === 'group'"
                  ref="zb"
                  v-model="targetKeysList"
                  mode="multiple"
                  :open="false"
                  :max-tag-count="2"
                  @focus="focusZb"
                >
                  <a-select-option v-for="(item, i) in mockData" :key="i" :value="item.key">
                    {{ item.title }}
                  </a-select-option>
                </a-select>
                <SdGroupPicker
                  v-else
                  ref="cRelSelect"
                  v-model="searchForm.unitArr"
                  :read-only="false"
                  :root-node="rootNodeData"
                  @change="changecompany"
                />
              </div>
            </a-form-model-item>

            <a-form-model-item>
              <a-button type="primary" @click="search('all')">查询</a-button>
              <!-- 重置 -->
              <a-button @click="resetSearch">重置</a-button>
            </a-form-model-item>
          </a-form-model>
        </div>
        <!-- 模型类型 事件标签分类 模型领域 -->
        <!-- 查询导出 -->
        <a-divider />
        <h3 :class="$style.riskviewtitle">审计线索统计</h3>

        <div :class="$style.lineBarBody">
          <a-form-model layout="inline" :class="$style.formBar">
            <a-form-model-item :label="'模型类型'" prop="modelType">
              <a-select v-model="linebarSearchForm.modelType" placeholder="请选择模型类型">
                <a-select-option value="1">定位型-整改类</a-select-option>
                <a-select-option value="2">定位型-关注类</a-select-option>
              </a-select>
            </a-form-model-item>

            <a-form-model-item label="事件标签分类">
              <a-select v-model="linebarSearchForm.eventTag" mode="multiple" allow-clear>
                <a-select-option v-for="(item, i) in eventList" :key="i" :value="item.id">{{
                  item.tagName + '-' + item.id
                }}</a-select-option>
              </a-select>
            </a-form-model-item>

            <a-form-model-item label="模型领域">
              <a-select
                v-model="linebarSearchForm.modelField"
                placeholder="请选择模型领域"
                allow-clear
                mode="multiple"
              >
                <a-select-option v-for="(item, i) in areaOption" :key="i" :value="item.id">{{
                  item.name
                }}</a-select-option>
              </a-select>
            </a-form-model-item>

            <a-form-model-item>
              <a-button type="primary" @click="search('lineBer')">查询</a-button>
              <a-popover
                v-model="visibleExport"
                title="请选择导出维度"
                placement="bottom"
                trigger="click"
              >
                <div slot="content">
                  <!-- 按照 事件标签 按责任人 确定取消按钮 -->
                  <a-row style="margin-bottom: 15px">
                    <a-radio-group v-model="exportType">
                      <a-radio :style="radioStyle" value="1">按照事件标签</a-radio>
                      <a-radio :style="radioStyle" value="2">按照责任人</a-radio>
                    </a-radio-group>
                  </a-row>
                  <div style="text-align: right">
                    <a-button @click="visibleExport = false">取消</a-button>
                    <a-button type="primary" @click="onExportEvent">确定</a-button>
                  </div>
                </div>
                <a-button type="primary">
                  导出
                </a-button>
              </a-popover>
            </a-form-model-item>
          </a-form-model>
          <a-spin :spinning="isshowLoading1" tip="正在查询请稍后...">
            <div id="linebar" :class="$style.linebar"></div>
          </a-spin>
        </div>
      </a-card>

      <!-- 整改率统计 -->
      <!-- 按单位 按模型 -->
      <!-- 单位名称 -->
      <a-card style="padding-top: 20px">
        <h3 :class="$style.riskviewtitle">整改率统计</h3>
        <div :class="$style.searchBtn">
          <a-button-group>
            <a-button :type="zgSumType ? 'primary' : ''" @click="zgSumType = true">按单位</a-button>
            <a-button :type="zgSumType ? '' : 'primary'" @click="zgSumType = false"
              >按领域</a-button
            >
          </a-button-group>
        </div>
        <a-form layout="inline">
          <a-form-model-item v-if="zgSumType" label="单位名称">
            <div style="width:200px">
              <SdGroupPicker
                ref="zgRelSelect"
                v-model="lineUnit"
                :root-node="rootNodeData"
                :read-only="false"
                :single="true"
              />
            </div>
            <!-- <a-input v-model=".unitName" /> -->
          </a-form-model-item>
          <a-form-model-item v-else label="模型领域" mode="multiple">
            <div style="width:200px">
              <a-select v-model="areaType" placeholder="请选择模型领域" allow-clear>
                <a-select-option v-for="(item, i) in areaOption" :key="i" :value="item.id">{{
                  item.name
                }}</a-select-option>
              </a-select>
            </div>
          </a-form-model-item>
          <a-form-model-item>
            <a-button type="primary" @click="search('line')">查询</a-button>
            <a-button v-if="zgSumType" type="primary" @click="exportBar">导出</a-button>
          </a-form-model-item>
        </a-form>
        <a-spin :spinning="isshowLoading2" tip="正在查询请稍后...">
          <div id="rectifyRate" :class="$style.rectifyRate"></div>
        </a-spin>
        <!-- 问题概括统计饼图、模型领域统计饼图 -->
        <a-row :gutter="24" style="margin-top: 20px">
          <a-col :span="12" :class="$style.exportBody">
            <!-- 右上角导出 -->
            <h3 :class="$style.riskviewtitle">问题概括统计</h3>
            <div :class="$style.exportIcon">
              <a-icon type="download" :style="{ fontSize: '22px' }" @click="exportPie1" />
            </div>
            <a-spin :spinning="isshowLoading3" tip="正在查询请稍后...">
              <div v-if="barishow1" id="problemSummary" :class="$style.bingtu"></div>
              <a-empty
                v-else
                style="height: 400px;
    line-height: 400px;"
              />
            </a-spin>
          </a-col>
          <a-col :span="12" :class="$style.exportBody">
            <h3 :class="$style.riskviewtitle">模型领域统计</h3>
            <div :class="$style.exportIcon">
              <a-icon type="download" :style="{ fontSize: '22px' }" @click="exportPie2" />
            </div>
            <a-spin :spinning="isshowLoading4" tip="正在查询请稍后...">
              <div v-if="barishow2" id="modelField" :class="$style.bingtu"></div>
              <a-empty
                v-else
                style="height: 400px;
    line-height: 400px;"
              />
            </a-spin>
          </a-col>
        </a-row>
      </a-card>

      <a-modal v-model="visibleZb" title="公司选择" @ok="zbOk">
        <a-transfer
          :data-source="mockData"
          show-search
          :list-style="{
            width: '400px',
            height: '500px',
          }"
          :target-keys="targetKeys"
          :render="(item) => item.title"
          @change="handleChangeZb"
        />
      </a-modal>
    </a-layout>
  </a-spin>
</template>

<script>
import components from './_import-components/audit-risk-view-import'
import auditMaintainService from '../maintain/audit-maintain-service'
import echarts from 'echarts'
import AuditRiskbraryService from './riskLibrary'
import moment from 'moment'
import { getUserInfo } from '@/common/store-mixin'
import DataService from '../dataUphold/data-config'
import SdGroupPicker from '@/common/components/sd-group-picker.vue'
import download from '@/common/services/download'
import { message, Modal } from 'ant-design-vue'

export default {
  name: 'AuditRiskView',
  metaInfo: {
    title: '审计问题看板',
  },
  components: {
    ...components,
    SdGroupPicker,
  },
  data() {
    return {
      isshowLoading1: false,
      isshowLoading2: false,
      isshowLoading3: false,
      isshowLoading4: false,
      isshowLoading5: false,
      tiptext: '正在导出请稍等……',
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 18 },
      },
      formItemLayout2: {
        labelCol: { span: 8 },
        wrapperCol: { span: 16 },
      },
      searchForm: {
        timeType: '1',
        timeArr: [],
        unitArr: [],
      },
      // 单位类型
      isUnitType: 'unit',
      linebarSearchForm: {
        modelType: '1',
        eventTag: [],
        modelField: [],
      },
      areaType: '',
      lineUnit: [],
      barSearchForm: {
        unitName: '',
        searchType: 'unit',
      },

      // 模型类型
      // 1定位型-整改类 2定位型-关注类
      modelTypeOption: [
        {
          key: '1',
          value: '定位型-整改类',
        },
        {
          key: '2',
          value: '定位型-关注类',
        },
      ],
      targetKeys: [],
      // 模型领域
      areaOption: [],
      rootNodeData: [],
      exportType: '1',
      visibleExport: false,
      radioStyle: {
        display: 'block',
        height: '30px',
        lineHeight: '30px',
      },
      eventList: [],
      // 整改单位类型
      zgSumType: true,
      visibleZb: false,
      mockData: [],
      targetKeysList: [],
      unitCodeList: [],
      chart1: null,
      chart2: null,
      chart3: null,
      chart4: null,
      barishow1: true,
      barishow2: true,
      // 下钻code
      downCode: '',
      // 是否有数据
    }
  },
  watch: {
    zgSumType(val) {
      // 切换单位和领域
      // 清空单位或者领域
      if (val) {
        this.areaType = ''
      } else {
        this.lineUnit = []
      }
      this.initRectifyRate()
    },
  },
  mounted() {
    this.getAreaOption()
    this.initSearchData()
    AuditRiskbraryService.getGroups().then((res) => {
      this.isUnitType = 'group'
      this.mockData = res.data.data.map((item) => ({
        key: item.code + '',
        title: item.name,
        description: item.description,
      }))
      // 如果长度为0，则显示二级单位
      if (this.mockData.length === 0) {
        this.getUserUnitCode()
        this.isUnitType = 'unit'
      }
      this.getMinxLinerBarData()
      this.initRectifyRate()
      this.initProblemSummary()
      this.initModelField()
    })

    // 尺寸变化
    window.addEventListener('resize', () => {
      this.chart1 && this.chart1.resize()
      this.chart2 && this.chart2.resize()
      this.chart3 && this.chart3.resize()
      this.chart4 && this.chart4.resize()
    })
  },
  methods: {
    initSearchData() {
      // 开始时间为当年1月1日 结束时间为当前时间
      this.searchForm.timeArr = [moment().startOf('year'), moment()]
      // 初始化集团
      auditMaintainService.getEventTagList().then((res) => {
        this.eventList = res.data
      })
    },
    changecompany(val) {
      this.searchForm.unitArr = val
    },
    zbOk() {
      this.visibleZb = false
      this.searchForm.zb = this.targetKeys
      this.targetKeysList = this.targetKeys
    },
    focusZb() {
      this.visibleZb = true
      this.$refs.zb.blur()
      AuditRiskbraryService.getGroups().then((res) => {
        this.isUnitType = 'group'
        this.mockData = res.data.data.map((item) => ({
          key: item.code + '',
          title: item.name,
          description: item.description,
        }))
        // 如果长度为0，则显示二级单位
        if (this.mockData.length === 0) {
          this.getUserUnitCode()
          this.isUnitType = 'unit'
        }
      })
    },
    // 获取当前用户单位，并且以当前单位为根节点
    getUserUnitCode() {
      const userInfo = getUserInfo()
      DataService.getCompany(userInfo.account).then((res) => {
        this.rootNodeData = {
          code: res.data.id,
          name: res.data.name,
          orgCode: res.data.code,
        }
      })
    },
    handleChangeZb(nextTargetKeys, direction, moveKeys) {
      this.targetKeys = nextTargetKeys
    },
    // getGroups 获取组织

    // 筛选部分
    getAreaOption() {
      auditMaintainService.getAreaListAll().then((res) => {
        this.areaOption = res.data
      })
    },
    // 搜索
    search(type) {
      if (type === 'all') {
        this.getMinxLinerBarData()
        this.initRectifyRate()
        this.initProblemSummary()
        this.initModelField()
      }
      if (type === 'lineBer') {
        this.getMinxLinerBarData()
      }
      if (type === 'line') {
        this.initRectifyRate()
      }
    },
    // 重置
    resetSearch() {
      this.searchForm = {
        timeType: '1',
        timeArr: [moment().startOf('year'), moment()],
        unitArr: [],
      }
      this.targetKeysList = []
      this.linebarSearchForm = {
        modelType: '1',
        eventTag: [],
        modelField: [],
      }
      this.search('all')
    },
    // onExportEvent 导出
    onExportEvent() {
      this.visibleExport = false
      // 获取导出类型
      this.isshowLoading5 = true
      const params = this.getSearchData('lineBar')
      // 如果下钻code

      // 如果是事件标签
      if (this.exportType === '1') {
        AuditRiskbraryService.exportBoardLine(params)
          .then((res) => {
            if (res.status === 200) {
              const url = URL.createObjectURL(res.data)
              const filename = res.headers['content-disposition']
              const fname = filename.substring(filename.indexOf('filename=') + 9, filename.length)
              download(url, decodeURI(fname))
              // 导出成功
              message.success('导出成功')
            } else {
              Modal.warning({
                title: '提示',
                content: '导出报错，请联系管理员!',
              })
              return false
            }
          })
          .finally(() => {
            this.isshowLoading5 = false
          })
      }
      if (this.exportType === '2') {
        AuditRiskbraryService.resPersonExport(params)
          .then((res) => {
            if (res.status === 200) {
              const url = URL.createObjectURL(res.data)
              const filename = res.headers['content-disposition']
              const fname = filename.substring(filename.indexOf('filename=') + 9, filename.length)
              download(url, decodeURI(fname))
              // 导出成功
              this.isshowLoading5 = false
              message.success('导出成功')
            } else {
              this.isshowLoading5 = false
              Modal.warning({
                title: '提示',
                content: '导出报错，请联系管理员!',
              })
              return false
            }
          })
          .finally(() => {
            this.isshowLoading5 = false
          })
      }
    },

    // 获取筛选条件
    getSearchData(type = 'all', xzCode = '') {
      const params = {}

      const timeArr = this.searchForm.timeArr.map((item) =>
        item ? moment(item).format('YYYY-MM-DD') : ''
      )
      // 时间类型
      if (this.searchForm.timeType === '1') {
        params.pushDateSt = timeArr[0]
        params.pushDateEd = timeArr[1]
      } else {
        // 转化为时间戳
        params.bussTimeSt = moment(timeArr[0]).valueOf()
        params.bussTimeEd = moment(timeArr[1]).add(1, 'days').valueOf()
      }
      // 是否是集团
      if (this.isUnitType === 'group') {
        params.unitCodeList = this.targetKeysList
        params.unitCode = xzCode
        if (this.downCode) {
          params.unitCode = this.downCode
        }
      } else {
        params.unitCodeList = this.searchForm.unitArr.map((item) => item.code)
      }
      // linebar筛选项
      if (type === 'lineBar') {
        params.modelType = this.linebarSearchForm.modelType
        params.eventTagList = this.linebarSearchForm.eventTag
        params.modelDomainList = this.linebarSearchForm.modelField
      }
      if (type === 'line') {
        params.unitName = this.lineUnit.length > 0 ? this.lineUnit[0].name : ''
        params.dimension = this.zgSumType ? 0 : 1
        params.domainName = this.areaOption.find((item) => item.id === this.areaType)?.name || ''
      }
      if (type === 'bar') {
      }
      return params
    },
    getMinxLinerBarData(type, xzCode = '') {
      this.isshowLoading1 = true
      AuditRiskbraryService.reformBoard(this.getSearchData('lineBar', xzCode))
        .then((res) => {
          const data = res.data.data

          const xAxisData = data.map((item) => item.unitName)
          // 整改率
          const seriesData = data.map((item) => ((item.reformRate || 0) * 100).toFixed(2))
          // 期限内已整改
          const seriesData1 = data.map((item) => ({ value: item.status0, ...item }))
          // 逾期已整改
          const seriesData2 = data.map((item) => item.status1)
          // 期限内未整改已完成
          const seriesData3 = data.map((item) => item.status2)
          // 逾期未整改完成
          const seriesData4 = data.map((item) => item.status3)
          // 已查看
          const seriesData5 = data.map((item) => item.viewCount)
          // 未查看
          const seriesData6 = data.map((item) => item.nonViewCount)
          this.unitCodeList = data.map((item) => item.unitCode)
          this.initMixLineBar(
            xAxisData,
            seriesData,
            seriesData1,
            seriesData2,
            seriesData3,
            seriesData4,
            seriesData5,
            seriesData6,
            type
          )
        })
        .finally(() => {
          this.isshowLoading1 = false
        })
    },
    initMixLineBar(
      xAxisData,
      seriesData,
      seriesData1,
      seriesData2,
      seriesData3,
      seriesData4,
      seriesData5,
      seriesData6,
      type
    ) {
      const myChart = echarts.init(document.getElementById('linebar'))
      const colorList = [
        '#fac858',
        '#5470c6',
        '#91cc75',
        '#fac858',
        '#ee6666',
        '#1890ff',
        '#a90000',
      ]
      const option = {
        height: 500,
        tooltip: {
          trigger: 'axis',
          // 调整颜色
          backgroundColor: 'rgba(255,255,255,1)',
          textStyle: {
            color: '#000',
          },
          // 字体颜色
          // 黑色

          formatter: function(params) {
            const paramsMap = params.map((item) => {
              return {
                seriesName: item.seriesName,
                value: item.value,
              }
            })
            if (params[1].data.modelType === 2 || params[1].data.modelType === '2') {
              paramsMap.push({
                seriesName: '已查看',
                value: params[1].data.viewCount,
              })
              paramsMap.push({
                seriesName: '未查看',
                value: params[1].data.nonViewCount,
              })
            }

            let str =
              '<div style="text-align:left;font-size:18px;margin-bottom: 10px">' +
              params[0].name +
              '<br></div>'
            paramsMap.forEach((item, index) => {
              // 如果名字是整改率
              str += `
              <div style='display:flex;justify-content: space-between;'>
                <div style='display:flex;align-items: center;'>
                  <div style="display:flex;align-items: center;width: '200px';color:'#333'">
                    <div style='margin-right:5px;width:${
                      item.seriesName === '整改率' ? '10px' : '20px'
                    };height:10px;border-radius:${
                item.seriesName === '整改率' ? '50%' : '2px'
              };background:${colorList[index]}'></div>
                    ${item.seriesName}
                  </div>
                </div>
                ${item.value} ${item.seriesName === '整改率' ? '%' : '条'}
              </div>
                `
            })

            return str
          },
        },
        grid: {
          top: 100,
          left: '1%', // grid布局设置适当调整避免X轴文字只能部分显示
          right: '5%', // grid布局设置适当调整避免X轴文字只能部分显示
          bottom: '5%',
          containLabel: true,
        },
        toolbox: {
          feature: {
            restore: { show: true },
            saveAsImage: { show: true },
          },
        },
        //  x轴滚动
        dataZoom: [
          {
            type: 'slider',
            show: true,
            xAxisIndex: [0],
            start: 0,
            end: 35,
            height: 10,
          },
          {
            type: 'inside',
            xAxisIndex: [0],
            start: 0,
            end: 35,
            height: 10,
          },
        ],
        title: {
          subtext: `注：整改率表示该公司已提交整改材料并经审批通过的问题数（含期限内已整改的问题数）占全部问题数的比例，
          整改率=100%*(期限内已整改问题数 + 逾期已整改问题数) / (期限内已整改问题数 + 逾期已整改问题数 + 期限内未整改问题数 + 逾期未整改问题数))`,
          left: 'center',
          top: '20px',
          itemGap: 10,
          subtextStyle: {
            fontSize: 14,
          },
        },
        legend: {
          show: true,
          data: ['整改率', '期限内已整改', '逾期已整改', '期限内未整改完成', '逾期未整改完成'],
          // 图例距离图表位置
          top: 0,

          // 图例颜色
        },
        color: ['#fac858', '#5470c6', '#91cc75', '#fac858', '#ee6666'],
        xAxis: [
          {
            type: 'category',
            data: xAxisData,

            axisLabel: {
              // 字体大小16
              show: true, // 是否显示刻度标签，默认显示
              interval: 0, // 坐标轴刻度标签的显示间隔，在类目轴中有效；默认会采用标签不重叠的策略间隔显示标签；可以设置成0强制显示所有标签；如果设置为1，表示『隔一个标签显示一个标签』，如果值为2，表示隔两个标签显示一个标签，以此类推。
              inside: false, // 刻度标签是否朝内，默认朝外
              margin: 6, // 刻度标签与轴线之间的距离
              // formatter: '{value}', // 刻度标签的内容格式器
              fontSize: 16,
              rotate: -15, // 刻度标签旋转的角度
            },
          },
        ],
        yAxis: [
          {
            type: 'value',
            name: '整改率',
            min: 0,
            interval: 10,
            axisLabel: {
              formatter: '{value} %',
            },
          },
          {
            type: 'value',
            name: '问题数据量',
            min: 0,

            axisLabel: {
              formatter: '{value} 条',
            },
          },
        ],
        series: [
          {
            name: '整改率',
            type: 'line',
            yAxisIndex: 0,
            tooltip: {
              valueFormatter: function(value) {
                return value + '%'
              },
            },
            data: seriesData,
            barWidth: 25,
          },
          {
            name: '期限内已整改',
            type: 'bar',
            yAxisIndex: 1,
            // 宽度
            tooltip: {
              valueFormatter: function(value) {
                return value + ' 条'
              },
            },
            // 堆叠
            stack: 'a',
            data: seriesData1,
            barWidth: 25,
          },
          {
            name: '逾期已整改',
            barWidth: 25,
            type: 'bar',
            yAxisIndex: 1,
            tooltip: {
              valueFormatter: function(value) {
                return value + ' 条'
              },
            },
            stack: 'a',
            // data: [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3],
            data: seriesData2,
          },
          {
            name: '期限内未整改完成',
            barWidth: 25,
            type: 'bar',
            yAxisIndex: 1,
            tooltip: {
              valueFormatter: function(value) {
                return value + ' 条'
              },
            },
            stack: 'a',
            // data: [2.0, 2.2, 3.3, 4.5, 6.3, 10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 6.2],
            data: seriesData3,
          },
          {
            name: '逾期未整改完成',
            type: 'bar',
            barWidth: 25,
            yAxisIndex: 1,
            tooltip: {
              valueFormatter: function(value) {
                return value + ' 条'
              },
            },
            stack: 'a',
            // data: [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3],
            data: seriesData4,
          },
        ],
      }
      if (type === 'down') {
        option.graphic = [
          {
            type: 'text',
            left: 50,
            top: 20,
            style: {
              text: '返回',
              fontSize: 18,
              fontWeight: 700,
            },
            onclick: () => {
              // 删除返回
              this.downCode = ''
              this.getMinxLinerBarData()
            },
          },
        ]
      } else {
        option.graphic = [
          {
            type: 'text',
            left: 50,
            top: 20,
            style: {
              text: '',
              fontSize: 18,
            },
          },
        ]
      }

      myChart.setOption(option)
      // 修改unitCodeList 为全局变量
      // 可以下钻并且是集团
      if (type !== 'down' && this.isUnitType === 'group') {
        myChart.on('click', (params) => {
          this.downCode = this.unitCodeList[params.dataIndex]
          const unitCode = this.unitCodeList[params.dataIndex]
          this.getMinxLinerBarData('down', unitCode)
        })
      } else {
        myChart.off('click')
      }
      this.chart1 = myChart
    },
    // 获取整改率统计数据

    initRectifyRate(type, xzCode) {
      this.isshowLoading2 = true
      AuditRiskbraryService.reformRateStatistics(this.getSearchData('line', xzCode))
        .then((res) => {
          const colors = ['#91cc75']
          const data = res.data.data.map((item, i) => {
            return {
              value: ((item.reformRate || 0) * 100).toFixed(2),
              name: this.zgSumType ? item.unitName : item.domainName,
              code: item.unitCode,
              itemStyle: {
                color: colors[i],
              },
            }
          })
          const myChart = echarts.init(document.getElementById('rectifyRate'))
          const option = {
            color: colors,
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'cross',
                label: {
                  backgroundColor: '#6a7985',
                },
              },
            },
            legend: {
              data: ['整改率'],
            },
            toolbox: {
              feature: {
                saveAsImage: {},
              },
            },
            grid: {
              left: '1%', // grid布局设置适当调整避免X轴文字只能部分显示
              right: '5%', // grid布局设置适当调整避免X轴文字只能部分显示
              bottom: '5%',
              containLabel: true,
            },
            xAxis: {
              type: 'category',
              data: data.map((item) => item.name),
              axisLabel: {
                show: true, // 是否显示刻度标签，默认显示
                interval: 0, // 坐标轴刻度标签的显示间隔，在类目轴中有效；默认会采用标签不重叠的策略间隔显示标签；可以设置成0强制显示所有标签；如果设置为1，表示『隔一个标签显示一个标签』，如果值为2，表示隔两个标签显示一个标签，以此类推。
                inside: false, // 刻度标签是否朝内，默认朝外
                margin: 6, // 刻度标签与轴线之间的距离
                fontSize: 16,
                rotate: -15, // 刻度标签旋转的角度
              },
            },
            yAxis: {
              type: 'value',
              interval: 10,
              axisLabel: {
                formatter: '{value} %',
              },
            },
            //  x轴滚动
            dataZoom: [
              {
                type: 'slider',
                show: true,
                xAxisIndex: [0],
                start: 0,
                height: 10,
                end: 20,
              },
              {
                type: 'inside',
                xAxisIndex: [0],
                start: 0,
                height: 10,
                end: 20,
              },
            ],
            series: [
              {
                name: '整改率',
                type: 'bar',
                barWidth: 25,
                data: data,
              },
            ],
          }
          if (type === 'down') {
            option.graphic = [
              {
                type: 'text',
                left: 50,
                top: 20,
                style: {
                  text: '返回',
                  fontSize: 18,
                  // 加粗
                  fontWeight: 700,
                },
                onclick: () => {
                  // 删除返回
                  // 清空下钻code
                  this.initRectifyRate()
                },
              },
            ]
          } else {
            option.graphic = [
              {
                type: 'text',
                left: 50,
                top: 20,
                style: {
                  text: '',
                  fontSize: 18,
                },
              },
            ]
          }
          myChart.setOption(option)
          // 点击下钻
          if (type !== 'down' && this.isUnitType === 'group') {
            myChart.on('click', (params) => {
              this.initRectifyRate('down', data[params.dataIndex].code)
            })
          }
          this.chart2 = myChart
        })
        .finally(() => {
          this.isshowLoading2 = false
        })
    },
    initProblemSummary(type) {
      this.isshowLoading3 = true
      // questionNatureStatistics
      AuditRiskbraryService.questionNatureStatistics(this.getSearchData('bar'))
        .then((res) => {
          const list = res.data.data
          // 如果没有数据则

          // 总数
          const sum = list.reduce((prev, cur) => {
            return prev + cur.count
          }, 0)
          // 计算占比
          const data = list.map((item) => {
            return {
              value: ((item.count / sum) * 100).toFixed(2),
              name: item.questionNature,
            }
          })
          if (data.length === 0) {
            this.barishow1 = false
          }
          const myChart = echarts.init(document.getElementById('problemSummary'))
          const option = {
            tooltip: {
              trigger: 'item',
              formatter: '{a} <br/>{b} : {c} ({d}%)',
            },
            series: [
              {
                name: '问题概括统计',
                type: 'pie',
                radius: '55%',
                center: ['50%', '45%'],
                data: data,
                label: {
                  formatter: `{b}
                {d}%`,
                },
                itemStyle: {
                  normal: {
                    color: function(params) {
                      // 自定义颜色
                      var colorList = [
                        '#fc8251',
                        '#5470c6',
                        '#9A60B4',
                        '#ef6567',
                        '#f9c956',
                        '#3BA272',
                      ]
                      return colorList[params.dataIndex]
                    },
                  },
                },
              },
            ],
          }
          myChart.setOption(option)
          this.chart3 = myChart
        })
        .finally(() => {
          this.isshowLoading3 = false
        })
    },
    initModelField() {
      this.isshowLoading4 = true
      AuditRiskbraryService.modelDomainStatistics(this.getSearchData('bar'))
        .then((res) => {
          const list = res.data.data
          // 总数
          const sum = list.reduce((prev, cur) => {
            return prev + cur.count
          }, 0)
          // 计算占比
          const data = list.map((item) => {
            return {
              value: ((item.count / sum) * 100).toFixed(2),
              name: item.domainName,
            }
          })
          if (data.length === 0) {
            this.barishow2 = false
          }
          const myChart = echarts.init(document.getElementById('modelField'))
          const option = {
            tooltip: {
              trigger: 'item',
              formatter: '{a} <br/>{b} : {d}%',
            },

            series: [
              {
                name: '模型领域统计',
                type: 'pie',
                radius: '55%',
                center: ['50%', '45%'],
                data: data,
                itemStyle: {
                  normal: {
                    color: function(params) {
                      // 自定义颜色
                      var colorList = [
                        '#fc8251',
                        '#5470c6',
                        '#9A60B4',
                        '#ef6567',
                        '#f9c956',
                        '#3BA272',
                      ]
                      return colorList[params.dataIndex]
                    },
                  },
                },
                label: {
                  formatter: `{b}
                {d}%`,
                },
              },
            ],
          }
          myChart.setOption(option)
          this.chart4 = myChart
        })
        .finally(() => {
          this.isshowLoading4 = false
        })
    },
    // 饼图导出
    exportPie1(type) {
      this.isshowLoading5 = true
      const params = this.getSearchData('bar')
      AuditRiskbraryService.exportBoardBar(params)
        .then((res) => {
          if (res.status === 200) {
            const url = URL.createObjectURL(res.data)
            const filename = res.headers['content-disposition']
            const fname = filename.substring(filename.indexOf('filename=') + 9, filename.length)
            download(url, decodeURI(fname))
            // 导出成功
            message.success('导出成功')
          } else {
            Modal.warning({
              title: '提示',
              content: '导出报错，请联系管理员!',
            })
            return false
          }
        })
        .finally(() => {
          this.isshowLoading5 = false
        })
    },
    exportPie2(type) {
      this.isshowLoading5 = true
      const params = this.getSearchData('bar')
      AuditRiskbraryService.exportBoardBarModel(params)
        .then((res) => {
          if (res.status === 200) {
            const url = URL.createObjectURL(res.data)
            const filename = res.headers['content-disposition']
            const fname = filename.substring(filename.indexOf('filename=') + 9, filename.length)
            download(url, decodeURI(fname))
            // 导出成功
            message.success('导出成功')
          } else {
            Modal.warning({
              title: '提示',
              content: '导出报错，请联系管理员!',
            })
            return false
          }
        })
        .finally(() => {
          this.isshowLoading5 = false
        })
    },
    exportBar() {
      this.isshowLoading5 = true
      const params = this.getSearchData('line')
      AuditRiskbraryService.reformRateExport(params)
        .then((res) => {
          if (res.status === 200) {
            const url = URL.createObjectURL(res.data)
            const filename = res.headers['content-disposition']
            const fname = filename.substring(filename.indexOf('filename=') + 9, filename.length)
            download(url, decodeURI(fname))
            // 导出成功
            message.success('导出成功')
          } else {
            Modal.warning({
              title: '提示',
              content: '导出报错，请联系管理员!',
            })
            return false
          }
        })
        .finally(() => {
          this.isshowLoading5 = false
        })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.title {
  margin-bottom: 20px;
}
.linebar {
  width: 100%;
  height: 650px;
  margin-top: 20px;
}
.rectify-rate {
  width: 100%;
  height: 600px;
  margin-top: 20px;
}
.bingtu {
  width: 100%;
  height: 400px;
  margin-top: 20px;
}
.time {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.line-bar-body {
}

.form-bar {
  :global {
    .ant-form-item-control-wrapper {
      width: 200px;
    }
  }
}
.search-btn {
  margin-bottom: 20px;
}
.export-body {
  position: relative;
  .export-icon {
    position: absolute;
    top: 25px;
    right: 10%;
    z-index: 1;
    cursor: pointer;
  }
}
.riskviewtitle {
  // 左侧有竖线
  position: relative;
  padding-left: 15px;
  margin-bottom: 15px;
  font-weight: 800px;
}
.riskviewtitle::before {
  position: absolute;
  top: 50%; /* 竖线垂直居中 */
  left: 0;
  width: 4px; /* 竖线宽度 */
  height: 80%; /* 高度与容器高度相同 */
  content: ''; /* 伪元素需要content属性 */
  background: #1890ff; /* 竖线颜色 */
  border-radius: 10px;
  transform: translateY(-50%); /* 对齐调整 */
}
</style>
