<template>
  <div
      id="invoice_invalid"
      v-loading="loading"
      element-loading-text="查询中，请稍等"
  >
    <el-card>
      <el-form label-position="top" style="width: 100%">
        <el-row :gutter="20">
          <el-col :span="4">
            <el-form-item label="发票种类：">
              <el-select
                  v-model="invoiceType"
                  placeholder="请选择"
                  style="width: 100%"
                  @change="handleEntPurchaseQuery"
              >
                <el-option
                    v-for="item in invoiceCategoryOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="发票代码：">
              <el-input
                  v-model="invoiceCode"
                  placeholder="请输入发票代码"
                  readonly="readonly"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="发票号码：">
              <el-input
                  v-model="invoiceNumber"
                  placeholder="请输入发票号码"
                  readonly="readonly"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="发票份数：">
              <el-input
                  v-model="invoiceNum"
                  placeholder="请输入发票份数"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item>
                            <span slot="label">
                                <span>&nbsp;&nbsp;</span>
                            </span>
              <el-button
                  @click="batchCancel"
                  type="primary"
                  icon="el-icon-arrow-right"
              >立即作废
              </el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <br/>
    <el-card>
      <div slot="header">
        <span>空白作废发票查询</span>
      </div>
      <el-form label-position="top" style="width: 100%">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="发票种类：">
              <el-select
                  v-model="search.invoiceCategory"
                  placeholder="请选择"
                  style="width: 100%"
              >
                <el-option
                    v-for="item in invoiceCategoryOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发票号码：">
              <el-input
                  v-model.trim="search.invoiceNumber"
                  placeholder="请输入发票号码"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="起始日期：">
              <el-date-picker
                  v-model="search.beginDate"
                  type="date"
                  placeholder="选择日期"
                  style="width: 100%"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="结束日期：">
              <el-date-picker
                  v-model="search.endDate"
                  type="date"
                  placeholder="选择日期"
                  style="width: 100%"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
              <el-form-item label="操作时间：">
                  <el-date-picker
                      v-model="search.dateRange"
                      type="daterange"
                      :clearable="false"
                      unlink-panels
                      range-separator="-"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      style="width: 100%"
                  ></el-date-picker>
              </el-form-item>
          </el-col> -->
          <el-col :span="6">
            <el-form-item>
              <span slot="label">&nbsp;</span>
              <el-button
                  @click="handleSearch"
                  type="primary"
                  icon="el-icon-search"
              >搜索
              </el-button
              >
              <el-button @click="handleResetSearch"
              >重置
              </el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-container>
        <el-table
            :data="search.resultList"
            border
            stripe
            height="550px"
            style="width: 100%"
        >
          <el-table-column
              type="index"
              :index="pageIndex"
              align="center"
              label="序号"
              width="50"
          ></el-table-column>
          <el-table-column
              prop="invoiceCategory"
              label="发票种类"
              width="160"
              align="center"
              :formatter="fmtInvoiceCategory"
          ></el-table-column>
          <el-table-column
              prop="invoiceCode"
              label="发票代码"
              show-overflow-tooltip
          ></el-table-column>
          <el-table-column
              prop="invoiceNumber"
              label="发票号码"
              show-overflow-tooltip
          ></el-table-column>
          <el-table-column
              prop="invalidOper"
              label="作废人"
              show-overflow-tooltip
          ></el-table-column>
          <el-table-column
              prop="invalidTime"
              label="作废时间"
              show-overflow-tooltip
          ></el-table-column>
        </el-table>
      </el-container>
      <br/>
      <el-row type="flex" :gutter="20">
        <el-col :span="12"></el-col>
        <el-col :span="12">
          <div style="text-align: right">
            <el-pagination
                layout="total, sizes, prev, pager, next"
                :current-page="search.resultPagination.currentPage"
                :page-sizes="search.resultPagination.pageSizes"
                :page-size="search.resultPagination.pageSize"
                :total="search.resultPagination.total"
                @size-change="handleSearchResultSizeChange"
                @current-change="handleSearchResultCurrentChange"
            ></el-pagination>
          </div>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import { InvoiceInvalid, EntPurchaseQuery } from '@/api/invoice_ext'
import { invoiceInvalidQuery } from '@/api/invoice'
import DateHelper from '@/utils/date'
import { AxiosRequestData } from '../../data/axios_request'
import cache from '../../utils/cache'

