<template>
  <a-spin :spinning="isshowLoading" tip="正在导出请稍等……" size="large">
    <div :class="$style.title">
      <a-form-model layout="inline">
        <a-form-model-item label="单位:">
          <div style="width: 300px">
            <SdGroupPicker
              ref="cRelSelect"
              v-model="companyUnit"
              :single="true"
              :root-node="userNodeTree"
              @change="changecompany"
            />
          </div>
        </a-form-model-item>
        <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">
                <a-range-picker v-model="searchForm.timeArr" />
              </a-col>
            </a-row>
          </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="pieLoading" tip="正在加载请稍等……" size="large">
        <div :class="$style.contentView">
          <div :class="[$style.viewBody, $style.viewBodySmall]">
            <div :class="$style.contentTitle">问题推送数量</div>
            <a-form-model layout="inline" :class="$style.searchform">
              <a-form-model-item label="业务领域:">
                <div style="width: 300px">
                  <!-- 多选 -->
                  <a-select
                    v-model="searchForm.area"
                    mode="multiple"
                    :max-tag-count="2"
                    @change="areaChange"
                  >
                    <template slot="maxTagPlaceholder">
                      ...
                    </template>
                    <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>
            <!--  -->
            <div :class="$style.numberofissues">
              <!-- 总推送数量，问题数，非问题数 已整改数 未整改数 -->
              <div v-for="(item, i) in sumList" :key="i">{{ item.name }}：{{ item.value }}</div>
            </div>
            <!--  -->
          </div>
          <div :class="[$style.viewBody]">
            <div :class="$style.contentTitle">问题领域分布</div>
            <div v-if="isshowpie" id="pie" :class="$style.pie"></div>
            <a-empty
              v-else
              style="height: 400px;
    line-height: 400px;"
            />
          </div>
        </div>
      </a-spin>
      <a-spin :spinning="scatterLoading" tip="正在加载请稍等……" size="large">
        <div :class="[$style.viewBody, $style.viewBodyBig]">
          <div :class="$style.contentTitle">责任人分析</div>
          <div id="scatter" :class="$style.scatter"></div>
        </div>
      </a-spin>
      <!-- 审计问题推送及整改率情况对标 -->
      <div :class="[$style.viewBody, $style.viewBodyBig]">
        <div :class="$style.contentTitle">审计问题推送及整改率情况对标</div>
        <div :class="$style.table">
          <div ref="tableHeight" :class="$style.tableone">
            <h1 :class="$style.tabletitle">疑点问题排名</h1>
            <sd-table
              :row-key="(row) => row.id"
              :scroll="{ y: tablHeight }"
              :columns="column1"
              :loading="loadingTable1"
              :data-source="tableData1"
              :pagination="false"
            ></sd-table>
          </div>
          <div :class="$style.tableone">
            <h1 :class="$style.tabletitle">整改率排名</h1>
            <sd-table
              :row-key="(row) => row.id"
              :scroll="{ y: tablHeight }"
              :loading="loadingTable2"
              :columns="column2"
              :data-source="tableData2"
              :pagination="false"
            ></sd-table>
          </div>
        </div>
        <!-- 下载按钮 -->
        <div :class="$style.download" @click="downLoadTable">
          <a-icon type="vertical-align-bottom" :style="{ fontSize: '18px' }" />
        </div>
      </div>
    </div>
  </a-spin>
</template>

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

