<template>
  <div class="app-container">
    <div v-loading.fullscreen.lock="loadingFull" />
    <el-form label-width="80px">
      <el-form-item label="搜索方式:">
        <el-radio-group v-model="searchParams.type">
          <el-radio :label="0">按开始时间到结束时间搜索</el-radio>
          <el-radio :label="1">按月搜索</el-radio>
          <el-radio :label="2">按年搜索</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="搜索时间:">
        <el-date-picker
          v-if="searchParams.type === 0"
          v-model="searchParams.time"
          type="daterange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          align="left"
        />
        <el-date-picker
          v-if="searchParams.type === 1"
          v-model="searchParams.month"
          type="month"
          placeholder="选择月"
          align="left"
          value-format="yyyy-MM"
        />
        <el-date-picker
          v-if="searchParams.type === 2"
          v-model="searchParams.year"
          type="year"
          placeholder="选择年"
          align="left"
          value-format="yyyy"
        />
        <el-button
          type="primary"
          size="small"
          @click="searchParams.page_index = 1;getFlowList()"
        >
          搜索
        </el-button>
        <el-button
          type="primary"
          size="small"
          style="margin:0 0 20px 20px;"
          :loading="downloadLoading"
          icon="el-icon-document"
          @click="exportFlowPrice"
        >
          导出
        </el-button>
      </el-form-item>
    </el-form>

    <el-table
      :data="table"
      :header-cell-style="{ background: '#f8fbfc' }"
      class="tableBorder"
      border
      stripe
    >
      <el-table-column
        prop="ordersn"
        align="center"
        label="流水单号"
      />
      <el-table-column
        prop="goods"
        align="center"
        label="进货信息"
        width="500"
      >
        <template
          slot-scope="{ row }"
        >
          <p
            v-for="(item, i) in row.goods.slice(0,3)"
            :key="i"
          >
            {{ `${item.name}+${item.sku.type ? item.sku.type : '' }+${item.sku.size ? item.sku.size : ''}+${item.num}件` }}
          </p>
          <el-button
            v-if="row.goods.length > 3"
            type="text"
            @click="handleSeeGoods(row)"
          >
            查看全部
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        prop="total"
        align="center"
        label="进货数量"
      />
      <el-table-column
        prop="account"
        align="center"
        label="进货金额"
      />
      <el-table-column
        prop="created_at"
        align="center"
        label="进货时间"
      />
    </el-table>
    <!-- 分页 -->
    <pagination
      :total="tableTotal"
      :limit="searchParams.page_size"
      :page="searchParams.page_index"
      @pagination="changePagination"
      @update:limit="changePagination"
    />
    <!-- 进货详情 -->
    <el-drawer
      title="进货详情"
      :visible.sync="visible.goods"
      direction="rtl"
      size="60%"
    >
      <el-form v-if="goodsInfo.id" label-width="100px">
        <el-form-item label="订单号:">{{ goodsInfo.ordersn }}</el-form-item>
        <el-form-item label="下单时间:">{{ goodsInfo.created_at }}</el-form-item>
        <el-form-item label="进货详情:">
          <el-table
            :data="goodsInfo.goods"
            border
          >
            <el-table-column
              prop="name"
              label="进货商品"
              align="center"
            />
            <el-table-column
              prop="sku"
              label="商品款式"
              align="center"
            >
              <template
                slot-scope="{ row }"
              >
                {{ row.sku.type ? row.sku.type : '商品款式未设置' }}
              </template>
            </el-table-column>
            <el-table-column
              prop="sku"
              label="商品尺码"
              align="center"
            >
              <template
                slot-scope="{ row }"
              >
                {{ row.sku.type ? row.sku.type : '商品尺码未设置' }}
              </template>
            </el-table-column>
            <el-table-column
              prop="num"
              label="进货量"
              align="center"
            />
            <el-table-column
              prop="price"
              label="商品单价"
              align="center"
            />
            <el-table-column
              prop="totalprice"
              label="进货总额"
              align="center"
            />
          </el-table>
        </el-form-item>
        <el-form-item label="合计:">{{ `数量: ${goodsInfo.total} 总金额: ${goodsInfo.account}元` }}</el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
// api
import {
  getFlowList
} from '@/api/finance/flow'
// 导出api
import {
  exportFlowPrice
} from '@/api/export'
// 格式化时间
import {
  formatter
} from '@/filters/index'
import { parseTime } from '@/utils'
export default {
  data() {
    return {
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 6)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      searchParams: {
        type: 0,
        time: [formatter(Date.now() - 6 * 24 * 60 * 60 * 1000, 'yyyy-MM-dd'), formatter(Date.now(), 'yyyy-MM-dd')],
        month: `${new Date().getFullYear()}-${new Date().getMonth() + 1}`,
        year: `${new Date().getFullYear()}`,
        page_size: 20,
        page_index: 1
      },
      table: [],
      tableTotal: 10,
      visible: {
        goods: false
      },
      goodsInfo: {},
      downloadLoading: false,
      loadingFull: false
    }
  },
  created() {
    this.getFlowList()
  },
  methods: {
    // 获取流水账单
    async getFlowList() {
      this.loadingFull = true
      try {
        const { page_index, page_size, time, type, month, year } = this.searchParams
        let date
        if (type === 0) {
          date = time
        } else if (type === 1) {
          date = month
        } else {
          date = year
        }
        const res = await getFlowList({
          page_index,
          page_size,
          type,
          time: date
        })
        const { message, code } = res
        if (code === 200) {
          const { data } = res
          const { list, total } = data
          this.table = list
          this.tableTotal = total
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        console.log(`获取流水账单失败:${e}`)
      }
      this.loadingFull = false
    },
    // 分页页码变化
    changePagination(data) {
      const { page, limit } = data
      this.searchParams.page_size = limit
      this.searchParams.page_index = page
      this.getFlowList()
    },
    // 查看进货详情
    handleSeeGoods(row) {
      this.goodsInfo = row
      this.visible.goods = true
    },
    // 导出流水账单
    async exportFlowPrice() {
      const { time, type, month, year } = this.searchParams
      let date
      if (type === 0) {
        date = time
      } else if (type === 1) {
        date = month
      } else {
        date = year
      }
      try {
        const res = await exportFlowPrice({
          type,
          time: date
        })
        const { code, message } = res
        if (code === 200) {
          const { data } = res
          if (data.length < 1) {
            this.$message.error('没有数据哦!!!')
            return false
          }
          this.downloadLoading = true
          import('@/vendor/Export2Excel').then(excel => {
            const tHeader = ['Id', '流水单号', '进货数量', '总金额', '进货时间']
            const filterVal = ['id', 'ordersn', 'total', 'account', 'created_at']
            const list = data
            const dataVal = this.formatJson(filterVal, list)
            excel.export_json_to_excel({
              header: tHeader,
              data: dataVal,
              filename: `${date}流水账单`,
              autoWidth: true,
              bookType: 'xlsx'
            })
            this.downloadLoading = false
          })
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        console.log(`导出流水账单失败: ${e}`)
      }
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
