<template>
  <div id="invoice_scan_code" v-loading="loading" element-loading-text="拼命加载中......请稍等">
    <el-form label-position="top" style="width: 100%">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="客户名称：">
            <el-input
                v-model="search.customerName"
                clearable
                prefix-icon="el-icon-search"
                placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <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="4">
          <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="8">
          <el-form-item>
            <span slot="label">&nbsp;</span>
            <el-button
                @click="handleSearch"
                type="primary"
                icon="el-icon-search"
            >搜索
            </el-button
            >
            <el-button v-on:click="showScanCode" type="primary"
            >生成扫码开票二维码
            </el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <br/>
    <div>
      <el-button
          :disabled="unselectedRow"
          @click="handleDelete()"
          type="primary"
          icon="el-icon-delete"
      >删除
      </el-button
      >
      <el-button @click="toggleSelection()">取消选择</el-button>
      <el-button
          :disabled="!selectedOneRow"
          @click="handleOpenOrdinaryInvoice"
          type="primary"
          icon="el-icon-arrow-right"
      >开具 增值税普通纸质发票
      </el-button>
      <el-button
          :disabled="!selectedOneRow"
          @click="handleOpenSpecialInvoice"
          type="primary"
          icon="el-icon-arrow-right"
      >开具 增值税专用纸质发票
      </el-button>
      <el-button
          :disabled="!selectedOneRow"
          @click="handleOpenElectronicsInvoice"
          type="primary"
          icon="el-icon-arrow-right"
      >开具 增值税普通电子发票
      </el-button>
      <el-button
          :disabled="!selectedOneRow"
          @click="handleOpenElectronicsSpecialInvoice"
          type="primary"
          icon="el-icon-arrow-right"
      >开具 增值税专用电子发票
      </el-button>
    </div>
    <br/>
    <el-table
        ref="multipleTable"
        :data="search.resultList"
        border
        stripe
        style="width: 100%"
        @selection-change="handleSearchResultCheckChange"
        :height="tableHeight"
    >
      <el-table-column
          type="selection"
          align="center"
          width="55"
      ></el-table-column>
      <el-table-column
          type="index"
          :index="pageIndex"
          align="center"
          label="序号"
          width="50"
      ></el-table-column>
      <el-table-column
          prop="customerType"
          align="center"
          label="类型"
          width="80"
          :formatter="fmtCustomerType"
      ></el-table-column>
      <el-table-column
          prop="customerName"
          label="名称"
          width="240"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          prop="customerEntTaxId"
          label="企业税号"
          width="180"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          prop="address"
          label="地址信息"
          width="180"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          prop="contactPhone"
          label="联系电话"
          width="180"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          prop="bankName"
          label="开户银行"
          width="180"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          prop="bankAccountNo"
          label="银行账号"
          width="180"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          prop="remark"
          label="备注"
          width="180"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          prop="customerEmail"
          label="电子邮箱"
          width="240"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          prop="customerMobile"
          label="手机号码"
          width="180"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          prop="interactType"
          label="交付方式"
          width="80"
          align="center"
          :formatter="fmtInteractType"
      ></el-table-column>
      <el-table-column
          prop="interactTypeDetail"
          label="交付详情"
          width="240"
          show-overflow-tooltip
      ></el-table-column>
    </el-table>
    <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-dialog title="扫码开票" :visible.sync="isScanInvoice" width="300px">
      <div style="text-align: center">
        <qr-code ref="invoiceQrCode" :qrcode="this"></qr-code>
        <el-row :gutter="20" style="margin-top: 50px">
          <el-col :span="12">
            <el-button
                @click="qrcodeDownload"
                type="primary"
                style="width: 100%"
            >二维码下载
            </el-button
            >
          </el-col>
          <el-col :span="12">
            <el-button
                v-print="printObj"
                type="primary"
                style="width: 100%"
            >二维码打印
            </el-button
            >
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getTaitouTodo, deleteTaitouTodo } from '@/api/taitou'
import QRCode from './components/QRCode'
import DateHelper from '@/utils/date'
import cache from '@/utils/cache'

// 客户类型列表
const customerTypeOptions = [
  {
    value: 1,
    label: '个人',
  },
  {
    value: 2,
    label: '企业',
  },
]

// 交付方式列表
const interactTypeOptions = [
  {
    value: 1,
    label: '邮箱',
  },
  {
    value: 2,
    label: '短信',
  },
  {
    value: 3,
    label: '微信',
  },
  {
    value: 4,
    label: '支付宝',
  },
  {
    value: 5,
    label: '其他',
  },
]

