<template>
  <div class="page-header-index-wide">
    <a-card title="保养任务周工作负荷统计报表" :loading="loading" v-show="visible" :bordered="false" :body-style="{padding: '0'}">
      <div class="salesCard">
        <a-tabs default-active-key="1" size="large" :tab-bar-style="{marginBottom: '24px', paddingLeft: '16px'}">
          <div class="extra-wrapper" slot="tabBarExtraContent">
            <a-button type="primary" icon="printer" @click="getData()">刷新</a-button>
            <a-button style="margin-left: 8px" type="primary" icon="printer" @click="handlePrint()">打印</a-button>
            <a-button style="margin-left: 8px" type="primary" @click="doExport()">导出</a-button>
            <a-select style="margin-left: 8px" @change="changeYear" v-model="queryParam.year" placeholder="请选择">
              <a-select-option
                v-for="item in years"
                :key="item.value"
                :label="item.label"
                :value="item.value">{{ item.label }}
              </a-select-option>
            </a-select>
            <a-select style="margin-left: 8px" @change="changeLevel" v-model="queryParam.standardLevel" placeholder="请选择">
              <a-select-option
                v-for="(label,value) in levelMap"
                :key="value"
                :label="label"
                :value="parseInt(value)">{{ label }}
              </a-select-option>
            </a-select>
          </div>
          <a-tab-pane loading="true" tab="图形统计" key="1">
            <a-row>
              <a-col :xl="24" :lg="24" :md="24" :sm="24" :xs="24">
                <div style="padding: 10px">
                  <div id="container"></div>
                </div>
              </a-col>
            </a-row>
          </a-tab-pane>
          <a-tab-pane loading="true" tab="表格统计" key="2">
            <a-row>
              <a-col :xl="24" :lg="24" :md="24" :sm="24" :xs="24">
                <div style="padding: 10px">
                  <a-table
                    bordered
                    :data-source="chartsData"
                    :columns="columns"
                    tableLayout="auto"
                    :scroll="{x: 1, y: BaseTool.Constant.scrollY }"
                    rowKey="week">
                    <template slot="useHours" slot-scope="text, record">
                      <div class="editable-cell-input-wrapper">
                        <a-input :value="text" :id="record.week + ',useHours'" @change="$event => onUseHoursChange($event, record.week, 'useHours')" />
                      </div>
                    </template>
                    <template slot="usePeople" slot-scope="text, record">
                      <div class="editable-cell-input-wrapper">
                        <a-input :value="text" :id="record.year + record.week + ',useHours'" @change="$event => onUsePeopleChange($event, record.week, 'usePeople')" />
                      </div>
                    </template>
                    <span slot="action" slot-scope="record">
                      <template>
                        <a @click="handleAdd(record)">提交数据</a>
                        <a-divider type="vertical" />
                        <a @click="handleView(record)">查看明细</a>
                        <a-divider type="vertical" />
                        <a @click="doExportDetail(record)">导出</a>
                      </template>
                    </span>
                  </a-table>
                </div>
              </a-col>
            </a-row>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-card>
    <print-in-check-job-report-week ref="basePrintModal" @ok="handleOk"/>
    <detail-check-job-report ref="detailModal" @ok="handleOk"/>
  </div>
</template>

<script>
import { getWeekReport, exportWeekReport, saveWorkHour, exportWeekReportWeek } from '@/api/report/check-job'
import { Chart } from '@antv/g2'
import PrintInCheckJobReportWeek from '@/views/dashboard/modules/PrintInCheckJobReportWeek'
import DetailCheckJobReport from '@/views/dashboard/modules/DetailCheckJobReport'

