<template>
  <div id="card-1">
    <el-row>
      <el-col :span="24" class="main">
        <el-col :span="24" class="one">
          <search-1 :form="searchForm" @onSubmit="search" @querySearch="querySearch" @toReset="toClose" :shopList="shopList"></search-1>
        </el-col>
        <el-col :span="24" v-if="afterSaleList.length != '0' || orderList.length != '0'">
          <el-button type="primary" @click="toFile()">对账</el-button>
        </el-col>
        <el-col :span="24" class="two">
          净销售额：<span>{{ info.total || '0' }}</span> 元
        </el-col>
        <el-col :span="24">
          <el-tabs type="border-card">
            <el-tab-pane label="订单">
              <data-table :fields="orderfields" @query="search" :data="orderList" :usePage="false"> </data-table>
            </el-tab-pane>
            <el-tab-pane label="售后单">
              <data-table :fields="afterSalefields" @query="search" :data="afterSaleList" :usePage="false"> </data-table>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-col>
    </el-row>
  </div>
</template>

<script>
const _ = require('lodash');
import FileSaver from 'file-saver';
const ExcelJS = require('exceljs');
import { mapState, createNamespacedHelpers } from 'vuex';
const { mapActions } = createNamespacedHelpers('getBill');
const { mapActions: outBill } = createNamespacedHelpers('outBill');
const { mapActions: shop } = createNamespacedHelpers('shop');
export default {
  name: 'card-1',
  props: {},
  components: { search1: () => import('./parts/search-1.vue') },
  data: function () {
    return {
      searchForm: {},
      info: {},
      afterSaleList: [],
      orderList: [],
      orderfields: [
        { label: '订单号', model: 'no' },
        { label: '订单类型', model: 'type' },
        { label: '支付时间', model: 'pay_time' },
        { label: '商品', model: 'goods' },
        { label: '规格', model: 'spec' },
        { label: '购买数量', model: 'buy_num' },
        { label: '单价', model: 'price' },
        { label: '优惠金额', model: 'discount' },
        { label: '总价', model: 'total' },
      ],
      afterSalefields: [
        { label: '订单号', model: 'no' },
        { label: '商品', model: 'goods' },
        { label: '规格', model: 'spec' },
        { label: '退款时间', model: 'end_time' },
        { label: '退款金额', model: 'money' },
      ],
      // 多选值
      selected: [],
      // 自营店铺信息
      shop: {},
      // 店铺列表
      shopList: [],
    };
  },
  async created() {
    await this.search();
    await this.searchOther();
  },
  methods: {
    ...shop({ shopQuery: 'query' }),
    ...mapActions(['query', 'fetch', 'create', 'update', 'delete']),
    ...outBill({ outQuery: 'query', outCreate: 'create' }),
    // 查询
    async search({ skip = 0, limit = 10, ...info } = {}) {
      let condition = _.cloneDeep(this.searchForm);
      if (condition.buy_time && condition.shop) {
        condition[`start`] = _.head(condition.buy_time);
        condition[`end`] = _.last(condition.buy_time);
        delete condition.buy_time;
        let res = await this.query({ skip, limit, ...condition, ...info });
        if (this.$checkRes(res)) {
          this.$set(this, 'info', res.data);
          this.$set(this, 'afterSaleList', res.data.afterSaleList);
          this.$set(this, 'orderList', res.data.orderList);
        }
      } else {
        this.$message({ type: `warning`, message: `请选择查询信息` });
      }
    },
    // 重置
    toClose() {
      this.searchForm = {};
      this.search();
    },
    // 店铺名称远程查询
    async querySearch(value) {
      let res = await this.shopQuery({ name: value });
      if (this.$checkRes(res)) {
        this.$set(this, 'shopList', res.data);
      }
    },
    // 导出清单
    toFile() {
      const workbook = new ExcelJS.Workbook();
      let orderList = this.orderList;
      const worksheet_one = workbook.addWorksheet('订单');
      let data_one = [['订单号', '订单类型', '支付时间', '商品', '规格', '购买数量', '单价', '优惠金额', '总价']];
      for (const p1 of orderList) {
        let p2 = [[p1.no, p1.type, p1.pay_time, p1.goods, p1.spec, p1.buy_num, p1.price, p1.discount, p1.total]];
        data_one.push(...p2);
      }
      for (const val of data_one) {
        worksheet_one.addRow(val);
      }
      let afterSaleList = this.afterSaleList;
      const worksheet_two = workbook.addWorksheet('售后单');
      let data_two = [['订单号', '商品', '规格', '退款时间', '退款金额']];
      for (const p1 of afterSaleList) {
        let p2 = [[p1.no, p1.goods, p1.spec, p1.end_time, p1.money]];
        data_two.push(...p2);
      }
      for (const val of data_two) {
        worksheet_two.addRow(val);
      }
      worksheet_one.columns.forEach(function (column, i) {
        column.width = 20;
      });
      worksheet_two.columns.forEach(function (column, i) {
        column.width = 20;
      });
      workbook.xlsx.writeBuffer().then((buffer) => {
        FileSaver.saveAs(
          new Blob([buffer], {
            type: 'application/octet-stream',
          }),
          `对账单.xlsx`
        );
      });
      // this.$confirm('是否确认对账?', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning',
      // }).then(async () => {
      //   let order = [];
      //   for (const p1 of this.orderList) {
      //     order.push(p1._id);
      //   }
      //   let afterSale = [];
      //   for (const p1 of this.afterSaleList) {
      //     afterSale.push(p1._id);
      //   }
      //   let res;
      //   res = await this.outCreate({ order, afterSale });
      //   if (this.$checkRes(res)) {
      //     this.$message({ type: `success`, message: `对账成功` });
      //   }
      // });
    },
    // 查询其他信息
    async searchOther() {},
  },
  computed: {
    ...mapState(['user']),
  },
  metaInfo() {
    return { title: this.$route.meta.title };
  },
  watch: {
    test: {
      deep: true,
      immediate: true,
      handler(val) {},
    },
  },
};
</script>

<style lang="less" scoped>
.one {
  margin: 0 0 10px 0;
}
.two {
  span {
    color: red;
  }
}
.title {
  text-align: center;
}
.el-col {
  margin: 10px 0;
}
</style>
