<template>
  <div>
    <a-card size="small" :bordered="false" class="searchBoxNormal">
      <div class="table-page-search-wrapper" ref="tableSearch">
        <a-form-model
          id="expenseAccountBearerList-form"
          ref="ruleForm"
          class="form-model-con"
          layout="inline"
          :rules="rules"
          :model="queryParam"
          @keyup.enter.native="handleSearch">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-model-item label="统计月份" prop="months">
                <a-input id="expenseAccountBearerList-months" :value="queryParam.months?queryParam.months.join(','):''" placeholder="请选择月份(多选)" style="width: 100%;">
                  <span style="cursor: pointer;" slot="addonAfter" @click="openMonth">
                    点击选择
                  </span>
                </a-input>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="费用承担方类型" prop="targetType">
                <v-select
                  code="EXPENSE_ACCOUNT_DETAIL_SPLIT_OBJ_TYPE"
                  allowClear
                  style="width: 100%;"
                  id="expenseAccountBearerList-targetType"
                  v-model="queryParam.targetType"
                  @change="targetChange"
                  placeholder="请选择费用承担方类型"
                ></v-select>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="费用承担方名称" prop="targetSn">
                <!-- 部门 -->
                <department id="expenseAccountBearerList-targetSn" v-show="queryParam.targetType=='DEPARTMENT'" style="width: 100%;" placeholder="请选择费用承担方名称" v-model="queryParam.targetSn"></department>
                <!-- 经销商 -->
                <custList
                  v-show="queryParam.targetType=='CUSTOMER'"
                  ref="custList"
                  cooperateFlag="1"
                  @change="custChange"
                  id="expenseAccountBearerList-custList"
                  placeholder="请选择经销商(输入名称搜索)"></custList>
                <a-select v-if="!queryParam.targetType" placeholder="请选择费用承担方名称"></a-select>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-button type="primary" @click="handleSearch" :disabled="disabled" id="expenseAccountBearerList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="expenseAccountBearerList-reset">重置</a-button>
              <a-button
                style="margin-left: 5px"
                type="primary"
                class="button-warning"
                @click="handleExport"
                :disabled="disabled"
                v-if="$hasPermissions('B_expenseCollectExportByTarget')"
                :loading="exportLoading"
                id="expenseAccountBearerList-export">导出</a-button>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-card>
    <a-card>
      <a-spin :spinning="spinning" tip="Loading...">
        <!-- 列表 -->
        <s-table
          class="sTable fixPagination"
          ref="table"
          size="small"
          :defaultLoadData="false"
          :rowKey="(record) => record.no"
          rowKeyName="no"
          :columns="columns"
          :showPagination="false"
          :data="loadData"
          :style="{ height: tableHeight+84.5+'px' }"
          :scroll="{ y: tableHeight-30}"
          bordered>
          <template slot="footer">
            <table v-if="totalData">
              <tr>
                <th colspan="5" width="42%" style="text-align: right;">汇总：</th>
                <th v-for="item in totalMData" width="6%" style="text-align: center;">{{ toThousands(item) }}</th>
                <th width="6%" style="text-align: center;">{{ toThousands(totalData['COUNT_PRICE']) }}</th>
              </tr>
            </table>
          </template>
        </s-table>
      </a-spin>
      <!-- 导出提示框 -->
      <reportModal :visible="showExport" @close="showExport=false"></reportModal>
      <selectMonth ref="months" @ok="getDateValue"></selectMonth>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { hdExportExcel } from '@/libs/exportExcel'