export default {
  name: 'Analysis',
  components: {
    PrintInCheckJobReportWeek,
    Chart,
    DetailCheckJobReport
  },
  data () {
    return {
      confirmLoading: false,
      loading: false,
      serverData: [],
      queryParam: {
        year: 2021,
        standardLevel: 2
      },
      years: [],
      levelMap: {},
      visible: true,
      chart: null, // 创建一个chart变量
      chartsData: [],
      // 表头
      columns: [
        {
          title: '年',
          width: 180,
          dataIndex: 'year'
        },
        {
          title: '周',
          width: 180,
          dataIndex: 'week'
        },
        {
          title: '标准工时',
          width: 120,
          dataIndex: 'totalHours'
        },
        {
          title: '可用工时',
          width: 120,
          dataIndex: 'useHours',
          scopedSlots: { customRender: 'useHours' }
        },
        {
          title: '可用人数',
          width: 120,
          dataIndex: 'usePeople',
          scopedSlots: { customRender: 'usePeople' }
        },
        {
          title: '操作',
          key: 'action',
          width: '200px',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ]
    }
  },
  created () {
    this.levelMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.CHECK_PLAN_LEVEL)
    this.initSelectYear()
  },
  mounted () {
    this.changeYear(this.queryParam.year)
  },
  methods: {
    initSelectYear () {
      var myDate = new Date()
      this.queryParam.year = myDate.getFullYear()// 获取当前年
      this.years = []
      for (let i = 0; i < 5; i++) {
        this.years.push({ value: (this.queryParam.year - i), label: (this.queryParam.year - i) + '年' })
      }
    },
    changeYear (value) {
      this.queryParam.year = value
      this.getData()
    },
    changeLevel (value) {
      this.queryParam.standardLevel = value
      this.getData()
    },
    getData () {
      getWeekReport(this.queryParam)
        .then(res => {
          this.chartsData = res.data

          // 需要将数据分组：总数，完成数
          const groupData = []
          this.chartsData.forEach(function (data) {
            groupData.push({ name: '标准工时', week: data.week + '', totalHours: data.totalHours, totalUseHours: data.useHours * data.usePeople })
          })
          this.getCharts('container', groupData)// 调用统计图
        })
    },
    getCharts (id, data) {
      this.chart && this.chart.destroy()// 防止点击搜索按钮新增一个
      this.chart = new Chart({
        container: 'container',
        autoFit: true,
        height: 400
      })
      this.chart.data(data)
      this.chart.scale('totalHours', {
        nice: true
      })
      this.chart.tooltip({
        showMarkers: false,
        shared: true,
        showCrosshairs: true // 展示 Tooltip 辅助线
      })
      this.chart.interval().position('week*totalHours').color('name').adjust([
        {
          type: 'dodge',
          marginRatio: 0
        }
      ])
      this.chart.interaction('active-region')
      this.chart.legend({
        position: 'bottom'
      })
      this.chart.line().position('week*totalUseHours')
      this.chart.point().position('week*totalUseHours').size(4).shape('circle').style({
        stroke: '#fff',
        lineWidth: 1
      })
      this.chart.render()
    },
    doExport () {
      const parameter = {
        ...this.queryParam
      }
      exportWeekReport(parameter).then(file => {
        this.BaseTool.UPLOAD.downLoadExportExcel(file)
      })
    },
    doExportDetail (record) {
      const parameter = {
        ...this.queryParam,
        week: record.week,
        year: record.year
      }
      exportWeekReportWeek(parameter).then(file => {
        this.BaseTool.UPLOAD.downLoadExportExcel(file)
      })
    },
    handlePrint (record) {
      const modal = this.$refs.basePrintModal
      this.visible = false
      modal.base({ year: this.queryParam.year, data: this.chartsData })
    },
    handleView (record) {
      const modal = this.$refs.detailModal
      modal.base(record)
    },
    handleAdd (record) {
      this.confirmLoading = true
      record.detailList = null
      saveWorkHour(record)
        .then((res) => {
          this.$message.info(res.data)
        }).catch(() => {
          this.confirmLoading = false
        })
    },
    handleOk () {
      this.visible = true
    },
    onUseHoursChange (e, week, attr) {
      const value = e.target.value
      console.log(value)
      if (value !== 0 && !value) {
        return
      }
      const data = [...this.chartsData]
      const target = data.find(item => item.week === week)
      if (target) {
        target[attr] = value
        this.chartsData = data
      }
    },
    onUsePeopleChange (e, week, attr) {
      const value = e.target.value
      console.log(value)
      if (value !== 0 && !value) {
        return
      }
      const data = [...this.chartsData]
      const target = data.find(item => item.week === week)
      if (target) {
        target[attr] = value
        this.chartsData = data
      }
    }
  }
}
</script>

<style lang="less" scoped>
.extra-wrapper {
  line-height: 55px;
  padding-right: 24px;

  .extra-item {
    display: inline-block;
    margin-right: 24px;

    a {
      margin-left: 24px;
    }
  }
}

.antd-pro-pages-dashboard-analysis-twoColLayout {
  position: relative;
  display: flex;
  display: block;
  flex-flow: row wrap;
}

.antd-pro-pages-dashboard-analysis-salesCard {
  height: calc(100% - 24px);
  /deep/ .ant-card-head {
    position: relative;
  }
}

.dashboard-analysis-iconGroup {
  i {
    margin-left: 16px;
    color: rgba(0,0,0,.45);
    cursor: pointer;
    transition: color .32s;
    color: black;
  }
}
.analysis-salesTypeRadio {
  position: absolute;
  right: 54px;
  bottom: 12px;
}
</style>
