<template>
  <a-card>
    <p :class="$style.integarsl">积分统计</p>
    <sd-detail-form
      ref="docform"
      :page-id="pageId"
      :class="$style.docform"
      @actionBtnClick="submitData"
    >
      <template v-slot="{ model, fields }">
        <sd-form-item name="type" />
        <sd-form-item v-if="model.type === '0'" name="selectMember" />
        <sd-form-item v-if="model.type === '1'" name="selectDept" />
        <sd-form-item name="year">
          <a-select
            ref="select"
            v-model="model.year"
            :get-popup-container="
              (triggerNode) => {
                return triggerNode.parentNode || document.body
              }
            "
            @change="handleChange"
          >
            <a-select-option v-for="item in yearData" :key="item" :value="item">
              {{ item }}
            </a-select-option>
          </a-select>
        </sd-form-item>
        <sd-form-item name="monthReport">
          <a-radio-group
            v-model="model.monthReport"
            name="monthradioGroup"
            @change="onChange(model, 'monthReport')"
          >
            <a-radio
              v-for="item in fields.monthReport.attr.selectListItem"
              :key="item.value"
              :value="item.value"
              :disabled="currentM && Number(item.value) > currentM"
            >
              {{ item.label }}
            </a-radio>
          </a-radio-group>
        </sd-form-item>
        <sd-form-item name="quarterReport" component="a-radio-group">
          <a-radio-group
            v-model="model.quarterReport"
            name="quarterradioGroup"
            @change="onChange(model, 'quarterReport')"
          >
            <a-radio
              v-for="item in fields.quarterReport.attr.selectListItem"
              :key="item.value"
              :value="item.value"
              :disabled="currentM && item.value !== String(moment().quarter())"
            >
              {{ item.label }}
            </a-radio>
          </a-radio-group>
        </sd-form-item>
        <sd-form-item name="halfYearReport">
          <a-radio-group
            v-model="model.halfYearReport"
            name="halfAYearradioGroup"
            @change="onChange(model, 'halfYearReport')"
          >
            <a-radio
              v-for="item in fields.halfYearReport.attr.selectListItem"
              :key="item.value"
              :value="item.value"
              :disabled="
                currentM &&
                  item.value !==
                    String(Math.floor(currentM % 6 === 0 ? currentM / 6 : currentM / 6 + 1))
              "
            >
              {{ item.label }}
            </a-radio>
          </a-radio-group>
        </sd-form-item>
        <sd-form-item name="yearReport">
          <a-radio-group
            v-model="model.yearReport"
            name="yearradioGroup"
            @change="onChange(model, 'yearReport')"
          >
            <a-radio
              v-for="item in fields.yearReport.attr.selectListItem"
              :key="item.value"
              :value="item.value"
            >
              {{ item.label }}({{ year === '' ? '' : year }})
            </a-radio>
          </a-radio-group>
        </sd-form-item>
      </template>
    </sd-detail-form>
    <a-modal
      v-model="echartsModal"
      :destroy-on-close="true"
      :width="900"
      title="积分统计"
      ok-text="导出"
      @ok="handleOk"
    >
      <div :class="$style.detailModal">
        <p>{{ echartsTitle }}</p>
        <sd-echart :class="$style.bar" :options="bar" autoresize />
        <sd-data-table
          ref="dataTable"
          data-url="api/xcoa-mobile/v1/km-point/statistics-list"
          :columns="getColumns(objType)"
        >
        </sd-data-table>
      </div>
    </a-modal>
  </a-card>
</template>

<script>
// 为了按需加载，下面的组件需要手工导入
import 'echarts/lib/chart/bar'
import 'echarts/lib/component/legend'
import 'echarts/lib/component/tooltip'
import moment from 'moment'
import { Message } from 'ant-design-vue'
import errorUtil from '@/common/services/error-util'
import download from '@/common/services/download'
import KmKnowledageService from '../km-knowledage-service'

import components from './_import-components/km-integral-statistics-import'
/**
 * 标注类型后，各个属性就可以自动完成 + 帮助提示
 * @type {import("echarts").EChartOption}
 */
