<template>
  <!-- 订单外部统计表-->
  <div id="externalStatistics">
    <!-- 查询区域 -->
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="searchQuery">
          <a-row :gutter="24">
            <a-col :md="6" :sm="8">
              <a-form-item label="预计发货月份">
                <!-- defaultPickerValue="[moment(defaultMonth),moment(defaultMonth)]" -->
                <a-range-picker
                  style="width: 100%"
                  :placeholder="['开始年月', '结束年月']"
                  format="YYYY-MM"
                  :mode="mode2"
                  :value="value"
                  @panelChange="handlePanelChange"
                  @change="monthChange"
                  required
                />
              </a-form-item>
            </a-col>

            <a-col :md="6" :sm="8">
              <a-form-item label="部门">
                <j-search-select-tag
                  placeholder="请选择部门"
                  v-model="queryParam.department"
                  :dictOptions="cdepNameOption">
                </j-search-select-tag>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-item label="客户">
                <j-search-select-tag
                  placeholder="请选择客户"
                  v-model="queryParam.customer"
                  :dictOptions="ccusNameOption">
                </j-search-select-tag>
              </a-form-item>
            </a-col>
            <template v-if="toggleSearchStatus"></template>
            <a-col :md="6" :sm="8">
              <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                <a-button type="primary" @click="searchQuery" :disabled="isDisabled" icon="search">查询</a-button>
                <a-button
                  type="primary"
                  @click="searchReset"
                  :disabled="isDisabled"
                  icon="reload"
                  style="margin-left: 8px"
                  >重置</a-button
                >
                <a @click="handleToggleSearch" style="margin-left: 8px">
                  {{ toggleSearchStatus ? '收起' : '展开' }}
                  <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>

    <!-- 引入 echarts -->
    <a-card :bordered="false" style="marginTop:10px;">
      <div class="chart">
        <!-- 部门 -->
        <div class="depChartStyle" style="background:rgba(255, 165, 0,.09);">
          <departmentChart ref="departmentChart" @option="getCdepNameOption" />
        </div>
        <!-- 客户 -->
        <div class="cusChartStyle" style="background:rgba(134, 151, 201,.08);">
          <customerChart ref="customerChart" @option-ccusName="getCcusNameOption"/>
        </div>
      </div>
    </a-card>

    <!-- table -->
    <a-card :bordered="false" style="marginTop:10px;">
      <a-table
        v-if="extStadata"
        bordered
        rowKey="index"
        :columns="extStaColumns"
        :data-source="extStadata"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
      >
      </a-table>
    </a-card>
  </div>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import JEllipsis from '@/components/jeecg/JEllipsis'
import moment from 'moment'

import departmentChart from '@views/reportForms/order-statistics/chart/external/departmentChart'
import customerChart from '@views/reportForms/order-statistics/chart/external/customerChart.vue'

import { externalList } from '@api/reportForms/order-statistics.js'
import { myFormatDate } from '@/utils/myutil'

