<template>
  <div :class="$style.searchdiv">
    <a-card :class="$style.searchWrap">
      <a-form-model
        ref="advancedSearchForm"
        class="ant-advanced-search-form"
        :model="form"
        :rules="rules"
        v-bind="formItemLayout"
      >
        <a-row :gutter="24" :class="$style.antformitem">
          <a-col :span="8">
            <a-form-model-item label="年度" prop="timeRange">
              <AuditRangePicker v-model="form.timeRange" :time-range.sync="form.timeRange" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="机构" prop="unitNames">
              <audit-group-picker
                v-model="form.unitNames"
                :selectall="false"
                :top-node-text="'风控机构'"
                :root-node="{ code: JgId, name: orgName, id: JgId }"
                :treeparams="{
                  moduleId: 'iamOrg2',
                }"
                :single="true"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="16"> </a-col>
          <a-col :class="$style.searchbutton" :span="8">
            <div class="reportbuttonContent" style="margin-right:15%">
              <a-button @click="handleReset">重置</a-button>
              <a-button type="primary" html-type="submit" @click="submitForm">查询</a-button>

              <a-button type="primary" @click="exportData">导出</a-button>
            </div>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>
    <a-card class="reporttablecardxm">
      <span class="header_sd-header_common"
        ><span :class="['toptitle', $style.toptitle]">损失事件统计</span></span
      >
      <template v-if="total !== 0">
        <div>
          <sd-echart :key="optionkey" :class="$style.echarts" :options="option" autoresize
        /></div>
      </template>
      <div :class="[$style.btns]">
        <audit-advanced-export
          ref="Export"
          :class-style="[$style.buttonSpacing]"
          :exclebxh="false"
          :expressions="expressions"
          :config-id="241"
          :v-if="false"
        />
      </div>
      <div v-if="dataKeysum !== 0" id="hj" style="display:none">
        <sd-data-table-hj
          ref="dataTablehj"
          :key="dataKeysum"
          :process-req="processReqsum"
          :columns="columnssum"
          :projectlist="true"
          :defultpagination-pagesize="50"
          :data-url="dataUrl"
          @dataLoaded1="dataLoadedsum"
          @rowClick="rowClick"
        >
          <template slot="SUM1" slot-scope="text, record">
            <span v-if="text === '0' || text === 0">{{ text }}</span>
            <a v-else @click="rowClick(record, 1)">{{ text }}</a>
          </template>
          <template slot="SUM2" slot-scope="text, record">
            <span v-if="text === '0' || text === 0">{{ text }}</span>
            <a v-else @click="rowClick(record, 2)">{{ text }}</a>
          </template>
        </sd-data-table-hj>
      </div>
      <sd-data-table
        v-if="tableKey !== 0"
        :key="tableKey"
        ref="dataTable"
        class="findTable"
        :data-url="dataUrl"
        :columns="columns"
        :projectlist="true"
        :row-key="(record, index) => index"
        :process-req="processReq"
        :defultpagination-pagesize="50"
        @dataLoaded="dataLoaded"
        @rowClick="rowClick"
        @fnonloadsum="fnonloadsum"
      >
        <template slot="SUM1" slot-scope="text, record">
          <span v-if="text === '0' || text === 0">{{ text }}</span>
          <a v-else @click="rowClick(record, 1)">{{ text }}</a>
        </template>
        <template slot="SUM2" slot-scope="text, record">
          <span v-if="text === '0' || text === 0">{{ text }}</span>
          <a v-else @click="rowClick(record, 2)">{{ text }}</a>
        </template>
      </sd-data-table>
    </a-card>
  </div>
</template>

