<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-row>
              <a-col :md="3" :sm="24">
                <a-month-picker
                  style="margin-left: 8px"
                  :default-value="moment(defaultStartMonth, monthFormat)"
                  :format="monthFormat"
                  v-model="queryParam.startMonth"
                  placeholder="开始月份"
                  @change="onStartChange" /></a-col>
              <a-col :md="3" :sm="24">
                <a-month-picker
                  style="margin-left: 8px"
                  :default-value="moment(defaultEndMonth, monthFormat)"
                  :format="monthFormat"
                  v-model="queryParam.endMonth"
                  placeholder="结束月份"
                  @change="onEndChange" /></a-col>

              <a-col :md="6" :sm="24">
                <a-tree-select
                  style="width: 100%"
                  :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                  :treeData="storeTreeData"
                  :treeNodeFilterProp="'name'"
                  :showSearch="true"
                  v-decorator="['storeId']"
                  v-model="queryParam.storeId"
                  placeholder="仓库类型"
                >
                </a-tree-select>
              </a-col>
              <a-col :md="2" :sm="24">
                <a-button style="margin-left: 8px" type="default" @click="getData()">查询</a-button>
              </a-col>
              <a-col :md="2" :sm="24">
                <a-button style="margin-left: 8px" type="primary" @click="handlePrint()">打印</a-button>
              </a-col>
              <a-col :md="2" :sm="24">
                <a-button style="margin-left: 8px" type="primary" @click="doExport()">导出</a-button>
              </a-col>
            </a-row>
          </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="month">
                    <span slot="action" slot-scope="record">
                      <template>
                        <a @click="handleView(record,1)">入库明细</a>
                        <a-divider type="vertical" />
                        <a @click="handleView(record,2)">出库明细</a>

                        <a-divider type="vertical" />
                        <a @click="doExportDetail(record,1)">导出入库明细</a>
                        <a-divider type="vertical" />
                        <a @click="doExportDetail(record,2)">导出出库明细</a>

                      </template>
                    </span>
                  </a-table>
                </div>
              </a-col>
            </a-row>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-card>
    <print-in-store ref="basePrintModal" @ok="handleOk"/>
    <detail-in-store-report ref="inStoreModal" @ok="handleOk"/>
    <detail-out-store-report ref="outStoreModal" @ok="handleOk"/>
  </div>
</template>

<script>
import { getStoreMonthReport, exportMonthReport1, exportMonthReportMonth1 } from '@/api/report/check-job'
import { Chart } from '@antv/g2'
import PrintInStore from '@/views/dashboard/modules/PrintInStoreInAndOutReport'
import DetailCheckJobReport from '@/views/dashboard/modules/DetailCheckJobReport'
import DetailInStoreReport from '@/views/dashboard/modules/DetailInStoreReport'
import DetailOutStoreReport from '@/views/dashboard/modules/DetailOutStoreReport'

import moment from 'moment'
import { fetchStoreTree } from '@/api/store/store'