// 发票种类列表
const invoiceCategoryOptions = [
  // {
  //     value: 1,
  //     label: "增值税普通电子发票",
  // },
  // {
  //     value: 2,
  //     label: "增值税电子专用发票",
  // },
  {
    value: 3,
    label: '增值税普通纸质发票',
  },
  {
    value: 4,
    label: '增值税专用纸质发票',
  },
]

/**
 * 获取发票种类文本；
 * @param {Number} intKey 发票类别的数字标识
 */
function GetInvoiceCategoryLabel(intKey) {
  let result = intKey
  for (const item of invoiceCategoryOptions) {
    if (item.value === intKey) {
      result = item.label
      break
    }
  }
  return result
}

export default {
  name: 'invoice_invalid',
  data() {
    return {
      loading: false,
      invoiceCategoryOptions: invoiceCategoryOptions,
      invoiceType: '',
      invoiceCode: '',
      invoiceNumber: '',
      invoiceNum: '',
      search: {
        invoiceCategory: '',
        invoiceNumber: '',
        beginDate: DateHelper.LocalCurrentMonthStart(),
        endDate: DateHelper.LocalCurrentMonthEnd(),
        resultList: [],
        resultPagination: {
          currentPage: 1,
          pageSizes: [10, 30, 50, 100],
          pageSize: 10,
          total: 0
        }
      },
      account: '',
      accountName: '',
      deviceType: '',
      taxDiscId: '',
      token: '',
      entTaxId: ''
    }
  },
  created() {
    let user = JSON.parse(cache.getSession('user'))
    let company = JSON.parse(cache.getSession('company'))
    this.account = user.account
    this.accountName = user.userName
    this.deviceType = company.defaultDeviceInfo.deviceType
    this.taxDiscId = company.defaultDeviceInfo.taxDiscId
    this.entTaxId = company.entTaxId
    this.token = cache.getToken()
    this.callInvoiceInvalidQuery(
        this.search.resultPagination.currentPage,
        this.search.resultPagination.pageSize
    )
  },
  methods: {
    pageIndex(index) {
      let currentPage = this.search.resultPagination.currentPage //当前页码，具体看组件取值
      let pageSize = this.search.resultPagination.pageSize //每页条数，具体是组件取值
      return index + 1 + (currentPage - 1) * pageSize
    },
    fmtInvoiceCategory(row, column, cellValue) {
      return GetInvoiceCategoryLabel(cellValue)
    },
    // 发票作废
    handleInvoiceInvalid() {
      let _this = this
      if (!_this.invoiceType) {
        this.$message({
          message: '发票种类不允许为空，请选择要作废的发票种类！',
          type: 'warning'
        })
        return
      }
      if (!_this.invoiceNum) {
        this.$message({
          message: '发票份数不允许为空，请输入要作废的发票份数！',
          type: 'warning'
        })
        return
      }
      let endInvoiceNumber = parseInt(this.invoiceNumber) + parseInt(_this.invoiceNum) - 1
      this.$confirm(
          '发票代码：' +
          this.invoiceCode +
          ' 发票号码：' +
          this.invoiceNumber + ' ---- ' + endInvoiceNumber +
          ' 是否作废当前发票！',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
      ).then(() => {
        _this.loading = true
        for (let i = 0; i < _this.invoiceNum; i++) {
          let number = parseInt(_this.invoiceNumber) + i
          InvoiceInvalid({
            invoiceInvalidType: 2,
            invoiceCategory: _this.invoiceType,
            invoiceCode: _this.invoiceCode,
            invoiceNumber: number
          })
              .then((val) => {
                // _this.$message.success(val.msg)
              })
              .catch((err) => {
                _this.loading = false
                _this.$message.error(err)
              })
        }
        _this.loading = false
        _this.$message.success('作废完成！')
        // 自动获取下一张作废发票
        _this.handleEntPurchaseQuery()
      }).catch(() => {
        // 取消了
      })
    },
    // 企业发票领用存信息
    handleEntPurchaseQuery() {
      this.invoiceCode = ''
      this.invoiceNumber = ''
      this.loading = true
      let _this = this
      EntPurchaseQuery(this.invoiceType)
          .then((val) => {
            _this.loading = false
            if (val.data.purchaseDetailVOs[0]) {
              _this.invoiceCode =
                  val.data.purchaseDetailVOs[0].currentCode
              _this.invoiceNumber =
                  val.data.purchaseDetailVOs[0].currentNumber
            } else {
              _this.$alert('暂无可以作废的发票信息！', '提示信息', {
                confirmButtonText: '确定',
                callback: (action) => {
                },
              })
            }
          })
          .catch((err) => {
            _this.loading = false
            _this.$message.error(err)
          })
    },
    // 空表发票作废查询
    handleSearch() {
      this.callInvoiceInvalidQuery(
          1,
          this.search.resultPagination.pageSize
      )
    },
    // 查询重置
    handleResetSearch() {
      this.search.invoiceCategory = ''
      this.search.invoiceNumber = ''
      this.search.beginDate = null
      this.search.endDate = null
    },
    handleSearchResultSizeChange(val) {
      this.callInvoiceInvalidQuery(1, val)
    },
    handleSearchResultCurrentChange(val) {
      this.callInvoiceInvalidQuery(
          val,
          this.search.resultPagination.pageSize
      )
    },
    callInvoiceInvalidQuery(pageNum, pageSize) {
      let beginTime = this.search.beginDate
      let endTime = this.search.endDate
      if (beginTime) {
        beginTime = this.dateFormat(new Date(beginTime), 'yyyy-MM-dd HH:mm:ss')
      }
      if (endTime) {
        let endTimeObj = new Date(endTime)
        endTime = this.dateFormat(
            new Date(
                endTimeObj.getFullYear(),
                endTimeObj.getMonth(),
                endTimeObj.getDate(),
                '23',
                '59',
                '59'
            ),
            'yyyy-MM-dd HH:mm:ss'
        )
      }
      if (beginTime && endTime) {
        if (DateHelper.ValidateDateRange(beginTime, endTime) == false) {
          this.$message.error(
              '起始日期与结束日期不合法，请确定后重试！'
          )
          return false
        }
      }
      this.loading = true
      let _this = this
      invoiceInvalidQuery({
        invoiceCategory: this.search.invoiceCategory,
        invoiceNumber: this.search.invoiceNumber,
        invoiceInvalidType: 2, // 空白作废
        invalidDateBegin: beginTime,
        invalidDateEnd: endTime,
        pageNum: pageNum,
        pageSize: pageSize,
      })
          .then((val) => {
            _this.search.resultPagination.total = val.data.total
            _this.search.resultPagination.pageSize = val.data.size
            _this.search.resultPagination.currentPage =
                val.data.current
            _this.search.resultList = val.data.records
            _this.loading = false
          })
          .catch((err) => {
            _this.$message.error(err)
            _this.loading = false
          })
    },
    dateFormat(date, fmt) {
      // 小时只支持24小时制
      var o = {
        'M+': date.getMonth() + 1, // 月份
        'd+': date.getDate(), // 日
        'H+': date.getHours(), // 24小时,
        'm+': date.getMinutes(), // 分
        's+': date.getSeconds(), // 秒
        'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
        S: date.getMilliseconds(), // 毫秒
      }
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(
            RegExp.$1,
            (date.getFullYear() + '').substr(4 - RegExp.$1.length)
        )
      }
      for (var k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
          fmt = fmt.replace(
              RegExp.$1,
              RegExp.$1.length == 1
                  ? o[k]
                  : ('00' + o[k]).substr(('' + o[k]).length)
          )
        }
      }
      return fmt
    },
    // 批量空白作废
    async batchCancel() {
      if (!this.invoiceType) {
        this.$message({
          message: '发票种类不允许为空，请选择要作废的发票种类！',
          type: 'warning'
        })
        return
      }
      if (!this.invoiceNum) {
        this.$message({
          message: '发票份数不允许为空，请输入要作废的发票份数！',
          type: 'warning'
        })
        return
      }
      if (this.token) {
        this.loading = true
        const url = '/sys/invoiceExt/invalid/batch'
        let response = await AxiosRequestData(
            url,
            this.token,
            {
              entTaxId: this.entTaxId,
              deviceType: this.deviceType,
              taxDiscId: this.taxDiscId,
              invoiceInvalidType: 2,
              invoiceCategory: this.invoiceType,
              invoiceCode: this.invoiceCode,
              invoiceNumber: this.invoiceNumber,
              invalidOper: this.accountName,
              mobile: this.account,
              reqChannel: 4,
              invalidCnt: this.invoiceNum
            },
            false,
            1
        )
        if (response) {
          console.log(response)
          this.loading = false
          if (response.code === 0) {
            let num = 0
            if (response.data.successList) {
              num = response.data.successList.length
            }
            this.$message({
              message: '空白作废完成，作废发票' + num + '份',
              type: 'success'
            })
          } else {
            this.$message.error(response.msg)
          }
        }
      }
    }
  }
}
</script>

<style scoped>
</style>
