<template>
  <a-spin :spinning="isshowLoading" tip="正在导出请稍等……" size="large">
    <div :class="$style.title">
      <a-form-model layout="inline">
        <a-form-model-item>
          <div style="width: 500px">
            <a-row>
              <a-col :span="6" style="padding-top: 2px">
                <a-select v-model="searchForm.unitType">
                  <a-select-option key="0" value="0">审计单位</a-select-option>
                  <a-select-option key="1" value="1">被审计单位</a-select-option>
                </a-select>
              </a-col>
              <a-col :span="18">
                <audit-two-unit
                  ref="cRelSelect"
                  v-model="companyUnit"
                  :single="true"
                  :root-node="userNodeTree"
                  @change="changecompany"
                />
              </a-col>
            </a-row>
          </div>
        </a-form-model-item>
        <a-form-model-item label="年份">
          <div style="width:240px">
            <AuditYearTime v-model="searchForm.year" select-type="mode" />
          </div>
        </a-form-model-item>
        <a-form-model-item>
          <a-button type="primary" @click="searchData">查询</a-button>
        </a-form-model-item>
      </a-form-model>
      <a-divider></a-divider>
      <a-spin :spinning="scatterLoading && barLoading" tip="正在加载请稍等……" size="large">
        <div :class="$style.contentView">
          <div :class="[$style.viewBody, $style.viewBodySmall]">
            <div :class="$style.contentTitle">审计开展次数</div>

            <div :class="$style.numberofissues">
              <!-- 头部信息 -->
              <div :class="$style.auditsum">
                <span>
                  审计开展总次数：
                </span>
                <span>
                  {{ totalAudit }}
                </span>
              </div>
              <!-- 总推送数量，问题数，非问题数 已整改数 未整改数 -->
              <div :class="$style.auditlist">
                <div v-for="(item, i) in sumList" :key="i" :class="$style.audititem">
                  <span>{{ item.name }}：</span>
                  <span>{{ item.value }}</span>
                </div>
              </div>
            </div>
            <!--  -->
          </div>
          <div :class="[$style.viewBody]">
            <div :class="$style.contentTitle">审计发现问题</div>
            <div :class="$style.searchselect">
              <audit-project-select
                v-model="searchForm.projdectList1"
                :options="projectOption"
                :field="{ key: 'id', name: 'name' }"
                @change="changeProjdectList1"
              />
            </div>
            <div v-if="isshowbar" id="bar" :class="$style.bar"></div>
            <a-empty
              v-else
              style="height: 400px;
    line-height: 400px;"
            />
            <div :class="$style.download" @click="downLoadTableBar">
              <a-icon type="vertical-align-bottom" :style="{ fontSize: '20px' }" />
            </div>
          </div>
        </div>
        <div :class="[$style.contentView, $style.contentmargin]">
          <div :class="[$style.viewBody, $style.viewBodySmall, $style.tablecontent]">
            <div :class="$style.contentTitle">整改情况</div>
            <h3>审计问题数量top20：</h3>
            <div :class="$style.searchselect2">
              <audit-project-select
                v-model="searchForm.projdectList2"
                :options="projectOption"
                :field="{ key: 'id', name: 'name' }"
                @change="changeProjdectList2"
              />
            </div>
            <sd-table
              :data-source="tableData1"
              :columns="column1"
              :scroll="{ y: tablHeight }"
              :loading="loadingTable1"
              :row-key="(row, i) => i"
              :pagination="false"
            ></sd-table>
          </div>
          <div ref="tableHeight" :class="[$style.viewBody]">
            <div :class="$style.contentTitle">风险分布</div>
            <div :class="$style.searchselect">
              <audit-project-select
                v-model="searchForm.projdectList3"
                :options="projectOption"
                :field="{ key: 'id', name: 'name' }"
                @change="changeProjdectList3"
              />
            </div>
            <div v-if="isshowscatter" id="scatter" :class="$style.scatter"></div>
            <a-empty
              v-else
              style="height: 400px;
    line-height: 400px;"
            />
          </div>
          <div :class="$style.download" @click="downLoadTableScatter">
            <a-icon type="vertical-align-bottom" :style="{ fontSize: '20px' }" />
          </div>
        </div>
      </a-spin>
    </div>
  </a-spin>
</template>