// 组件
import { STable, VSelect } from '@/components'
import selectMonth from './selectMonth.vue'
import reportModal from '@/views/common/reportModal.vue'
import department from '@/views/expenseManagement/expenseReimbursement/department.js'
import custList from '@/views/common/custList.vue'
// 接口
import { expenseCollectReportQueryPageByTarget, expenseCollectReportQueryCountByTarget, expenseCollectReportExportByTarget } from '@/api/reportData'
export default {
  name: 'ExpenseAccountBearerList',
  mixins: [commonMixin],
  components: { STable, VSelect, selectMonth, department, custList, reportModal },
  data () {
    return {
      spinning: false,
      showExport: false, // 导出弹窗初始值
      disabled: false, //  查询、重置按钮是否可操作
      exportLoading: false, // 导出按钮加载状态
      tableHeight: 0, // 表格高度
      queryParam: {
        months: undefined, // 月
        targetType: undefined, // 费用承担方类型
        targetSn: undefined// 费用承担方
      },
      rules: {
        'months': [{ required: true, message: '请选择月份', trigger: 'change' }],
        'targetType': [{ required: true, message: '请选择费用承担方类型', trigger: 'change' }],
        'targetSn': [{ required: true, message: '请选择费用承担方名称', trigger: 'change' }]
      },
      columns: [], // 表头数据
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const _this = this
        _this.disabled = true
        _this.spinning = true
        const paramsPage = Object.assign(parameter, this.queryParam)
        // 获取列表数据 无分页
        return expenseCollectReportQueryPageByTarget(paramsPage).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            // 计算列表序号
            const no = (data.pageNo - 1) * data.pageSize
            for (var i = 0; i < data.list.length; i++) {
              data.list[i].no = no + i + 1
            }
          }
          _this.spinning = false
          _this.disabled = false
          // 统计
          this.getCount(paramsPage)
          return data
        })
      },
      totalData: null, // 统计数据
      totalMData: []// 汇总数据
    }
  },
  methods: {
    getColumns () {
      const _this = this
      const arr = [
        {
          title: '单据类型',
          dataIndex: 'BILL_TYPE',
          width: '8%',
          align: 'center',
          customRender: function (text) {
            return text || '--'
          }
        },
        {
          title: '费用类型',
          dataIndex: 'COST_TYPE_NAME',
          align: 'center',
          customRender: function (text) {
            return text || '--'
          },
          width: '8%',
          ellipsis: true
        },
        {
          title: '费用承担方类型',
          dataIndex: 'TARGET_TYPE',
          width: '10%',
          align: 'center',
          customRender: function (text) {
            return ((text || text == 0) ? text : '--')
          }
        },
        {
          title: '费用承担方名称',
          dataIndex: 'TARGET_NAME',
          width: '10%',
          align: 'center',
          customRender: function (text) {
            return ((text || text == 0) ? text : '--')
          }
        },
        {
          title: '区域',
          dataIndex: 'SUBAREA_NAME',
          width: '6%',
          align: 'center',
          customRender: function (text) {
            return ((text || text == 0) ? text : '--')
          }
        }
      ]

      if (this.queryParam.months) {
        // 月份排序
        this.queryParam.months.sort((a, b) => {
          return a.replace('-', '') - b.replace('-', '')
        })
        for (let i = 0; i < this.queryParam.months.length; i++) {
          const item = this.queryParam.months[i]
          arr.push({
            title: item.replace('-', '年') + '月',
            dataIndex: 'M_' + item.replace('-', '_'),
            width: '6%',
            align: 'center',
            customRender: function (text) {
              return ((text || text == 0) ? _this.toThousands(text) : '--')
            }
          })
        }
      }
      arr.push({
        title: '总计',
        dataIndex: 'COUNT_PRICE',
        width: '6%',
        align: 'center',
        customRender: function (text) {
          return ((text || text == 0) ? _this.toThousands(text) : '--')
        }
      })
      this.columns = arr
    },
    // 选择月份
    openMonth () {
      this.$refs.months.showModal(this.queryParam.months, 'm1')
    },
    // 选择月份完成
    getDateValue (data) {
      this.queryParam.months = data
    },
    // 费用承担方类型 change
    targetChange (v) {
      // 清空费用承担方名称
      this.queryParam.targetSn = undefined
      this.$refs.custList.resetForm()
    },
    // 经销商 change
    custChange (v, obj, id) {
      this.queryParam.targetSn = v.key
      this.$refs.ruleForm.validateField('targetSn')
    },
    // 查询
    handleSearch () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          _this.getColumns()
          _this.$refs.table.refresh(true)
        } else {
          _this.$message.error('请选择查询条件')
          return false
        }
      })
    },
    // 获取统计数据
    getCount (params) {
      this.totalData = null
      this.totalMData = []
      expenseCollectReportQueryCountByTarget(params).then(res => {
        this.totalData = res.data
        for (var key in res.data) {
          if (key.indexOf('M_') >= 0) {
            this.totalMData.push(res.data[key])
          }
        }
      })
    },
    //  重置
    resetSearchForm () {
      this.queryParam = {
        months: undefined,
        targetType: undefined,
        targetSn: undefined
      }
      this.totalData = null
      this.totalMData = []
      this.$refs.ruleForm.resetFields()
      this.$refs.table.clearTable()
      this.getColumns()
    },
    //  导出
    handleExport () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          _this.showExport = true
          const params = _this.queryParam
          _this.$store.state.app.curActionPermission = 'B_expenseCollectExportByTarget'
          _this.exportLoading = true
          _this.spinning = true
          hdExportExcel(expenseCollectReportExportByTarget, params, '费用汇总报表（按承担方）', function () {
            _this.exportLoading = false
            _this.spinning = false
            _this.$store.state.app.curActionPermission = ''
          })
        } else {
          return false
        }
      })
    },
    // 初始化
    pageInit () {
      this.getColumns()
      this.setTableH()
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 240
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style style="less">

</style>