export default {
  name: 'invoice_scan_code',
  components: {
    'qr-code': QRCode,
  },
  data() {
    return {
      loading: false,
      search: {
        customerName: '', // 客户名称
        beginDate: DateHelper.LocalCurrentMonthStart(),
        endDate: DateHelper.LocalCurrentMonthEnd(),
        resultList: [],
        resultMultipleSelection: [],
        resultPagination: {
          currentPage: 1,
          pageSizes: [10, 30, 50, 100],
          pageSize: 10,
          total: 0,
        },
      },
      tableHeight: '',
      isScanInvoice: false,
      companyName: '',
      companyTaxId: '',
      printObj: {
        id: '#QRCode', // 这里是要打印元素的ID
        popTitle: '', // 打印的标题
        extraCss: '', // 打印可引入外部的一个 css 文件
        extraHead: '', // 打印头部文字
      },
    }
  },
  created() {
    this.tableHeight = window.innerHeight - 250
    let company = JSON.parse(cache.getSession('company'))
    this.companyName = company.entName
    this.companyTaxId = company.entTaxId
    this.callGetTaitouTodo(
        this.search.resultPagination.currentPage,
        this.search.resultPagination.pageSize
    )
  },
  mounted() {
    this.tableHeight = window.innerHeight - 250
    window.onresize = () => {
      return (() => {
        this.tableHeight = window.innerHeight - 250
      })()
    }
  },
  computed: {
    // 没有选中的数据
    unselectedRow: function () {
      if (this.search.resultMultipleSelection) {
        return this.search.resultMultipleSelection.length === 0
      } else {
        return true
      }
    },
    // 选中1行数据
    selectedOneRow: function () {
      if (this.search.resultMultipleSelection) {
        return this.search.resultMultipleSelection.length === 1
      } else {
        return false
      }
    },
  },
  methods: {
    pageIndex(index) {
      let currentPage = this.search.resultPagination.currentPage //当前页码，具体看组件取值
      let pageSize = this.search.resultPagination.pageSize //每页条数，具体是组件取值
      return index + 1 + (currentPage - 1) * pageSize
    },
    fmtCustomerType(row, column, cellValue) {
      let result = cellValue
      for (const item of customerTypeOptions) {
        if (item.value === cellValue) {
          result = item.label
          break
        }
      }
      return result
    },
    fmtInteractType(row, column, cellValue) {
      let result = cellValue
      for (const item of interactTypeOptions) {
        if (item.value === cellValue) {
          result = item.label
          break
        }
      }
      return result
    },
    handleSearch() {
      this.callGetTaitouTodo(1, this.search.resultPagination.pageSize)
    },
    handleSearchResultCheckChange(val) {
      this.search.resultMultipleSelection = val
      console.log('选中数据：')
      console.log(this.search.resultMultipleSelection)
    },
    handleSearchResultSizeChange(val) {
      this.callGetTaitouTodo(1, val)
    },
    handleSearchResultCurrentChange(val) {
      this.callGetTaitouTodo(val, this.search.resultPagination.pageSize)
    },
    toggleSelection() {
      this.$refs.multipleTable.clearSelection()
      console.log('多选表格行 全部取消')
      console.log(this.multipleSelection)
    },
    handleDelete() {
      this.callDeleteTaitouTodo()
    },
    // 显示二维码
    showScanCode() {
      // this.$refs.invoiceQrCode.getCompanyInfo(this.companyName, this.companyTaxId)
      this.isScanInvoice = true
    },
    qrcodeDownload() {
      this.$refs.invoiceQrCode.qrCodeDownLoad()
    },
    qrCodePrint() {
      this.$refs.invoiceQrCode.qrCodePrint()
    },
    callGetTaitouTodo(pageNum = 1, pageSize = 10) {
      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
      getTaitouTodo({
        customerName: this.search.customerName,
        createTimeBegin: beginTime,
        createTimeEnd: 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
          })
    },
    callDeleteTaitouTodo() {
      let selectedList = this.search.resultMultipleSelection
      if (selectedList) {
        let delList = new Array()
        for (let index = 0; index < selectedList.length; index++) {
          const element = selectedList[index]
          delList[index] = {
            recordId: element.recordId,
            belongEntTaxId: element.belongEntTaxId,
          }
        }
        this.loading = true
        let _this = this
        deleteTaitouTodo(delList)
            .then((val) => {
              _this.loading = false
              _this.$message.success(val.msg)
              _this.callGetTaitouTodo(
                  _this.search.resultPagination.currentPage,
                  _this.search.resultPagination.pageSize
              )
            })
            .catch((err) => {
              _this.$message.error(err)
              _this.loading = false
            })
      } else {
        _this.$message.warning('请选择需要删除的项目！')
        _this.loading = false
      }
    },
    // 打开专用纸质发票页面
    handleOpenSpecialInvoice() {
      if (
          this.search.resultMultipleSelection &&
          this.search.resultMultipleSelection.length === 1
      ) {
        this.$router.push({
          name: 'special_invoice',
          params: this.search.resultMultipleSelection[0],
        })
      }
    },
    // 打开普通纸质发票页面
    handleOpenOrdinaryInvoice() {
      if (
          this.search.resultMultipleSelection &&
          this.search.resultMultipleSelection.length === 1
      ) {
        this.$router.push({
          name: 'ordinary_invoice',
          params: this.search.resultMultipleSelection[0],
        })
      }
    },
    // 打开普通电子发票页面
    handleOpenElectronicsInvoice() {
      if (
          this.search.resultMultipleSelection &&
          this.search.resultMultipleSelection.length === 1
      ) {
        this.$router.push({
          name: 'electronics_invoice',
          params: this.search.resultMultipleSelection[0],
        })
      }
    },
    // 打开专用电子发票页面
    handleOpenElectronicsSpecialInvoice() {
      if (
          this.search.resultMultipleSelection &&
          this.search.resultMultipleSelection.length === 1
      ) {
        this.$router.push({
          name: 'electronics_special_invoice',
          params: this.search.resultMultipleSelection[0],
        })
      }
    },
    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
    },
  },
}
</script>

<style scoped>
</style>