export default {
  name: 'KmIntegralStatistics',
  metaInfo: {
    title: '积分统计',
  },
  components,
  data() {
    return {
      showForm: false,
      pageId: 'km/point/kmPointStatistics',
      docId: null,
      bar: {},
      year: null,
      currentM: null,
      yearData: [],
      echartsModal: false,
      echartsTitle: '',
      size: null,
      objType: '',
      echartsData: [],
      echartsColor: null,
    }
  },
  watch: {
    year(val) {
      if (val === Number(moment().format('YYYY'))) {
        this.currentM = moment().format('M')
      } else {
        this.currentM = false
      }
    },
  },
  created() {
    const nowYear = moment().format('YYYY')
    this.years = this.getYearTen(nowYear)
  },
  methods: {
    getColumns(objType) {
      if (objType === '0') {
        return [
          {
            title: '序号',
            customRender: (text, record, index) => `${index + 1}`,
          },
          {
            title: '姓名',
            dataIndex: 'name',
          },
          {
            title: '部门',
            dataIndex: 'deptName',
          },
          {
            title: '积分',
            dataIndex: 'point',
          },
        ]
      } else {
        return [
          {
            title: '序号',
            customRender: (text, record, index) => `${index + 1}`,
          },
          {
            title: '部门',
            dataIndex: 'deptName',
          },
          {
            title: '积分',
            dataIndex: 'point',
          },
        ]
      }
    },
    handleChange(v) {
      this.year = v
    },
    getYearTen(cur) {
      const years = []
      for (let i = 0; i <= 20; i++) {
        this.yearData.push(cur - i)
      }
      return years
    },
    popupScroll() {
      const addYears = this.getYearTen(this.yearData[this.yearData.length])
      this.yearData.push(...addYears)
    },
    moment,
    onChange(v, key) {
      const arr = ['quarterReport', 'monthReport', 'halfYearReport', 'yearReport']
      arr.forEach((k) => {
        if (k !== key) v[k] = ''
      })
    },
    // 提交
    submitData(evt, btn) {
      if (btn.buttonId === 'save') {
        evt.preventDefault()
        this.$refs.docform.validateFields().then(() => {
          if (
            this.$refs.docform.getFieldValue('monthReport') === undefined ||
            this.$refs.docform.getFieldValue('quarterReport') === undefined ||
            this.$refs.docform.getFieldValue('halfYearReport') === undefined ||
            this.$refs.docform.getFieldValue('yearReport') === undefined
          ) {
            Message.warn('统计方式不能为空！')
          } else {
            this.previewStatistics()
          }
        })
      }
    },

    previewStatistics() {
      const obj = this.$refs.docform.getFieldsValue()
      this.objType = this.$refs.docform.getFieldValue('type')
      const objYear = obj.year + '年'
      const objType = obj.type === '0' ? '个人积分' : '部门积分'
      const objCountType =
        obj.monthReport !== ''
          ? obj.monthReport + '月'
          : obj.quarterReport !== ''
          ? obj.quarterReport + '季度'
          : obj.halfYearReport !== ''
          ? obj.halfYearReport === '1'
            ? '上半年'
            : '下半年'
          : obj.yearReport !== ''
          ? '年报'
          : ''
      this.echartsTitle = objYear + objCountType + objType
      // 柱状图 根据个人部门颜色区分
      this.echartsColor = obj.type === '0' ? ['#c23531'] : ['#3398DB']
      const params = {
        inputs: [
          {
            name: 'type',
            value: Number(obj.type),
          },
          {
            name: 'selectDept',
            value: JSON.stringify(obj.selectDept),
          },
          {
            name: 'selectMember',
            value: JSON.stringify(obj.selectMember),
          },
          {
            name: 'year',
            value: Number(obj.year),
          },
        ],
      }
      params.inputs.push(
        Object.assign(
          { name: 'monthReport' },
          obj.monthReport ? { value: Number(obj.monthReport) } : ''
        )
      )
      params.inputs.push(
        Object.assign(
          { name: 'quarterReport' },
          obj.quarterReport ? { value: Number(obj.quarterReport) } : ''
        )
      )
      params.inputs.push(
        Object.assign(
          { name: 'halfYearReport' },
          obj.halfYearReport ? { value: Number(obj.halfYearReport) } : ''
        )
      )
      params.inputs.push(
        Object.assign(
          { name: 'yearReport' },
          obj.yearReport ? { value: Number(obj.yearReport) } : ''
        )
      )
      KmKnowledageService.getPreviewStatistics(params)
        .then((res) => {
          if (res.status === 200) {
            this.size = res.data
            Message.success('提交成功')
            this.echartsModal = true
            this.statisticsList()
          }
        })
        .catch((err) => {
          Message.warning({ content: errorUtil.getMessage(err) })
          this.echartsModal = false
        })
    },
    statisticsList() {
      const params = {
        maxResults: 10,
        startPosition: 0,
        formId: 'kmPointStatistics',
      }
      KmKnowledageService.getStatisticsList(params).then((res) => {
        const data = res.data.data || []
        if (data.length > 0) {
          this.echartsData = data
          const tenData = data.length > 10 ? this.echartsData.slice(0, 10) : this.echartsData

          const bar = {
            color: this.echartsColor,
            tooltip: {},
            xAxis: {
              type: 'category',
              data:
                this.$refs.docform.getFieldValue('type') === '0'
                  ? tenData.map((d) => d.name)
                  : tenData.map((d) => d.deptName),
            },
            yAxis: {
              type: 'value',
            },
            series: [
              {
                type: 'bar',
                barWidth: 40, // 柱图宽度
                barMaxWidth: 40, // 最大宽度
                label: {
                  show: true,
                  position: 'top',
                },
                data: tenData.map((d) => d.point),
              },
            ],
          }
          this.bar = bar
        }
      })
    },
    // 导出
    handleOk() {
      KmKnowledageService.getExportStatistics().then((res) => {
        const url = URL.createObjectURL(res)
        download(url, `${this.echartsTitle} ` + '统计.csv')
      })
      this.echartsModal = false
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.integarsl {
  margin: 20px 0 40px;
  font-size: $padding-lg;
  font-weight: bold;
  text-align: center;
}
.docform {
  width: 1000px;
  margin: 0 auto;
  :global(.sd-form-btns-close) {
    display: none;
  }
  :global(.sd-form-btns-save) {
    margin-left: 20%;
  }
}
.detail-modal {
  width: 800px;
  margin: 0 auto;
  text-align: center;
  .bar {
    width: 800px;
    margin: 0 auto;
  }
}
</style>