export default {
  name: 'ExternalStatistics', // 订单外部统计表
  mixins: [JeecgListMixin],
  components: { JEllipsis, moment, departmentChart, customerChart },

  data() {
    // let ellipsis = (v, l = 20) => <j-ellipsis value={v} length={l} /> // 省略
    return {
      description: '订单外部统计表',
      extStaColumns: [
        {
          title: '序号',
          width: 90,
          dataIndex: 'index',
          key: 'index',
          customRender: (text, record, index) => `${index + 1}`,
          className: 'replacecolor'
        },
        {
          title: '部门',
          width: 140,
          dataIndex: 'cdepName',
          className: 'replacecolor'
        },
        {
          title: '客户',
          width: 140,
          dataIndex: 'cvenAbbName',
          className: 'replacecolor'
        },
        {
          title: '预计发货月份',
          width: 120,
          dataIndex: 'yearMonth',
          customRender: text => {
            return moment(text).format('YYYY-MM')
          },
          className: 'replacecolor'
        },
        { title: '含税单价', width: 120, dataIndex: 'inatUnitPrice', className: 'replacecolor' },
        {
          title: '实际数量',
          width: 120,
          dataIndex: 'iquantity',
          className: 'replacecolor'
        },
        { title: '本币金额', width: 150, dataIndex: 'inatMoney', className: 'replacecolor' }
      ],
      extStadata: [],
      cdepNameOption: [], //部门下拉数据
      ccusNameOption: [],//客户下拉数据
      loading: false, // 表格加载
      // 查询条件
      queryParam: {
        vendorType: '外部'
        // pageNo: '',
        // startYearMonth: '',
        // endYearMonth: '',
        // department: '',
        // customer: ''
      },

      pagination: {
        // total: '', //总条数
        // current: '', //当前页
        // pageSize: '' //一页多少
      },
      mode2: ['month', 'month'],
      value: [], //起始月份
      isDisabled: false, //按钮禁止
      monthFormat: 'YYYY-MM'
      // defaultMonth: [] //默认当前月
    }
  },

  mounted() {},
  created() {
    // 初次加载当月数据
    this.getThisMonthData();
    //this.value = [];
    //this.value.push(myFormatDate(new Date(),"yyyy-MM"));
    //this.value.push(myFormatDate(new Date(),"yyyy-MM"));

  },
  computed: {},
  methods: {
    // 初次加载当月数据（列表、图）
    getThisMonthData() {
      this.$nextTick(() => {
        this.loading = true;
        // let nowDate = new Date()
        // let date = {
        //   year: nowDate.getFullYear(),
        //   month: nowDate.getMonth() + 1
        // }
        // if (date.month >= 1 && date.month <= 9) {
        //   date.month = '0' + date.month
        // }
        //this.defaultMonth = date.year + '-' + date.month

        //this.queryParam.startYearMonth = this.defaultMonth
        //this.queryParam.endYearMonth = this.defaultMonth
        this.queryParam.vendorType = '外部'

        externalList(this.queryParam).then(res => {
          // 参数给 chart
          this.$refs.departmentChart.queryParam = this.queryParam
          this.$refs.customerChart.queryParam = this.queryParam
          this.loading = false;
          if (res.success) {
            this.extStadata = res.result.records;
            this.pagination = {
              total: res.result.total,
              current: res.result.current,
              pageSize: res.result.size
            }
          }
        })
      })
    },

    // 查询订单统计
    getExternalData() {
      this.$nextTick(() => {
        this.loading = true;
        this.queryParam.vendorType = '外部'
        externalList(this.queryParam).then(res => {
          this.loading = false;
          // 参数给 chart
          this.$refs.departmentChart.queryParam = this.queryParam
          this.$refs.customerChart.queryParam = this.queryParam

          if (res.success) {
            this.extStadata = res.result.records;

            this.pagination = {
              total: res.result.total,
              current: res.result.current,
              pageSize: res.result.size
            }
          }
        })
      })
    },

    // 查询
    searchQuery() {
      this.queryParam.pageNo = ''
      if (this.queryParam) {
        // 清空部门chart数据
        this.$refs.departmentChart.cdepNameArr = []
        this.$refs.departmentChart.iquantityArr = []
        this.$refs.departmentChart.inatMoneyArr = []
        // 清空客户chart数据
        this.$refs.customerChart.ccusNameArr = []
        this.$refs.customerChart.iquantityArr = []
        this.$refs.customerChart.inatMoneyArr = []

        this.getExternalData()

        //查询条件 传给 部门chart + 渲染
        this.$refs.departmentChart.queryParam = this.queryParam
        this.$refs.departmentChart.getDepChartData()

        //查询条件 传给 客户chart + 渲染
        this.$refs.customerChart.queryParam = this.queryParam
        this.$refs.customerChart.getCusChartData()
      }

      this.isDisabled = true
      setTimeout(() => {
        let that = this
        that.isDisabled = false
      }, 3000)
    },
    // 重置
    searchReset() {
      this.queryParam = {}
      this.value = [] //起始年月重置
      this.queryParam.startYearMonth = []
      this.queryParam.endYearMonth = []

      // 清空部门 chart 数据 + 查询条件 + 重新渲染
      this.$refs.departmentChart.cdepNameArr = []
      this.$refs.departmentChart.iquantityArr = []
      this.$refs.departmentChart.inatMoneyArr = []
      this.$refs.departmentChart.queryParam = {}
      this.$refs.departmentChart.getDepChartData()

      // 清空客户 chart 数据 + 查询条件 + 重新渲染
      this.$refs.customerChart.ccusNameArr = []
      this.$refs.customerChart.iquantityArr = []
      this.$refs.customerChart.inatMoneyArr = []
      this.$refs.customerChart.queryParam = {}
      this.$refs.customerChart.getCusChartData()

      // 重新渲染列表数据
      this.getExternalData()

      this.isDisabled = true
      setTimeout(() => {
        let that = this
        that.isDisabled = false
      }, 3000)
    },
    // 日期面板变化时的回调
    handlePanelChange(value, mode) {
      this.value = value
      this.mode2 = [mode[0] === 'date' ? 'month' : mode[0], mode[1] === 'date' ? 'month' : mode[1]]
      this.queryParam.startYearMonth = value[0].format('YYYY-MM')
      this.queryParam.endYearMonth = value[1].format('YYYY-MM')
      // console.log('开始年月:', this.queryParam.startYearMonth)
      // console.log('结束年月:', this.queryParam.endYearMonth)
    },

    // 时间发生变化的回调，发生在用户选择时间时
    monthChange(value) {
      this.value = value
      this.queryParam.startYearMonth = ''
      this.queryParam.endYearMonth = ''
    },

    handleTableChange(pagination, filters, sorter) {
      this.queryParam.pageNo = pagination.current
      this.getExternalData()
    },
    
    //整理部门下拉框数据
    getCdepNameOption(val){
       val.map(item=>{
         this.cdepNameOption.push({text:item,value:item})
       })
    },

    //整理客户下拉框数据
    getCcusNameOption(index) {
       index.map(item=>{
         this.ccusNameOption.push({text:item,value:item})
       })
    }
    
  }
}
</script>
<style lang="less" scoped>
@import '~@assets/less/common.less';
@import '~@assets/less/overwriter.less';
/deep/ .ant-table-thead > tr > th {
  text-align: center;
  // font-weight: 700;
}

/deep/ .ant-table-tbody {
  text-align: center;
}

// /deep/ th.replacecolor {
//   background-color: #ccc;
// }

.depChartStyle,
.cusChartStyle {
  // width: 100%;
  // height: 600px;
  text-align: center;
  padding-top: 10px;
}
.depChartStyle {
  margin-bottom: 20px;
}
</style>
