<template>
  <div class="divBox">
    <div class="selCard mb14">
      <el-form size="small" label-width="85px">
        <el-form-item label="时间选择：">
          <el-date-picker
            v-model="timeVal"
            type="daterange"
            align="right"
            unlink-panels
            clearable
            format="yyyy/MM/dd"
            value-format="yyyy/MM/dd"
            @change="onchangeTime"
            style="width: 280px"
          />
        </el-form-item>
        <el-form-item label="商户名称：" prop="mer_id">
          <el-select
            v-model="tableForm.mer_id"
            clearable
            filterable
            remote
            :remote-method="getMerSelect"
            placeholder="请选择"
            class="selWidth"
            @visible-change="getMerSelect()"
          >
            <el-option
              v-for="item in merSelect"
              :key="item.mer_id"
              :label="item.mer_name"
              :value="item.mer_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="getList(1)">搜索</el-button>
          <el-button size="small" @click="searchReset()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- <cards-data v-if="cardLists.length>0" :more="true" :card-lists="cardLists" /> -->
    <el-card class="box-card">
      <div class="mb5">
        <el-tabs v-if="headeNum.length > 0" v-model="tableForm.type" @tab-click="getList(1)">
          <el-tab-pane v-for="(item,index) in headeNum" :key="index" :name="item.type.toString()" :label="item.title" />
        </el-tabs>
      </div>
      <el-table
        v-loading="listLoading"
        :data="tableData.data"
        size="small"
        class="table"
        highlight-current-row
      >
        <el-table-column label="序号" min-width="60">
          <template scope="scope">
            <span>{{ scope.$index+(tableForm.page - 1) * tableForm.limit + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="create_time"
          label="日期"
          min-width="150"
        />
        <el-table-column
        v-if="tableForm.type == 0"
          prop="mer_name"
          label="商户"
          min-width="120"
        />
        <el-table-column

          prop="nickname"
          label="用户"
          min-width="120"
        />
        <el-table-column
          prop="title"
          label="类型"
          min-width="120"
        />
        <el-table-column
          prop="mark"
          label="详情"
          min-width="200"
        />
        <el-table-column
          prop="number"
          label="数量"
          min-width="120"
        />
        <!-- <el-table-column label="操作" min-width="100" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="onDetails(scope.row.time)">详情</el-button>
            <el-button type="text" size="small" @click="exports(scope.row.time)">下载账单</el-button>
          </template>
        </el-table-column> -->
      </el-table>
      <div class="block mb20">
        <el-pagination
          background
          :page-size="tableForm.limit"
          :current-page="tableForm.page"
          layout="total, prev, pager, next, jumper"
          :total="tableData.total"
          @size-change="handleSizeChange"
          @current-change="pageChange"
        />
      </div>
    </el-card>
    <el-dialog
      :title="tableForm.type == 1 ? '日账单详情' : '月账单详情'"
      :visible.sync="dialogVisible"
      width="830px"
      :before-close="handleClose"
      center
    >
      <el-row align="middle" class="ivu-mt mt20">
      <el-col :span="4">
        <el-menu
          default-active="0"
          class="el-menu-vertical-demo"
        >
          <el-menu-item :name="accountDetails.date">
            <span>{{accountDetails.date}}</span>
          </el-menu-item>
        </el-menu>
      </el-col>
      <el-col :span="20">
          <el-col :span="6">
              <div class="grid-content">
                  <span class="title">{{accountDetails.income && accountDetails.income.title}}</span>
                  <span class="color_red">{{accountDetails.income && accountDetails.income.number}}元</span>
                  <span class="count">{{accountDetails.income && accountDetails.income.count}}</span>
                  <div class="list" v-if="accountDetails.income && accountDetails.income.data && accountDetails.income.data.length > 0">
                      <el-row class="item" v-for="(item,index) in accountDetails.income.data" :key="index">
                          <el-col :span="12" class="name">{{item['0']}}</el-col>
                          <el-col :span="12" class="cost">
                              <span class="cost_num">{{item['1']}}</span>
                              <span class="cost_count">{{item['2']}}</span>
                          </el-col>
                      </el-row>
                  </div>
              </div>
              <el-divider direction="vertical"></el-divider>
          </el-col>
          <el-col :span="6">
              <div class="grid-content">
                  <span class="title">{{accountDetails.bill && accountDetails.bill.title}}</span>
                  <span class="color_red">{{accountDetails.bill && accountDetails.bill.number}}元</span>
                  <span class="count">{{accountDetails.bill && accountDetails.bill.count}}</span>
                  <div class="list" v-if="accountDetails.bill && accountDetails.bill.data && accountDetails.bill.data.length > 0">
                      <el-row class="item" v-for="(item,index) in accountDetails.bill.data" :key="index">
                          <el-col :span="12" class="name">{{item['0']}}</el-col>
                          <el-col :span="12" class="cost">
                              <span class="cost_num">{{item['1']}}</span>
                              <span class="cost_count">{{item['2']}}</span>
                          </el-col>
                      </el-row>
                  </div>
              </div>
              <el-divider direction="vertical"></el-divider>
          </el-col>
          <el-col :span="6">
              <div class="grid-content">
                  <span class="title">{{accountDetails.expend && accountDetails.expend.title}}</span>
                  <span class="color_gray">{{accountDetails.expend && accountDetails.expend.number}}元</span>
                  <span class="count">{{accountDetails.expend && accountDetails.expend.count}}</span>
                  <div class="list" v-if="accountDetails.expend && accountDetails.expend.data && accountDetails.expend.data.length > 0">
                      <el-row class="item" v-for="(item,index) in accountDetails.expend.data" :key="index">
                          <el-col :span="12" class="name">{{item['0']}}</el-col>
                          <el-col :span="12" class="cost">
                              <span class="cost_num">{{item['1']}}</span>
                              <span class="cost_count">{{item['2']}}</span>
                          </el-col>
                      </el-row>
                  </div>
              </div>
              <el-divider direction="vertical"></el-divider>
          </el-col>
          <el-col :span="6">
              <div class="grid-content">
                  <span class="title">{{accountDetails.charge && accountDetails.charge.title}}</span>
                  <span class="color_gray">{{accountDetails.charge && accountDetails.charge.number}}元</span>
              </div>
          </el-col>
      </el-col>
    </el-row>
    <span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="dialogVisible = false">我知道了</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
import { merSelectListApi } from "@/api/product";
import { financialLstApi, financialDetailApi, finaHeaderDataApi, downloadFinancialApi,xfqLstApi } from '@/api/accounts'
import { roterPre } from '@/settings'
import cardsData from "@/components/cards/index";
import createWorkBook from '@/utils/newToExcel.js';
export default {
  name: 'AccountsStatements',
  components: { cardsData },
  data() {
    return {
      loading: false,
      roterPre: roterPre,
      timeVal: [],
      listLoading: true,
      tableData: {
        data: [],
        total: 0
      },
      tableForm: {
        page: 1,
        limit: 10,
        start_time: '',
        end_time: '',
        pm: 0,
        type: '0',
        mer_id: '',
      },
      ruleForm: {
        status: '0'
      },
      headeNum: [
        {type: 0,title: "使用记录"},
        {type: 1,title: "发放记录"},
      ],
      dialogVisible: false,
      rules: {
        status: [
          { required: true, message: '请选择对账状态', trigger: 'change' }
        ]
      },
      reconciliationId: 0,
      cardLists: [],
      merSelect: [],
      accountDetails: {
        date: '',
        charge: {},
        expend: {},
        income: {}
      }
    }
  },
  computed: {

  },
  mounted() {
    this.getList('')
    this.getMerSelect()
    // this.getHeaderData()
  },
  methods: {
    /**重置 */
    searchReset(){
      this.timeVal = []
      this.tableForm = {
        page: 1,
        limit: 10,
        start_time: '',
        end_time: '',
        pm: 0,
        type: '0',
        mer_id: '',
      }
      // this.$refs.searchForm.resetFields()
      this.getList(1)
    },
    // 商户列表；
    getMerSelect(query) {
      merSelectListApi({keyword: query})
        .then((res) => {
          this.merSelect = res.data;
        })
        .catch((res) => {
          this.$message.error(res.message);
        });
    },
    onDetails(date) {
      financialDetailApi(this.tableForm.type,{date: date}).then(res => {
        this.dialogVisible = true
        this.accountDetails = res.data
      }).catch(res => {
        this.$message.error(res.message)
      })
    },
    getHeaderData(){
       finaHeaderDataApi({date:this.tableForm.date}).then(res => {
           this.cardLists = res.data.stat
       }).catch(res => {
         this.$message.error(res.message)
       })
    },
    async exports(time) {
     let excelData = JSON.parse(JSON.stringify(this.tableForm)), data = []
      excelData.page = 1
      let pageCount = 1
      let lebData = {};
      for (let i = 0; i < pageCount; i++) {
        lebData = await this.downData(excelData,time)
        pageCount = Math.ceil(lebData.count/excelData.limit)
        if (lebData.export.length) {
          data = data.concat(lebData.export)
          excelData.page++
        }
      }
      createWorkBook(lebData.header, lebData.title, data, lebData.foot,lebData.filename);
      return
    },
    /**订单列表 */
    downData(excelData,time) {
      excelData.date = time
      return new Promise((resolve, reject) => {
        downloadFinancialApi(this.tableForm.type,excelData).then((res) => {
          return resolve(res.data)
        })
      })
    },
    handleClose() {
      this.dialogVisible = false
    },
    // 具体日期
    onchangeTime(e) {

      this.timeVal = e
      try{
        this.tableForm.start_time = this.timeVal ? this.timeVal[0].split('/').join('-'): ''
        this.tableForm.end_time = this.timeVal ? this.timeVal[1].split('/').join('-'): ''
      }catch(e){
        console.log(e)
        //TODO handle the exception
      }

      console.log(this.tableForm,'this.tableForm')
      this.getList('')
      // this.getHeaderData()
    },
    // 列表
    getList(num) {
      this.listLoading = true
      this.tableForm.page = num ? num : this.tableForm.page;
      xfqLstApi({
        page: this.tableForm.page,
        limit: this.tableForm.limit,
        pm: this.tableForm.type,
        start_time: this.tableForm.start_time,
        end_time: this.tableForm.end_time,
        mer_id: this.tableForm.mer_id,
        uid: this.tableForm.uid,
      }).then(res => {
        this.tableData.data = res.data.list
        this.tableData.total = res.data.count
        this.listLoading = false
      }).catch(res => {
        this.listLoading = false
        this.$message.error(res.message)
      })
    },
    pageChange(page) {
      this.tableForm.page = page
      this.getList('')
    },
    handleSizeChange(val) {
      this.tableForm.limit = val
      this.chkName = ''
      this.getList('')
    }
  }
}
</script>
<style lang="scss" scoped>
  .selWidth{
    width: 300px;
  }
  .el-dropdown-link {
    cursor: pointer;
    color: var(--prev-color-primary);
    font-size: 12px;
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }
  .tabBox_tit {
    width: 60%;
    font-size: 12px !important;
    margin: 0 2px 0 10px;
    letter-spacing: 1px;
    padding: 5px 0;
    box-sizing: border-box;
  }
  .el-menu-item{
    font-weight: bold;
    color: #333;
  }
  ::v-deep .el-dialog__header{
    text-align: left;
  }
  .el-col{
    position: relative;
    .el-divider--vertical{
      position: absolute;
      height: 100%;
      right: 0;
      top: 0;
      margin: 0;
    }
  }
  .grid-content{
      padding: 0 15px;
      display: block;
      .title,.color_red,.color_gray{
        display: block;
        line-height: 20px;
      }
      .color_red{
        color: red;
        font-weight: bold;
      }
      .color_gray{
        color: #333;
        font-weight: bold;
      }
     .count{
        font-size: 12px;
     }
     .list{
         margin-top: 20px;
         .item{
            overflow: hidden;
            margin-bottom: 10px;
         }
         .name,.cost{
            line-height: 20px;
         }
         .cost{
            text-align: right;
            span{
              display: block;
            }
         }
         .name,.cost_count{
            font-size: 12px;
         }
         .cost_count{
            margin-top: 10px;
         }
         .cost_num{
            font-weight: bold;
            color: #333;
         }
     }

  }

</style>