<script>
import components from './_import-components/audit-supervise-view-import'
import auditTwoUnit from './audit-two-unit.vue'
import auditProjectSelect from './audit-project-select.vue'
import AuditRiskbraryService from './riskLibrary'
import DataService from '../dataUphold/data-config'
import { getUserInfo } from '@/common/store-mixin'
import echarts from 'echarts'
import AuditYearTime from '../portrait/audit-year-time.vue'
import download from '@/common/services/download'
import { message, Modal } from 'ant-design-vue'
export default {
  name: 'AuditSuperviseView',
  metaInfo: {
    title: '审计监督画像',
  },
  components: {
    ...components,
    auditTwoUnit,
    AuditYearTime,
    auditProjectSelect,
  },
  data() {
    return {
      searchForm: {
        projdectList1: [],
        projdectList2: [],
        projdectList3: [],
        // 单位
        unitName: '',
        unitCode: '',
        unitType: '0',
        year: [],
      },
      userNodeTree: [],
      projectOption: [],
      // 公司
      companyUnit: [],
      auditsum: 0,
      totalAudit: 0,
      sumList: [],
      barLoading: false,
      isshowbar: false,
      isshowscatter: false,
      scatterLoading: false,
      isshowLoading: false,
      // 下钻领域
      drillDomain: '',
      // 下钻数据
      // 领域
      domainData: [],
      // 阶段
      purchaseData: [],
      barData: [],
      statusData: [],
      // 散点图数据
      scatterList: [],
      echartsBar: null,
      echartsScatter: null,
      tableData1: [],
      tableData2: [],
      loadingTable1: false,
      loadingTable2: false,
      column1: [
        {
          title: '序号',
          dataIndex: 'id',
          width: '80px',
        },
        {
          title: '单位名称',
          dataIndex: 'unitName',
          width: '140px',
          // 溢出隐藏
          ellipsis: true,
        },
        {
          title: '审计问题数量',
          dataIndex: 'count',
          // 超出隐藏
        },
        {
          title: '整改完成率',
          dataIndex: 'reformRate',
        },
      ],

      tablHeight: 0,
      isJt: false,
    }
  },
  created() {},
  mounted() {
    this.tablHeight = this.$refs.tableHeight.clientHeight - 170
    this.searchForm.year = [2020, 2021, 2022]
    this.initUserCompany()
  },
  methods: {
    // 初始化个人公司
    initUserCompany() {
      const userInfo = getUserInfo()
      DataService.getCompany(userInfo.account).then((res) => {
        // 100000和100001
        const roleCompany = ['100000', '100001']

        this.userNodeTree.push({
          code: res.data.id,
          name: res.data.name,
          orgCode: res.data.code,

          type: 'Group',
        })
        this.companyUnit = [
          {
            code: res.data.id,
            name: res.data.name,
            orgCode: res.data.code,
          },
        ]
        if (roleCompany.includes(res.data.code)) {
          this.isJt = true
          this.userNodeTree = [
            {
              code: '28951',
              name: '国家电力投资集团有限公司',
              orgCode: '100000',
            },
          ]
          this.companyUnit = [
            {
              code: '28951',
              name: '国家电力投资集团有限公司',
              orgCode: '100000',
            },
          ]
        }
        this.searchForm.unitName = this.companyUnit[0].name
        this.searchForm.unitCode = this.companyUnit[0].orgCode
        // 调用接口
        this.initProjectData()
      })
    },
    // 获取项目信息
    initProjectData() {
      const data = {
        columns: 'keyId,id,index,name',
        maxResults: 9999,
        startPosition: 0,
        orderBy: 'keyId asc,index asc',
        expressions: [
          { dataType: 'long', name: 'belongOrgId', op: 'eq', longValue: '-1' },
          { dataType: 'str', name: 'keyId', op: 'eq', stringValue: 'CPRODUCT_IAM_AUDIT_TYPE' },
        ],
        buttonExpressions: [],
      }
      AuditRiskbraryService.getProject(data).then((res) => {
        res.data.data.forEach((item) => {
          item.id = item.id.replace('C', '')
        })
        this.projectOption = res.data.data
        console.log(this.projectOption)
        this.sumList = this.projectOption.map((item) => {
          return {
            name: item.name,
            key: item.id,
            value: 0,
          }
        })
        // 默认选择第一个领域
        this.searchForm.projdectList1 = this.projectOption.map((val) => val.id)
        this.searchForm.projdectList2 = this.projectOption.map((val) => val.id)
        this.searchForm.projdectList3 = this.projectOption.map((val) => val.id)
        // 调用查询问题推送数量接口
        this.getSumData()
        // 审计发现问题
        this.initBarData()
        this.initScatterData()
        this.initTable()
      })
    },

    // 查询问题推送数量
    getSumData() {
      this.scatterLoading = true
      AuditRiskbraryService.countStatistics(this.searchParams('list'))
        .then((res) => {
          const data = res.data
          this.totalAudit = data.total || 0
          // 如果data的key和sumList的key相同，就赋值
          this.sumList.forEach((item) => {
            data.auditTypeBeanList.forEach((val) => {
              if (item.key === val.auditType) {
                item.value = val.count
              }
            })
          })
        })
        .finally(() => {
          this.scatterLoading = false
        })
    },
    changecompany(data) {
      this.searchForm.unitName = data[0]?.name || ''
      this.searchForm.unitCode = data[0]?.orgCode || ''
    },
    // 获取数据
    searchParams(type) {
      // 如果包含领域，如果包含下钻
      const params = {}
      // 年份
      params.unitType = this.searchForm.unitType
      params.unitCode = this.searchForm.unitCode
      if (type === 'bar') {
        // 遍历去除C
        params.auditTypes = this.searchForm.projdectList1.map((item) => item)

        // 项目列表
      }
      if (type === 'scatter') {
        // 散点图
        params.auditTypes = this.searchForm.projdectList3.map((item) => item)
      }
      if (type === 'table') {
        // 表格
        params.auditTypes = this.searchForm.projdectList2.map((item) => item)
      }

      // 开始年份结束年份
      // 对年份进行排序
      const yearList = this.searchForm.year.sort((a, b) => a - b)
      params.yearSt = yearList[0] + ''
      params.yearEd = yearList[this.searchForm.year.length - 1] + ''
      return params
    },
    searchData() {
      // 最少选择一个年份
      // 请选择开始年份和结束年份
      if (this.searchForm.year.length === 0) {
        message.warn('请选择开始年份和结束年份')
      }
      this.getSumData()
      this.initBarData()
      this.initTable()
      this.initScatterData()
    },
    // 获取饼图数据
    // 初始化 ，领域分布 ，阶段分布
    initBarData() {
      // 外层
      this.barLoading = true
      AuditRiskbraryService.questionStatistics(this.searchParams('bar')).then((res) => {
        this.isshowbar = res.data.length !== 0
        this.barLoading = false
        this.barData = res.data
        // 根据年份进行排序
        this.barData.sort((a, b) => a.planYear * 1 - b.planYear * 1)
        // 遍历数据，给所有项目插入name
        this.barData.forEach((item) => {
          this.projectOption.map((val1) => {
            if (item.auditType === val1.id) {
              item.name = val1.name
            }
          })
        })
        this.$nextTick(() => {
          this.initBar()
        })
      })
    },
    // 初始化柱图
    initBar() {
      const bar = document.getElementById('bar')

      this.echartsBar = echarts.init(bar)
      // 所有的项目key
      const allKey = this.barData.map((item) => item.auditType)

      const proKeylist = Array.from(new Set(allKey))
      // 判断有哪些年份
      let years = this.barData.map((item) => item.planYear)
      // 去重年份
      years = Array.from(new Set(years)).sort((a, b) => a - b)

      // 按照项目顺序获取所有的name
      const names = []
      proKeylist.map((val) => {
        this.projectOption.map((item) => {
          if (val === item.id) {
            names.push(item.name)
          }
        })
      })
      // 按照年份，项目顺序，生成数据
      // [
      //   {
      //     year: 2020,
      //     data: [
      //       { name: '项目1', count: 10 },
      //       { name: '项目2', count: 20 },
      //       { name: '项目3', count: 30 },
      //     ],
      //   }
      // ]
      const data = years.map((year) => {
        const obj = {
          year,
          data: proKeylist.map((val) => {
            // 如有年份和类型一样的则插入对象
            let dataList = 0
            const findData = this.barData.find(
              (item) => item.auditType === val && year === item.planYear
            )
            if (findData) {
              dataList = findData.count
            }
            return dataList
          }),
        }
        return obj
      })
      // 生成数据
      // 根据年生成
      const series = data.map((item, index) => {
        return {
          name: item.year,
          type: 'bar',
          barWidth: 25,
          label: { show: true, position: 'top' },
          data: item.data,
        }
      })

      this.echartsBar.clear()

      const color = ['#5b9bd5', '#ed7d31', '#a5a5a5']

      const option = {
        color,
        legend: {
          data: years,
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
          },
        },
        grid: {
          bottom: '10%',
          containLabel: true,
        },
        xAxis: {
          type: 'category',
          data: names,
          // 旋转角度
          axisLabel: {
            rotate: 45,
          },
        },
        dataZoom: [
          {
            type: 'slider',
            show: true,
            xAxisIndex: [0],
            start: 0,
            end: 60,
          },
        ],

        yAxis: [
          {
            type: 'value',
          },
        ],
        series: series,
      }
      this.echartsBar.setOption(option)
      // 监听外圈点击事件
      window.addEventListener('resize', () => {
        this.echartsBar.resize()
      })
    },
    // 初始化风险分布
    initScatterData() {
      this.scatterLoading = true
      AuditRiskbraryService.getRiskStatistics(this.searchParams('scatter'))
        .then((res) => {
          this.scatterList = res.data
          // 根据id添加名字
          this.scatterList.forEach((item) => {
            this.projectOption.map((val) => {
              if (item.auditType === val.id) {
                item.name = val.name || ''
              }
            })
          })
          //
          this.isshowscatter = this.scatterList.length !== 0
          this.$nextTick(() => {
            this.initScatter()
          })
        })
        .finally(() => {
          this.scatterLoading = false
        })
    },
    // 初始化散点图
    initScatter() {
      const scatter = document.getElementById('scatter')
      this.echartsScatter = echarts.init(scatter)
      this.echartsScatter.clear()
      const scatterData = this.scatterList.map((item) => {
        return [item.amount, item.count, item.name]
      })
      const legendData = scatterData.map((item) => item[2])
      const option = {
        xAxis: {
          // 问题金额
          name: '问题金额',
        },
        yAxis: {
          // 问题数量
          name: '问题数量',
        },
        legend: {
          type: 'scroll',
          orient: 'vertical', // 图例列表的布局朝向（垂直排列）
          right: 0,
          height: '80%',
          y: 'center',
          data: legendData,
          bottom: 10,
          itemGap: 15, // 图例的上下间距
          itemWidth: 10, // 图例左侧图块的长度
          padding: 5,
          textStyle: {
            fontSize: 16,
            fontWeight: 400,
            color: '#33333',
          },
          pageTextStyle: {
            // 设置分页的当前页与总页码的文本样式
            color: 'rgba(36, 196, 221, 0.95)',
          },
          pageIconColor: '#6495ed', // 翻页下一页的三角按钮颜色
          pageIconInactiveColor: '#aaa', // 翻页（即翻页到头时）
          pageIconSize: 20, // 翻页按钮大小
          pageButtonGap: 22, // 翻页按钮与图例的间距
          formatter: function(name) {
            // 截取字符串八个
            return name.length > 8 ? name.substring(0, 8) + '...' : name
          },
        },
        grid: {
          left: '10%',
          right: 200,
        },
        // 显示to
        tooltip: {
          formatter: function(data) {
            return `${data.seriesName}<br/>问题金额：${data.data[0]}<br/>问题数量：${data.data[1]}`
          },
        },
        color: ['#fac858', '#5470c6', '#91cc75', '#fac858', '#ee6666'],
        series: scatterData.map((item) => {
          return {
            name: item[2],
            data: [item],
            type: 'scatter',
            symbolSize: 30,
            label: {
              emphasis: {
                show: true,
                formatter: function(param) {
                  return param.seriesName
                },
                position: 'top',
              },
            },
          }
        }),
      }

      this.echartsScatter.setOption(option)
      // 监听页面尺寸变化
      window.addEventListener('resize', () => {
        this.echartsScatter.resize()
      })
    },
    // 初始化表格
    initTable() {
      this.loadingTable1 = true
      this.loadingTable2 = true
      AuditRiskbraryService.getReformStatistics(this.searchParams('table'))
        .then((res) => {
          this.tableData1 = res.data.map((item, index) => {
            const reformRate = item.reformRate
            const reformRateNum = Number(reformRate.replace('%', ''))
            item.reformRate = reformRateNum.toFixed(2) + '%'
            return {
              ...item,
              id: index + 1,
            }
          })
        })
        .finally(() => {
          this.loadingTable1 = false
        })
    },
    changeProjdectList1() {
      this.initBarData()
    },
    changeProjdectList2() {
      this.initTable()
    },
    changeProjdectList3() {
      this.initScatterData()
    },
    // downLoad
    downLoadTableBar() {
      this.isshowLoading = true
      AuditRiskbraryService.exportquestionExport(this.searchParams('bar'))
        .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.isshowLoading = false
        })
    },
    downLoadTableScatter() {
      this.isshowLoading = true
      AuditRiskbraryService.exportriskExport(this.searchParams('scatter'))
        .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.isshowLoading = false
        })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.title {
  min-height: 100%;
  padding: 20px;
  background: #fff;
}
::v-deep .ant-card-body {
  height: 100%;
}
.content-view {
  display: flex;
  justify-content: space-between;
  height: calc(100% - 70px);
}
.view-body {
  position: relative;
  // flex: 1;
  width: 68%;
  height: 500px;
  border: 1px solid #0086d6;
  border-radius: 10px;

  // title居中浮动
  .content-title {
    position: absolute;
    top: -20px;
    left: calc(50% - 75px);
    width: 150px;
    height: 40px;
    font-size: 18px;
    font-weight: 600;
    line-height: 40px;
    color: #fff;
    text-align: center;
    background: #02a7f0;
    border-radius: 5px;
  }
  .searchform {
    padding: 25px 0 10px 15px;
  }
}
.view-body-big {
  width: 100%;
  margin-top: 50px;
  .content-title {
    left: calc(50% - 140px);
    width: 280px;
  }
}
.view-body-small {
  width: 30%;
  margin-right: 2%;
}
.numberofissues {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  width: 90%;
  height: calc(100% - 50px);
  padding-top: 20px;
  margin: 10px auto;
  .auditsum {
    position: relative;
    width: 100%;
    height: 80px;
    font-weight: 600;
    color: #fff;
    text-align: center;
    background-color: #1c375e;
    border-radius: 10px;
    // 第一个span左上，第二个span中间
    span:nth-child(1) {
      position: absolute;
      top: 0;
      left: 5px;
      font-size: 20px;
      color: #fff;
    }
    span:nth-child(2) {
      position: absolute;
      top: 50%;
      left: 50%;
      font-size: 20px;
      transform: translate(-50%, -50%);
    }
  }
  // 分成两列 单数f2f2f2 双数045679
  .auditlist {
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
    width: 100%;
    height: calc(100% - 80px);
    margin-top: 20px;
    overflow-y: scroll;
    .audititem {
      position: relative;
      width: 48%;
      height: 20%;
      min-height: 40px;
      margin: 0 1% 10px 1%;
      border-radius: 10px;

      span:nth-child(1) {
        position: absolute;
        top: 5px;
        left: 10px;
        font-size: 16px;
      }
      span:nth-child(2) {
        position: absolute;
        top: 60%;
        left: 50%;
        font-size: 16px;
        transform: translate(-50%, -50%);
      }
      &:nth-child(4n + 1),
      &:nth-child(4n + 4) {
        color: #333;
        background-color: #f2f2f2;
      }
      &:nth-child(4n + 2),
      &:nth-child(4n + 3) {
        color: #fff;
        background-color: #045679;
      }
    }
  }
}
.bar,
.scatter {
  width: 100%;
  height: calc(100% - 60px);
  margin-top: 40px;
}

// 右上角
.download {
  position: absolute;
  top: 15px;
  right: 10px;
  z-index: 1;
  cursor: pointer;
}
.contentmargin {
  position: relative;
  margin-top: 50px;
}
.tablecontent {
  padding: 10px;
  padding-top: 20px;
}
// 筛选框宽度240px
.searchselect {
  position: absolute;
  // 右上角
  top: 10px;
  right: 40px;
  width: 240px;
}
.searchselect2 {
  position: absolute;
  // 右上角
  top: 25px;
  right: 10px;
  width: 240px;
}
</style>