export default {
  name: 'AuditProcessRisk',
  metaInfo: {
    title: 'AuditProcessRisk',
  },
  components: {
    ...components,
    SdGroupPicker,
  },
  data() {
    return {
      searchForm: {
        area: [],
        // 推送日期
        pushDataSd: '',
        pushDataEd: '',
        // 业务日期
        timeArr: [],
        // 单位
        unitName: '',
        unitCode: '',
        timeType: '1',
      },
      areaOption: [],
      companyUnit: [],
      userNodeTree: [],
      isshowLoading: false,
      sumList: [
        {
          name: '总推送数',
          value: 0,
          key: 'total',
        },
        {
          name: '问题数',
          value: 0,
          key: 'questionNum',
        },
        {
          name: '非问题数',
          value: 0,
          key: 'nonQuestionNum',
        },
        {
          name: '已整改数',
          value: 0,
          key: 'reformNum',
        },
        {
          name: '未整改数',
          value: 0,
          key: 'nonReformNum',
        },
      ],
      pieLoading: false,
      isshowpie: false,
      listLoading: false,
      scatterLoading: false,
      // 下钻领域
      drillDomain: '',
      // 下钻数据
      // 领域
      domainData: [],
      // 阶段
      purchaseData: [],
      statusData: [],
      echartsPie: null,
      echartsScatter: null,
      tableData1: [],
      tableData2: [],
      loadingTable1: false,
      loadingTable2: false,
      //       //单位编码
      // private String unitCode;

      // //单位名称
      // private String unitName;

      // //问题数量
      // private Integer count;

      // //整改率
      // private String reformRate;
      column1: [
        {
          title: '序号',
          dataIndex: 'id',
          width: '80px',
        },
        {
          title: '单位编码',
          dataIndex: 'unitCode',
          width: '100px',
        },
        {
          title: '单位名称',
          dataIndex: 'unitName',
          // 超出隐藏
          ellipsis: true,
        },
        {
          title: '疑点问题数量',
          dataIndex: 'count',
          width: '140px',
        },
      ],
      column2: [
        {
          title: '序号',
          dataIndex: 'id',
          width: '80px',
        },
        {
          title: '单位编码',
          dataIndex: 'unitCode',
          width: '100px',
        },
        {
          title: '单位名称',
          dataIndex: 'unitName',
          ellipsis: true,
        },
        {
          title: '整改率',
          dataIndex: 'reformRate',
          width: '100px',
        },
      ],
      tablHeight: 0,
      isJt: false,
      scatterData: [],
    }
  },
  created() {
    this.initUserCompanyRole()
  },
  mounted() {
    this.tablHeight = this.$refs.tableHeight.clientHeight - 130
  },
  methods: {
    // 初始化， 获取当前人群的权限，
    initUserCompanyRole() {
      // 初始化时间
      this.searchForm.timeArr = [moment().startOf('year'), moment()]

      const userInfo = getUserInfo()
      DataService.getCompany(userInfo.account).then((res) => {
        // 100000和100001
        const roleCompany = ['100000', '100001']

        this.userNodeTree = [
          {
            code: res.data.id,
            name: res.data.name,
            orgCode: res.data.code,
          },
        ]
        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.initAreaData()
        this.initPieData()
        this.initTable()
        this.getScatterData()
      })
    },
    // 获取领域信息
    initAreaData() {
      auditMaintainService.getAreaListAll().then((res) => {
        this.areaOption = res.data
        // 默认选择第一个领域
        // 调用查询问题推送数量接口
        this.getSumData()
      })
    },
    // 领域变化
    areaChange(val) {
      // 根据val的值过滤选项
      this.getSumData()
    },
    // 查询问题推送数量
    getSumData() {
      this.listLoading = true
      AuditRiskbraryService.getCountStatistics(this.searchParams('area'))
        .then((res) => {
          const data = res.data

          // 如果data的key和sumList的key相同，就赋值
          this.sumList = this.sumList.map((item) => {
            return {
              ...item,
              value: data[item.key] || 0,
            }
          })
        })
        .finally(() => {
          this.listLoading = false
        })
    },
    changecompany(data) {
      this.searchForm.unitName = data[0]?.name || ''
      this.searchForm.unitCode = data[0]?.orgCode || ''
    },
    // 获取数据
    searchParams(type) {
      // 如果包含领域，如果包含下钻
      const params = {}
      // 时间类型
      let timeArr = this.searchForm.timeArr.map((item) => (item ? moment(item)._d.getTime() : ''))
      // 如果业务实践时间
      if (this.searchForm.timeType === '1') {
        timeArr = timeArr.map((item) => (item ? moment(item).format('YYYY-MM-DD') : ''))
        params.pushDateSt = timeArr[0]
        params.pushDateEd = timeArr[1]
      } else {
        //
        // 格式为年月日时分秒
        params.bussTimeSt = timeArr[0]
        params.bussTimeEd = timeArr[1]
      }
      params.unitCode = this.searchForm.unitCode
      if (type === 'area') {
        params.modelDomainList = this.searchForm.area
      }
      // 如果是下钻
      if (type === 'drill') {
        params.modelDomainId = this.drillDomain
      }
      return params
    },
    searchData() {
      this.getSumData()
      this.initPieData()
      this.getScatterData()
      this.initTable()
    },
    // 获取饼图数据
    // 初始化 ，领域分布 ，阶段分布
    initPieData() {
      // 外层
      this.pieLoading = true
      AuditRiskbraryService.getDomainDistribution(this.searchParams())
        .then((res1) => {
          // 内层
          AuditRiskbraryService.getStatusStatistics(this.searchParams()).then((res2) => {
            this.domainData = res1.data.data
            this.statusData = res2.data

            this.isshowpie = this.domainData.length !== 0
            this.$nextTick(() => {
              this.initPie()
            })
          })
        })
        .finally(() => {
          setTimeout(() => {
            this.pieLoading = false
          }, 60000)
        })
    },
    // 初始化饼图
    initPie() {
      const pie = document.getElementById('pie')

      this.echartsPie = echarts.init(pie)

      this.echartsPie.clear()

      const color = ['#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4']

      // //期限内已整改
      // private Integer status0;
      // //逾期已整改
      // private Integer status1;
      // //期限内未整改已完成
      // private Integer status2;
      // //逾期未整改完成
      // private Integer status3;
      const statusKey = [
        {
          name: '期限内已整改',
          key: 'status0',
        },
        {
          name: '逾期已整改',
          key: 'status1',
        },
        {
          name: '期限内未整改',
          key: 'status2',
        },
        {
          name: '逾期未整改',
          key: 'status3',
        },
      ]
      let inside = statusKey.map((item) => {
        return {
          name: item.name,
          value: this.statusData[item.key] || 0,
        }
      })
      // 过滤等于0的数据
      inside = inside.filter((item) => item.value !== 0)
      const outer = this.domainData.map((item) => {
        return {
          name: item.domainName,
          value: item.count,
          modelDomainId: item.modelDomainId,
        }
      })
      // 如果outer===0
      if (outer.length === 0) {
        this.pieLoading = false
        this.isshowpie = false
      }
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)',
        },
        color,
        legend: {
          data: [
            ...this.purchaseData.map((item) => item.modelPhaseName),
            ...this.domainData.map((item) => item.domainName),
          ],
        },
        series: [
          {
            name: '占比',
            type: 'pie',
            selectedMode: 'single',
            radius: [0, '30%'],
            label: {
              position: 'inner',
              fontSize: 14,
            },
            labelLine: {
              show: false,
            },
            // 饼图中心
            data: inside,
            itemStyle: {
              color: function(colos) {
                return colos.dataIndex === 1 ? '#91cc75' : '#5470c6'
              },
            },
          },
          {
            name: '占比',
            type: 'pie',
            radius: ['45%', '60%'],
            labelLine: {
              length: 30,
            },
            label: {
              formatter: '{a|{a}}{abg|}\n{hr|}\n  {b|{b}：}{c}  {per|{d}%}  ',
              backgroundColor: '#F6F8FC',
              borderColor: '#8C8D8E',
              borderWidth: 1,
              borderRadius: 4,
              rich: {
                a: {
                  color: '#6E7079',
                  lineHeight: 22,
                  align: 'center',
                },
                hr: {
                  borderColor: '#8C8D8E',
                  width: '100%',
                  borderWidth: 1,
                  height: 0,
                },
                b: {
                  color: '#4C5058',
                  fontSize: 14,
                  fontWeight: 'bold',
                  lineHeight: 33,
                },
                per: {
                  color: '#fff',
                  backgroundColor: '#4C5058',
                  padding: [3, 4],
                  borderRadius: 4,
                },
              },
            },
            data: outer,
            itemStyle: {},
          },
        ],
      }
      this.echartsPie.setOption(option)
      this.pieLoading = false

      // 监听外圈点击事件
      this.echartsPie.on('click', (params) => {
        this.drillDomain = params.data.modelDomainId
        if (this.drillDomain) {
          AuditRiskbraryService.getPhaseDistribution(this.searchParams('drill')).then((res) => {
            this.purchaseData = res.data.data
            this.echartsPie.clear()
            const that = this
            // 重新绘制 下钻
            const setOption = {
              legend: {
                top: 'bottom',
              },
              title: {
                text: params.data.name,
                left: 'center',
              },
              tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)',
              },
              graphic: [
                {
                  type: 'text',
                  left: 50,
                  top: 20,
                  style: {
                    text: '返回',
                    fontSize: 18,
                  },
                  onclick: function() {
                    that.echartsPie.clear()
                    that.initPie()
                  },
                },
              ],
              color: ['#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4'],
              series: [
                {
                  name: '问题个数',
                  type: 'pie',
                  radius: [20, 100],
                  center: ['50%', '50%'],
                  roseType: 'area',
                  itemStyle: {
                    borderRadius: 8,
                  },
                  data: this.purchaseData.map((item) => {
                    return {
                      value: item.count,
                      name: item.modelPhaseName,
                    }
                  }),
                },
              ],
            }
            this.echartsPie.setOption(setOption)
          })
        }
      })
      // 添加尺寸变化监听
      window.addEventListener('resize', () => {
        this.echartsPie.resize()
      })
    },
    // 初始化散点图数据
    getScatterData() {
      this.scatterLoading = true
      AuditRiskbraryService.getResPersonStatistics(this.searchParams())
        .then((res) => {
          this.scatterData = res.data.data
          this.initScatter()
        })
        .finally(() => {
          setTimeout(() => {
            this.scatterLoading = false
          }, 60000)
        })
    },
    // 初始化散点图
    initScatter() {
      const scatter = document.getElementById('scatter')
      this.echartsScatter = echarts.init(scatter)
      this.echartsScatter.clear()

      const legendData = this.scatterData.map((item) => item.modelName)
      const option = {
        color: [
          '#dd4444',
          '#fec42c',
          '#80F1BE',
          '#fac858',
          '#ee6666',
          '#73c0de',
          '#3ba272',
          '#fc8452',
          '#9a60b4',
        ],
        legend: {
          type: 'scroll',
          orient: 'vertical', // 图例列表的布局朝向（垂直排列）
          right: 0,
          height: '80%',
          data: legendData,
          y: 'center',
          bottom: 10,
          itemGap: 15, // 图例的上下间距
          itemWidth: 8, // 图例左侧图块的长度
          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: '5%',
          right: 300,
          top: '18%',
          bottom: '10%',
        },
        tooltip: {
          backgroundColor: 'rgba(255,255,255,0.1)',
          // 文字颜色
          textStyle: {
            color: '#33333',
          },
          formatter: function(param) {
            var value = param.data
            // prettier-ignore
            return '<div style="border-bottom: 1px solid rgba(255,255,255,0.1); font-size: 18px;padding-bottom: 7px;margin-bottom: 7px">'
                + param.seriesName + ''
                + '</div>'
                + '问题数量' + '：' + value[0] + '<br>'
                + '非问题数量' + '：' + value[1] + '<br>';
          },
        },
        xAxis: {
          type: 'value',
          name: '问题数量',
          nameGap: 16,
          // 最小步长
          minInterval: 1,
          nameTextStyle: {
            fontSize: 16,
          },
          splitLine: {
            show: false,
          },
        },
        yAxis: {
          type: 'value',
          name: '非问题数量',
          nameLocation: 'end',
          minInterval: 1,
          nameGap: 20,
          nameTextStyle: {
            fontSize: 16,
          },
          splitLine: {
            show: false,
          },
        },

        series: this.scatterData.map((item) => {
          // 分为三档
          // 大于10为15
          // 大于10020
          // 大于1000为25
          const symbolSize = item.questionNum > 1000 ? 50 : item.questionNum > 100 ? 40 : 30
          return {
            name: item.modelName,
            type: 'scatter',
            symbolSize: symbolSize,
            itemStyle: {
              opacity: 0.8,
            },
            data: [[item.questionNum, item.nonQuestionNum]],
          }
        }),
      }
      this.echartsScatter.setOption(option)
      this.scatterLoading = false

      window.addEventListener('resize', () => {
        this.echartsScatter.resize()
      })
    },
    // 初始化表格
    initTable() {
      this.loadingTable1 = true
      this.loadingTable2 = true
      AuditRiskbraryService.getQuestionNumRank(this.searchParams())
        .then((res) => {
          this.tableData1 = res.data.data.map((item, index) => {
            return {
              ...item,
              id: index + 1,
            }
          })
        })
        .finally(() => {
          this.loadingTable1 = false
        })
      AuditRiskbraryService.getReformRateRank(this.searchParams())
        .then((res) => {
          this.tableData2 = res.data.data.map((item, index) => {
            // reformRate: "0.08%" 如果超出两位小数则四舍五入
            const reformRate = item.reformRate
            const reformRateNum = Number(reformRate.replace('%', ''))
            item.reformRate = reformRateNum.toFixed(2) + '%'
            return {
              ...item,
              id: index + 1,
            }
          })
        })
        .finally(() => {
          this.loadingTable2 = false
        })
    },
    // downLoad
    downLoadTable() {
      this.isshowLoading = true
      AuditRiskbraryService.downLoadTwoTable(this.searchParams())
        .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%;
}
.scatter {
  width: 100%;
  height: 500px;
}
.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;
  }
  &:last-child .content-title {
    background-color: #0086d6;
  }
  .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%;
}
.time {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}
.numberofissues {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  width: 90%;
  height: calc(100% - 100px);
  margin: 10px auto;
  > div {
    width: 90%;
    height: 60px;
    font-weight: 600;
    line-height: 60px;
    color: #fff;
    text-align: center;
    background-color: #015478;
    border-radius: 10px;
  }
  :nth-child(1) {
    width: 100%;
    background-color: #1b365d;
  }
}
.pie {
  width: 100%;
  height: calc(100% - 60px);
  margin-top: 40px;
}
.table {
  display: flex;
  justify-content: space-between;
  height: 100%;
  padding: 20px;
  margin-top: 20px;

  .tableone {
    align-items: center;
    width: 48%;
    height: 95%;
    padding: 10px;
    background-color: #fff;
    border-radius: 10px;
    box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);
    .tabletitle {
      margin-bottom: 10px;
      font-size: 20px;
      font-weight: 600;
    }
  }
}
// 右上角
.download {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 1;
  cursor: pointer;
}
</style>
