<template>
  <div class="app-container">
    <div v-show="viewState == 1">
      <button-bar ref="btnbar" view-title="销售数据报表" :btndisabled="btndisabled" @btnhandle="btnHandle" />
      <div class="main-content">
        <div class="searchcon">
          <el-button size="small" class="searchbtn" @click="clicksearchShow">
            {{ searchxianshitit }}
          </el-button>
          <div v-show="isSearchShow" class="search">
            <el-form ref="queryParams" :model="queryParams" :inline="true" class="tab-header">
              <el-form-item label="日期">
                <el-date-picker v-model="queryParams.date" type="date" clearable value-format="yyyy-MM-dd"
                  placeholder="选择日期" />
              </el-form-item>
              <el-form-item label="类别">
                <el-select v-model="queryParams.type" filterable placeholder="全部" clearable>
                  <el-option v-for="item in state_list" :key="item.dictKey" :label="item.dictValue"
                    :value="item.dictKey">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <div class="btn" style="text-align: center;">
              <el-button type="primary" size="small" icon="el-icon-search" @click="dosearch">查询</el-button>
              <el-button type="primary" size="small" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            </div>
          </div>
        </div>
        <div>
          <el-form>
            <el-row>
              <el-col :span="8">
                <div class="listtop" style="border: 0;">
                  <div class="tit">当日数据 {{nowDate}}</div>
                </div>

                <div>
                  <el-table v-loading="tableLoading" :key="tableKey" :data="dataList" border style="width: 100%"
                    show-summary :summary-method="getSummaries">
                    <el-table-column prop="name" label="现金流量-经营活动产生的现金流量(元)" align="center" />
                    <el-table-column prop="totalPrice" label="总额" align="center" width="150" />
                  </el-table>
                </div>
                <div style="margin-top: 50px;">
                  <el-table v-loading="tableLoading" :data="listSalesChannelData" border style="width: 100%">
                    <el-table-column width="200" label="销售渠道类别" prop="salesChannelCategory" align="center" />
                    <el-table-column label="总额" prop="totalAmount" align="center" />
                    <el-table-column label="应收帐款" prop="accountsReceivable" align="center" />
                    <el-table-column label="扣除应收" prop="deductionAccountsReceivable" align="center" />
                  </el-table>
                </div>
              </el-col>
              <el-col :span="16">
                <!-- <div style="margin-left: 50px;margin-top: 20px;"> -->

                <div id="main" style="width: 100%;height: 100%;min-height: 480px; margin-top: 30px;"></div>

                <!-- </div> -->
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div style="display: flex; flex-direction: row;margin-top: 20px;width: 100%;">
          <!-- <div style="width: 35%;">
            <div class="tit">当日数据 {{nowDate}}</div>
            <div style="margin-top: 30px;">
              <el-table v-loading="tableLoading" :key="tableKey" :data="dataList" border style="width: 100%"
                show-summary :summary-method="getSummaries">
                <el-table-column prop="name"  label="现金流量-经营活动产生的现金流量(元)" align="center" />
                <el-table-column prop="totalPrice" label="总额" align="center" width="150" />
              </el-table>
            </div>
            <div style="margin-top: 50px;">
              <el-table v-loading="tableLoading" :data="listSalesChannelData" border style="width: 100%">
                <el-table-column width="200" label="销售渠道类别" prop="salesChannelCategory" align="center" />
                <el-table-column label="总额" prop="totalAmount" align="center" />
                <el-table-column label="应收帐款" prop="accountsReceivable" align="center" />
                <el-table-column label="扣除应收" prop="deductionAccountsReceivable" align="center" />
              </el-table>
            </div>
          </div> -->
          <div style="width: 65%;margin-left: 50px;margin-top: 20px;">

            <div id="main" style="width: 800px; height: 500px;margin-top: 30px;"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import req from '@/api/supervise/salesreport'
  import ButtonBar from '@/components/ButtonBar'
  import Pagination from '@/components/pagination'
  import pageye from '@/components/pagination/pageye'
  import * as echarts from 'echarts';

  export default {
    name: 'XiaoshouXstjTj',
    components: {
      ButtonBar,
      Pagination,
      pageye
    },
    // components: {  },
    data() {
      return {
        btndisabled: false,
        viewState: 1, // 1、列表 2、添加 3、修改 4、查看
        isSearchShow: false,
        searchxianshitit: '显示查询条件',
        tableLoading: false,
        tableKey: 0,
        dataList: [{
            name: '销售商品收到的现金(元)',
            totalPrice: '10000'
          },
          {
            name: '收到其他与经营活动有关的现金(元)',
            totalPrice: '2000'
          }
        ],
        listSalesChannelData: [{
            salesChannelCategory: '连网连锁店',
            totalAmount: '2000000',
            accountsReceivable: '31,914',
            deductionAccountsReceivable: '35,793'
          },
          {
            salesChannelCategory: '连锁内加盟',
            totalAmount: '28,700',
            accountsReceivable: '28,749',
            deductionAccountsReceivable: '58,339'
          },
          {
            salesChannelCategory: '配送中心',
            totalAmount: '-1241.81',
            accountsReceivable: '28,749',
            deductionAccountsReceivable: '58,339'
          },
          {
            salesChannelCategory: '连锁外加盟',
            totalAmount: '29822.44',
            accountsReceivable: '28,749',
            deductionAccountsReceivable: '58,339'
          }
        ],
        financialAnalysisChartData: {},
        // 类型1.全部,2.常规商品3.烟草
        state_list: [{
            dictKey: 1,
            dictValue: '全部'
          },
          {
            dictKey: 2,
            dictValue: '常规商品'
          }, {
            dictKey: 3,
            dictValue: '烟草'
          }
        ],
        btnList: [ // 右上角按钮
          {
            type: 'success',
            size: 'small',
            icon: 'export',
            btnKey: 'build',
            btnLabel: '导出'
          },
          {
            type: 'info',
            size: 'small',
            icon: 'cross',
            btnKey: 'doClose',
            btnLabel: '关闭'
          }
        ],
        queryParams: {
            customerSid: '11',
          date: "",
          type: "" // 类别key
        },

        nowDate: this.getDate(),
        // 柱状图
        option: {
          legend: {},
          tooltip: {},
          dataset: {
            // 提供一份数据。
            source: [
              ['product', '分销商进货额', '实际发货额'],
              ['1-1', "30816", '28700'],
              ['1-2', '20960', '15471'],
              ['1-3', 31465, 41573],
              ['1-4', 32796, 26290],
              ['1-5', 31914, 28749],
              ['1-6', 35793, 58339],
              ['1-7', 33370, 16888]
            ]
          },
          // 声明一个 X 轴，类目轴（category）。默认情况下，类目轴对应到 dataset 第一列。
          xAxis: {
            type: 'category'
          },
          // 声明一个 Y 轴，数值轴。
          yAxis: {},
          // 声明多个 bar 系列，默认情况下，每个系列会自动对应到 dataset 的每一列。
          series: [{
            type: 'bar'
          }, {
            type: 'bar'
          }]
        },
      }
    },
    mounted() {
      // 初始化按钮
      this.$refs['btnbar'].setButtonList(this.btnList)
      // this.drawLine();
    },
    created() {
      this.loadList()
    },
    methods: {
      getDate(){
        var tempDate = new Date() // 获取今天的日期
        tempDate.setDate(tempDate.getDate() - 1) // 今天的前N天的日期，N自定义
       var endDate = tempDate.getFullYear() + '-' + (tempDate.getMonth() + 1) + '-' + tempDate.getDate()
        console.log(endDate)
        return endDate
      },
      // 搜索条件效果
      clicksearchShow() {
        this.isSearchShow = !this.isSearchShow
        if (this.isSearchShow) {
          this.searchxianshitit = '隐藏查询条件'
        } else {
          this.searchxianshitit = '显示查询条件'
        }
      },
      // 右上角点击事件
      btnHandle(btnKey) {
        switch (btnKey) {
          case 'build': // 导出
            this.doBuild()
            break
          case 'doClose': // 关闭
            this.doClose()
            break
          default:
            break
        }
      },
      loadList() {
        this.tableLoading = true

        let _this = this
        req.initData(_this.queryParams).then((resp) => {
          if (resp.success) {
            console.log('1111', resp.data)
            const data = resp.data
           _this.dataList = data.financialData
           _this.listSalesChannelData = data.listSalesChannelData
           _this.drawLine(data.financialAnalysisChartData)
           this.tableLoading = false
          } else {
            // 根据resp.code进行异常情况处理
            _this.dataList = []
            _this.listSalesChannelData = []
          }
        }).catch(e => {
          console.log('eeeee', e)
          _this.tableLoading = false
        })
      },
     // 柱状图初始化
     drawLine(obj) {
       // 基于准备好的dom，初始化echarts实例
       var myChart = echarts.init(document.getElementById('main'));
       // 绘制图表
       console.log('option', obj)
       myChart.setOption({
         legend: {},
         tooltip: {},
         dataset: {
           // 提供一份数据。
           source: obj
         },
         // 声明一个 X 轴，类目轴（category）。默认情况下，类目轴对应到 dataset 第一列。
         xAxis: {
           type: 'category'
         },
         // 声明一个 Y 轴，数值轴。
         yAxis: {},
         // 声明多个 bar 系列，默认情况下，每个系列会自动对应到 dataset 的每一列。
         series: [{
           type: 'bar'
         }, {
           type: 'bar'
         }]
       })
     },

      dosearch() {

        this.nowDate = this.queryParams.date;
        this.loadList();

      },
      resetQuery() {
        this.queryParams = {
            customerSid: '',
          date: "",
          type: '' // 类别key
        }
        this.loadList();

      },
      // 合计
      getSummaries(param) {
        const {
          columns,
          data
        } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '本项合计'
            return
          }
          const values = data.map(item => Number(item[column.property]))
          if (column.property === 'totalPrice') {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] += ''
          } else {
            if (!values.every(value => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!isNaN(value)) {
                  return prev + curr
                } else {
                  return prev
                }
              }, 0)
              sums[index] += ''
              this.amount = sums[index] += ''
            } else {
              sums[index] = ''
            }
          }
        })
        return sums
      },
      // 导出
      doBuild() {
        this.$message({
          showClose: true,
          type: 'success',
          message: '功能暂未完善...'
        })
      },
      // 返回
      doClose() {
        this.$store.dispatch('tagsView/delView', this.$route)
        this.$router.go(-1)
      }

    }

  }
</script>
<style scoped>
  .wenjiantit {
    font-size: 16px;
    font-weight: bold;
    margin: 25px 0 10px 0;
  }

  .forminfo {
    margin: 0;
    padding: 0;
  }

  .listcon {
    height: calc(100vh - 250px);
    overflow-y: auto;
    overflow-x: hidden;
  }
</style>