<script>
import 'echarts/lib/chart/treemap'
import 'echarts/lib/chart/pie'
import 'echarts/lib/chart/pictorialBar'
import 'echarts/lib/component/title'
import 'echarts/lib/chart/bar'
import 'echarts/lib/component/legend'
import 'echarts/lib/component/legendScroll'
import 'echarts/lib/component/tooltip'
import moment from 'moment'
import { Modal, message } from '@/common/one-ui'
import axios from '@/common/services/axios-instance'
import { getUserInfo } from '@/common/store-mixin'
import TableColumnTypes from '@/common/services/table-column-types'
import download from '@/common/services/download'
import AuditRangePicker from '@product/iam/components/picker/audit-range-picker.vue'
import auditGroupPicker from '@product/iam/components/picker/audit-group-picker.vue'
import auditAdvancedExport from '@product/iam/components/audit-advanced-export.vue'
import riskTasksService from '../task/risk-tasks-service'
import StatisticsService from './statistics-service'
import components from './_import-components/risk-loss-event-statistics-import'
const echarts = require('echarts/lib/echarts')
export default {
  name: 'RiskLossEventStatistics',
  metaInfo: {
    title: '损失事件统计',
  },
  components: {
    ...components,
    AuditRangePicker,
    auditGroupPicker,
    auditAdvancedExport,
  },
  data() {
    return {
      optionkey: 0,
      data: [],
      columns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '单位名称',
          dataIndex: 'unitName',
          width: '30%',
          sdHidden: false,
        },
        {
          title: '损失事件数量',
          dataIndex: 'num',
          width: '30%',
          sdHidden: false,
          scopedSlots: { customRender: 'number' },
          sdClickable: true,
        },
        {
          title: '占比',
          dataIndex: 'percent',
          width: '30%',
          sdHidden: false,
        },
      ],
      columnssum: [
        {
          title: '单位名称',
          dataIndex: 'unitName',
          width: '30%',
          sdHidden: false,
        },
        {
          title: '损失事件数量',
          dataIndex: 'num',
          width: '30%',
          sdHidden: false,
          scopedSlots: { customRender: 'number' },
          sdClickable: true,
        },
        {
          title: '占比',
          dataIndex: 'percent',
          width: '30%',
          sdHidden: false,
        },
      ],
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 14 },
      },
      dateFormat: 'YYYY',
      form: {
        unitNames: [],
        timeRange: [],
      },
      rules: {
        timeRange: [{ required: true, message: '请选择统计时间', trigger: 'change' }],
        unitNames: [{ required: true, message: '请选择审计机构', trigger: 'change' }],
      },
      params: {
        year: null,
        unitId: null,
      },
      flag: true,
      option: {},
      total: 0,
      tableKey: 0,
      dataKeysum: 0,
      hj: {},
      // hjarr: [],
      dataUrl: 'api/xcoa-mobile/v1/risk-statistics-analysis/lossEventStatistics?year=',
      expressions: [],
      orgName: '',
      orgId: '',
      JgId: '',
    }
  },
  created() {
    let userInfo = getUserInfo()
    this.orgName = userInfo.deptName
    const params = {
      orgId: userInfo.deptId,
    }

    axios({
      url: 'api/xcoa-mobile/v1/iamorg/getCurrentUserGroup',
      method: 'get',
    }).then((res) => {
      userInfo = res.data
      this.orgId = res.data.id
      this.orgName = res.data.name
      this.JgId = res.data.id
      riskTasksService.findIamOrgId(res.data.id).then((res1) => {
        this.JgId = res1.data
        //   if (res.data) {
        // this.orgId = res.data
        this.form.unitNames = [
          {
            id: parseInt(this.JgId),
            text: this.orgName,
            name: this.orgName,
            title: this.orgName,
            code: this.JgId.toString(),
            oldId: this.JgId,
            type: 'Group',
          },
        ]
        //   }
      })
    })
  },
  methods: {
    dataLoaded(eventData) {
      if (this.flag) {
        return
      }
      this.total = eventData.data.length
      eventData.data.forEach((item, index) => {
        item.sortNum = index + 1
        item.id = index
      })
      const bar = {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#6ee394' },
          { offset: 0.5, color: '#5ac5c5' },
          { offset: 1, color: '#49adef' },
        ]),
        tooltip: {},
        xAxis: {
          type: 'category',
          data: eventData.data.map((d) => d.unitName),
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            type: 'bar',
            barWidth: 40, // 柱图宽度
            barMaxWidth: 40, // 最大宽度
            label: {
              show: true,
              position: 'top',
            },
            data: eventData.data.map((d) => d.num),
          },
        ],
      }
      this.option = bar
      this.optionkey++
      return eventData
    },
    dataLoadedsum(res) {
      if (res.data.length) {
        const obj = {}
        let num = 0
        res.data.forEach((d) => {
          num += d.num
        })
        obj.id = 1
        obj.unitName = '总计'
        obj.num = num
        obj.percent = '100%'
        res.data.splice(0, res.data.length)
        res.data.push(obj)
        return res
      }
    },
    fnonloadsum() {
      if (this.flag) {
        document.querySelector('.findTable .ant-table-wrapper').style.display = 'none'
      } else {
        document.querySelector('.findTable .ant-table-wrapper').style.display = ''
      }
      setTimeout(() => {
        if (
          document
            .getElementById('hj')
            .getElementsByClassName('ant-table-tbody')[0]
            .getElementsByTagName('tr').length > 0
        ) {
          const obj = document.getElementById('hj').getElementsByClassName('ant-table-tbody')[0]
            .firstChild
          obj.firstChild.colSpan = 2
          obj.classList.add('childsum')
          document.getElementsByClassName('ant-table-tbody')[1].appendChild(obj)
        }
      }, 1000)
    },
    submitForm() {
      this.flag = false
      this.$refs.advancedSearchForm.validate((valid, values) => {
        if (valid) {
          const startYear = moment(this.form.timeRange[0]).format('YYYY')
          const endYear = moment(this.form.timeRange[1]).format('YYYY')
          this.params.year = startYear + '-' + endYear
          this.params.unitId = this.form.unitNames[0].id
          this.dataUrl =
            'api/xcoa-mobile/v1/risk-statistics-analysis/lossEventStatistics?year=' +
            startYear +
            '-' +
            endYear +
            '&unitId=' +
            this.form.unitNames[0].id
          this.expressions.push({
            dataType: 'str',
            name: 'year',
            op: 'eq',
            stringValue: startYear + '-' + endYear,
          })
          this.expressions.push({
            dataType: 'long',
            name: 'unitId',
            op: 'eq',
            longValue: this.form.unitNames[0].id,
          })
          this.tableKey++
          this.dataKeysum++
        }
      })
    },
    processReq(req) {
      req.data = {
        year: this.params.year,
        unitId: this.params.unitId,
      }
      return req
    },
    processReqsum(req, pagination) {
      req.data = {
        year: this.params.year,
        unitId: this.params.unitId,
      }
      return req
    },
    handleReset() {
      this.$refs.advancedSearchForm.resetFields()
      this.tableKey = 0
      this.total = 0
      this.dataKeysum = 0
    },
    // 导出接口
    exportData() {
      this.$refs.Export.exportdata()
    },
    rowClick(record, lb) {
      const param = {}
      if (record.unitName === '总计') {
        param.dateStart = moment(this.form.timeRange[0]).format('YYYY')
        param.dateEnd = moment(this.form.timeRange[1]).format('YYYY')
        param.fillingUnitId = this.form.unitNames[0].id
      } else {
        param.columnValue = record.unitId
        param.dateStart = moment(this.form.timeRange[0]).format('YYYY')
        param.dateEnd = moment(this.form.timeRange[1]).format('YYYY')
      }
      const url =
        '#/risk-loss-event-mxlist?params=' +
        encodeURIComponent(JSON.stringify(param)) +
        '&type=projectlist'
      window.open(url)
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.toptitle {
  color: #404040;
  font-weight: bold;
  font-size: 22px;
  margin-left: calc(50% - 150px);
}
.search-wrap {
  margin-bottom: $padding-lg;
  :global(.ant-advanced-search-form) {
    padding: 0;
    background: transparent;
    border: none;
  }
  :global .ant-divider-horizontal {
    margin: 10px 0;
  }
}
.searchdiv {
  background-color: #f0f2f5;
  height: 100%;
  :global(.sd-has-table.ant-card) {
    min-height: calc(100vh - 320px);
  }
  :global(.reporttablecardxm) {
    :global(.ant-table-body) {
      height: calc(100vh - 350px);
      overflow: auto;
    }
  }
}

.emptyecharts {
  width: 600px;
  height: 400px;
  margin: auto auto;
  text-align: center;
  &::after {
    content: '无数据';
    padding-top: 150px;
    display: block;
  }
}
.echarts {
  width: 100%;
  height: 400px;
  margin: auto auto;
  text-align: center;
}
.piespan {
  margin-left: -600px;
  position: relative;
  .cate {
    position: absolute;
    right: 300px;
    top: 30px;
    z-index: 5;
    // overflow: auto;
    // height: 250px;
    li {
      cursor: pointer;
      list-style: none;
      font-size: 13px;
      line-height: 23px;
      color: #919191;
      padding-left: 15px;
      position: relative;
    }
  }
}
.pdiv {
  height: 14px;
  width: 14px;
  background: #54c5eb;
  border-radius: 11px;
  position: absolute;
  left: -7px;
  top: 5px;
}
.cateli-span {
  color: #0162eb;
  display: inline-block;
  width: 180px;
}
.cateli-point {
  display: inline-block;
  width: 80px;
}
.backicon {
  position: absolute;
  top: 3px;
  left: 5px;
  cursor: pointer;
}
</style>
