<template>
  <div class="subPage" :style="{ padding: '20px' }">
    <div>
      <el-form inline>
        <el-form-item label="案场">
          <el-select v-model="caseId" size="medium" placeholder="请选择案场">
            <el-option
              v-for="item in cases"
              :key="item.CaseId"
              :label="item.CaseName"
              :value="item.CaseId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="条码">
          <el-input v-model="bookBarcode"></el-input>
        </el-form-item>
        <el-form-item label="书名">
          <el-input v-model="bookName"></el-input>
        </el-form-item>
        <el-form-item :style="{ float: 'right' }">
          <el-button type="primary" size="medium" @click="filterList">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-button plain @click="editBook()" size="medium">图书录入</el-button>
      <el-button plain @click="showBatchInput()" size="medium">批量导入</el-button>
      <div :style="{ margin: '10px 0' }">
        <el-table :data="list" border style="width: 100%">
          <el-table-column label="图片" width="128">
            <template slot-scope="scope">
              <img width="64" :src="scope.row.BookImg" alt>
            </template>
          </el-table-column>
          <el-table-column prop="BookBarcode" label="条码"></el-table-column>
          <el-table-column prop="BookName" label="书名"></el-table-column>
          <el-table-column label="案场">
            <template slot-scope="scope">
              <span>{{ getCaseName(scope.row.CaseId) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="分类">
            <template slot-scope="scope">
              <span>{{ getTypeName(scope.row.BookTypeId) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="价格">
            <template slot-scope="scope">
              <span>{{ formatPrice(scope.row.Price) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="BorrowDays" label="借阅(天)"></el-table-column>
          <el-table-column prop="InStock" label="总数量"></el-table-column>
          <el-table-column prop="LeftNum" label="借出"></el-table-column>
          <el-table-column label="预约">
            <template slot-scope="scope">
              <span>{{ getReserveNum(scope.row) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="录入时间">
            <template slot-scope="scope">
              <span>{{ toolClass.dateFormat(scope.row.CreateDate) }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="150">
            <template slot-scope="scope">
              <div>
                <el-button type="text" @click="changeStock(scope.row)" size="small">盘点</el-button>
                <el-button @click="setRecommend(scope.row)" type="text" size="small">{{ scope.row.IsRecommend === 1 ? '取消推荐' : '设为推荐' }}</el-button>
              </div>
              <div>
                <el-button @click="editBook(scope.row)" type="text" size="small">编辑</el-button>
                <el-button @click="removeBook(scope.row)" type="text" size="small">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          layout="prev, pager, next"
          :current-page="page"
          :total="pagenum"
          @current-change="pageChange"
        ></el-pagination>
      </div>
    </div>
    <el-dialog
      title="批量导入"
      :visible.sync="showDialog"
      width="50%">
      <div :style="{ margin: 'auto', width: '80%' }">
        <div><el-button @click="inputRef.click()" :style="{ width: '100%' }">上传文件</el-button></div>
        <div><el-button type="text" size="medium" :style="{ float: 'right' }">下载导入模板</el-button></div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="showDialog = false">确 定</el-button>
        <el-button @click="showDialog = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { createNamespacedHelpers, mapState } from 'vuex'
import { Loading } from 'element-ui'

const { mapState: mapLibSate, mapActions } = createNamespacedHelpers('library')

export default {
  name: 'bookList',
  data() {
    return {
      caseId: '',
      bookBarcode: '',
      bookName: '',
      inputRef: window.document.createElement('input'),
      showDialog: false,
    }
  },
  computed: {
    ...mapState({
      cases: x => x.app.cases.list,
      defaultCase: x => x.app.cases.default,
      orgid: x => x.app.user.OrgId
    }),
    ...mapLibSate({
      list: s => s.list,
      page: s => s.page,
      pagenum: s => s.pagenum,
      types: s => s.type.list
    })
  },
  created() {
    this.inputRef.type = 'file'
    // https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types
    this.inputRef.accept = 'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    this.inputRef.addEventListener('change', this.importBatch.bind(this))

    this.filterList()
  },
  methods: {
    ...mapActions({
      getList: 'getBookList',
      getTypeList: 'getTypeList',
      deleteBook: 'deleteBook',
      setBookRecommend: 'updateBookDetail',
      batchImport: 'batchImport',
    }),

    // 查询过滤
    filterList({ page = 0 } = {}) {
      const caseId = this.caseId || this.defaultCase
      if (!caseId) {
        this.$message({
          showClose: true,
          message: '请选择案场',
          type: 'error'
        })
        return
      }

      this.getTypeList({ page: 0, pagesize: 1000, caseid: caseId })

      this.getList({
        page,
        caseid: caseId,
        barcode: this.bookBarcode,
        name: this.bookName
      }).catch(err => {
        this.$message({
          showClose: true,
          message: err,
          type: 'error'
        })
      })
    },

    // 分页过滤
    pageChange(page) {
      this.filterList({ page })
    },

    // 删除图书
    removeBook({ BookId: id }) {
      this.$confirm('确认删除此数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.deleteBook({
            BookId: id
          })
            .then(() => {
              this.$message({
                showClose: true,
                message: '删除成功',
                type: 'success'
              })
            })
            .catch(err => {
              this.$message({
                showClose: true,
                message: err,
                type: 'error'
              })
            })
        })
        .catch(x => x)
    },

    // 跳转到编辑
    editBook({ BookId: id } = {}) {
      this.$router.push({ name: 'libraryEdit', params: { id } })
    },

    // 设为/取消推荐
    setRecommend(book) {
      const tipMsg = book.IsRecommend === 1 ? '确定取消推荐?' : '确认设置为推荐?'
      book.IsRecommend = Math.abs(book.IsRecommend - 1)

      this.$confirm(tipMsg, '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      })
        .then(() => {
          this.setBookRecommend(book)
            .then(() => {
              this.$message({
                showClose: true,
                message: '设置成功',
                type: 'success'
              })
            })
            .catch(err => {
              this.$message({
                showClose: true,
                message: err,
                type: 'error'
              })
            })
        })
        .catch(x => x)
    },

    // 批量导入
    showBatchInput() {
      if (!this.caseId) {
        this.showDialog = false

        this.$message({
          showClose: true,
          message: '请选择案场',
          type: 'error'
        })
        return
      }

      this.showDialog = true
    },
    importBatch(e) {
      this.showDialog = false

      // 需要指定案场
      const caseName = this.getCaseName(this.caseId)
      const file = e.target.files[0]
      if (!file) {
        this.$message({
          showClose: true,
          message: '请选择导入文件',
          type: 'error'
        })
      }

      this.$confirm(`数据将被导入至【${caseName}】案场, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const loadding = Loading.service({
            lock: true,
            text: '数据导入中, 可能耗时较长, 请耐心等候...'
          })

          const data = {
            caseId: this.caseId,
            excel: file,
          }

          this.batchImport(data).then(() => {
            loadding.close()

            this.$confirm(`数据导入完成, 点击【确定】刷新页面`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              window.location.reload()
            })
          }).catch((err) => {
            loadding.close()

            this.$message({
              showClose: true,
              message: err,
              type: 'error'
            })
          })
        })
        .catch(x => x)
    },

    getCaseName(id) {
      return (this.cases.filter(x => x.CaseId === id)[0] || {}).CaseName
    },

    getTypeName(id) {
      return (this.types.filter(x => x.BookTypeId === id)[0] || {}).BookTypeName
    },

    formatPrice(price) {
      return window.Number(price).toFixed(2)
    },

    getReserveNum({ InStock, LeftNum, BorrowNum } = {}) {
      return InStock - LeftNum - BorrowNum
    },

    changeStock({ BookId: id }) {
      this.$router.push({ name: 'stockChange', params: { id } })
    },
  }
}
</script>