export default {
  name: 'Analysis',
  components: {
    DetailOutStoreReport,
    DetailInStoreReport,
    PrintInStore,
    Chart,
    DetailCheckJobReport
  },
  props: {
    title: {
      type: String,
      default: '仓库出库入库数据月统计报表'
    }
  },
  data () {
    return {
      storeTreeData: [],
      queryParam: {
        startMonth: this.BaseTool.Moment().format(this.BaseTool.Date.PICKER_NORM_YEAR) + '-01-01',
        endMonth: this.BaseTool.Moment().format(this.BaseTool.Date.PICKER_NORM_YEAR) + '-12-01',
        storeId: null,
        searchStartTime: null,
        searchEndTime: null,
        filter: this.filter
      },
      loading: false,
      serverData: [],
      sbLevelMap: {},
      treeData: [],
      monthFormat: 'YYYY-MM',
      defaultStartMonth: this.BaseTool.Moment().format(this.BaseTool.Date.PICKER_NORM_YEAR) + '-01',
      defaultEndMonth: this.BaseTool.Moment().format(this.BaseTool.Date.PICKER_NORM_YEAR) + '-12',
      years: [],
      levelMap: {},
      visible: true,
      chart: null, // 创建一个chart变量
      chartsData: [],
      // 表头
      columns: [
        {
          title: '月份',
          width: 180,
          dataIndex: 'month'
        },
        {
          title: '入库数量',
          width: 120,
          dataIndex: 'inStoreNum'
        },
        {
          title: '出库数量',
          width: 120,
          dataIndex: 'outStoreNum'
        },
        {
          title: '入库金额',
          width: 120,
          dataIndex: 'inStorePrice',
          customRender: (text, record, index) => {
            return this.BaseTool.Amount.formatter(text)
          }
        },
        {
          title: '出库金额',
          width: 120,
          dataIndex: 'outStorePrice',
          customRender: (text, record, index) => {
            return this.BaseTool.Amount.formatter(text)
          }
        },
        {
          title: '操作',
          key: 'action',
          width: '200px',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ]
    }
  },
  created () {
    this.tableOption()
    this.setTree()
  },
  mounted () {
    this.$nextTick(function () {
      this.getData()
    })
  },
  methods: {
    tableOption () {
      if (!this.optionAlertShow) {
        this.options = {
          alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
          rowSelection: {
            selectedRowKeys: this.selectedRowKeys,
            onChange: this.onSelectChange,
            getCheckboxProps: record => ({
              props: {
                disabled: true,
                name: record.id
              }
            })
          }
        }
        this.optionAlertShow = true
      } else {
        this.options = {
          alert: false,
          rowSelection: null
        }
        this.optionAlertShow = false
      }
    },
    setTree () {
      fetchStoreTree().then(res => {
        this.storeTreeData = res.data
      })
    },
    moment,
    changeLevel (value) {
      this.queryParam.standardLevel = value
      this.getData()
    },
    onStartChange (date, dateString) {
      this.$nextTick(() => {
        this.queryParam.startMonth = this.BaseTool.Date.formatter(dateString + '-01', this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
      })
    },
    onEndChange (date, dateString) {
      this.queryParam.endMonth = this.BaseTool.Date.formatter(dateString + '-01', this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
    },
    getData () {
      if (this.queryParam.startMonth == null) {
        this.$message.error('请选择起始月份')
        return
      }
      if (this.queryParam.endMonth == null) {
        this.$message.error('请选择结束月份')
        return
      }
      for (var i = 0; i < this.storeTreeData.length; i++) {
        if (this.queryParam.storeId === this.storeTreeData[i].id) {
          alert('立体仓和货架没有数据')
          return
        }
      }
      getStoreMonthReport(this.queryParam)
        .then(res => {
          this.chartsData = res.data

          // 需要将数据分组：总数，完成数
          const groupData = []
          this.chartsData.forEach(function (data) {
            groupData.push({ name: '入库数量', month: data.month + '', num: data.inStoreNum })
            groupData.push({ name: '出库数量', month: data.month + '', num: data.outStoreNum })
          })
          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('num', {
        nice: true
      })
      this.chart.tooltip({
        showMarkers: false,
        shared: true
      })
      this.chart.interval().position('month*num').color('name').adjust([
        {
          type: 'dodge',
          marginRatio: 0
        }
      ])
      this.chart.interaction('active-region')
      this.chart.legend({
        position: 'bottom'
      })
      this.chart.render()
    },
    doExport () {
      const parameter = {
        ...this.queryParam
      }
      exportMonthReport1(parameter).then(file => {
        this.BaseTool.UPLOAD.downLoadExportExcel(file)
      })
    },
    doExportDetail (record, number) {
      const parameter = {
        ...this.queryParam,
        month: record.month,
        year: record.year,
        number: number
      }
      exportMonthReportMonth1(parameter).then(file => {
        this.BaseTool.UPLOAD.downLoadExportExcel(file)
      })
    },
    handlePrint (record) {
      const modal = this.$refs.basePrintModal
      this.visible = false
      modal.base({ startMonth: this.queryParam.startMonth, endMonth: this.queryParam.endMonth, title: this.title, data: this.chartsData })
    },
    handleView (record, number) {
      let modal
      if (number === 1) {
        modal = this.$refs.inStoreModal
      } else {
        modal = this.$refs.outStoreModal
      }
      console.log(record)
      modal.base(record)
    },
    handleOk () {
      this.visible = true
    }
  }
}
</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>
