<template>
  <div id="invoice_todo">
    <el-row type="flex" :gutter="20">
      <el-col :span="5">
        <el-input
            v-model="searchText"
            clearable
            prefix-icon="el-icon-search"
            placeholder="请输入购方名称"
        ></el-input>
      </el-col>
      <el-col :span="4">
        <el-select v-model="selectStatus" placeholder="请选择">
          <el-option
              v-for="item in statusList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="12">
        <el-button @click="onSearch" type="primary">搜索</el-button>
        <el-button v-show="false" v-on:click="showScanCode" type="primary">扫码开票</el-button>
      </el-col>
    </el-row>
    <br/>
    <el-table
        ref="multipleTable"
        :data="tableData"
        border
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
        :height="tableHeight"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="index" :index="pageIndex" align="center" label="序号" width="50"></el-table-column>
      <el-table-column prop="customerName" label="购方名称"></el-table-column>
      <el-table-column prop="totalAmountTaxes" label="发票金额" :formatter="fmtRMB"></el-table-column>
      <el-table-column prop="createTime" label="发起时间"></el-table-column>
      <el-table-column label="操作" align="center" width="120">
        <template slot-scope="scope" v-if="scope.row.status !== 4">
          <el-button @click="handleGoKaipiao(scope.row)" type="primary" size="small">点击开票</el-button>
        </template>
      </el-table-column>
    </el-table>
    <br/>
    <el-row type="flex" :gutter="20">
      <el-col :span="12">
        <div>
          <el-button @click="handleDelete()">删除</el-button>
          <el-button @click="toggleSelection()">取消选择</el-button>
        </div>
      </el-col>
      <el-col :span="12">
        <div style="text-align:right">
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pagination.currentPage"
              :page-sizes="pagination.pageSizes"
              :page-size="pagination.pageSize"
              layout="total, sizes, prev, pager, next"
              :total="pagination.total"
          ></el-pagination>
        </div>
      </el-col>
    </el-row>

    <el-dialog title="开具发票" :visible.sync="todoCommit.dialogVisible" center>
      <el-form
          :model="todoCommit.form"
          :rules="todoCommit.rules"
          ref="todoCommitForm"
          label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发票抬头">
              <el-input v-model="todoCommit.form.customerName" readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="税号">
              <el-input v-model="todoCommit.form.customerEntTaxId" readonly></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="地址">
          <el-input v-model="todoCommit.form.address" auto-complete="off" readonly></el-input>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开户银行">
              <el-input
                  v-model="todoCommit.form.bankName"
                  auto-complete="off"
                  readonly
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开户银行账号">
              <el-input
                  v-model="todoCommit.form.bankAccountNo"
                  auto-complete="off"
                  readonly
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="交付方式" style="text-align:left">
          <!-- 交付方式  1:邮箱  2:短信   3:微信  4:支付宝 5:其他 -->
          <el-radio-group v-model="todoCommit.form.interactType">
            <el-radio :label="1">邮箱</el-radio>
            <el-radio :label="2">手机短信</el-radio>
            <el-radio :label="3">微信卡包</el-radio>
            <el-radio :label="4">支付宝发票管家</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
            v-if="todoCommit.form.interactType === 1"
            label="邮箱"
            prop="customerEmail"
        >
          <el-input v-model="todoCommit.form.customerEmail"></el-input>
        </el-form-item>
        <el-form-item
            v-if="todoCommit.form.interactType === 2"
            label="手机号码"
            prop="customerMobile"
        >
          <el-input v-model="todoCommit.form.customerMobile"></el-input>
        </el-form-item>
        <el-form-item label="备注说明">
          <el-input
              v-model="todoCommit.form.remark"
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
          ></el-input>
        </el-form-item>
        <el-form-item style="text-align:left">
          <label style="color:red">
            <u>发票价税合计：{{ todoCommit.form.totalAmountTaxes }} 元</u>
          </label>
          <el-button
              @click="handleTodoInvoiceDetail"
              style="display:inline;margin-left:30px"
          >查看详细
          </el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="handleTodoCommitOk">立即开票</el-button>
                <el-button @click="handleTodoCommitCancel">取消</el-button>
            </span>
    </el-dialog>
    <el-dialog title="发票详细" :visible.sync="todoInvoiceDetail.dialogVisible" center>
      <el-card>
        <div slot="header" class="clearfix">
          <span>商品列表</span>
        </div>
        <el-table
            :data="todoInvoiceDetail.productList"
            border
            style="width: 100%"
            height="250px"
        >
          <el-table-column prop="itemCode" label="商品编码"></el-table-column>
          <!-- <el-table-column prop="orderId" label="订单id"> </el-table-column> -->
          <!-- <el-table-column prop="entTaxId" label="税号"> </el-table-column> -->
          <el-table-column prop="itemName" label="产品项目名称"></el-table-column>
          <el-table-column prop="price" label="单价"></el-table-column>
          <el-table-column prop="unit" label="单位"></el-table-column>
          <el-table-column prop="number" label="数量"></el-table-column>
          <el-table-column prop="taxRate" label="税率"></el-table-column>
          <el-table-column prop="taxes" label="税额"></el-table-column>
          <el-table-column prop="amount" label="金额"></el-table-column>
          <!-- 项目行性质   0 正常行、1 折扣行、 2 被折扣行 -->
          <!-- <el-table-column prop="itemType" label="项目行性质"> </el-table-column> -->
          <!-- 零税率标识 空：非零税率， 1：免税，2：不征收，3 普通零税率 -->
          <!-- <el-table-column prop="zeroRateFlag" label="零税率标识"> </el-table-column> -->
          <!-- 增值税特殊 优惠政策标示为 1，增值税特殊管理必须为不征税 -->
          <!-- <el-table-column prop="taxSpeManage" label="增值税特殊"> </el-table-column> -->
          <!-- 是否享受优惠政策  0 不享受  1： 享受 -->
          <!-- <el-table-column prop="preferentialFlag" label="是否享受优惠政策"> </el-table-column> -->
        </el-table>
      </el-card>
      <br/>
      <el-card>
        <el-row :gutter="20">
          <el-col :span="12" style="text-align:left">
            <label style="color:red">
              <u>发票价税合计：{{ todoCommit.form.totalAmountTaxes }} 元</u>
            </label>
            <label style="color:red;margin-left:40px">
              <u>发票总税额：{{ invoiceDetailTotalTaxes }} 元</u>
            </label>
          </el-col>
          <el-col :span="12" style="text-align:right">
            <el-button
                @click="todoInvoiceDetail.dialogVisible = false"
                type="primary"
                size="small"
            >确 定
            </el-button>
          </el-col>
        </el-row>
      </el-card>
    </el-dialog>
    <el-dialog title="扫码开票" :visible.sync="isScanInvoice" center>
      <div>
        <el-button v-on:click="qrcodeDownload" type="primary">二维码下载</el-button>
        <el-button v-print="printObj" type="primary">二维码打印</el-button>
      </div>
      <qr_code ref="invoiceQrCode" :qrcode="this"></qr_code>
      <span slot="footer">
                <el-button v-on:click="qrcodeShow">取 消</el-button>
            </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getInvoiceTodo,
  getInvoiceTodoDetail,
  deleteInvoiceTodo,
  invoiceTodoCommit,
  getInvoiceTodoCmdParam,
} from '@/api/invoice_management'
import QRCode from './components/QRCode'
import cache from '@/utils/cache'

export default {
  name: 'invoice_todo',
  components: {
    qr_code: QRCode,
  },
  data() {
    return {
      searchText: '',
      tableData: [],
      pagination: {
        currentPage: 1,
        pageSizes: [10, 30, 50, 100],
        pageSize: 10,
        total: 0,
      },
      multipleSelection: [],
      todoCommit: {
        dialogVisible: false,
        recordId: '', // 待开发票记录id
        customerType: 0, // 客户抬头类型1 ：个人 2：企业
        form: {
          customerName: '',
          customerEntTaxId: '',
          address: '',
          bankName: '',
          bankAccountNo: '',
          interactType: 0,
          customerEmail: '',
          customerMobile: '',
          remark: '',
          totalAmountTaxes: 0,
          interactTypeDetail: ''
        },
        rules: {
          customerEmail: [
            {
              required: true,
              message: '请输入邮箱',
              trigger: 'blur',
            },
          ],
          customerMobile: {
            required: true,
            message: '请输入手机号码',
            trigger: 'blur',
          },
        },
      },
      todoInvoiceDetail: {
        dialogVisible: false,
        recordId: '', // 待开发票记录id
        productList: [], // 商品列表
      },
      tableHeight: '',
      isScanInvoice: false,
      companyName: '',
      companyTaxId: '',
      printObj: {
        id: '#QRCode', // 这里是要打印元素的ID
        popTitle: '', // 打印的标题
        extraCss: '', // 打印可引入外部的一个 css 文件
        extraHead: '', // 打印头部文字
      },
      statusList: [
        {
          value: 2,
          label: '待开票'
        },
        {
          value: 3,
          label: '开票中'
        },
        {
          value: 4,
          label: '开票成功'
        },
        {
          value: 5,
          label: '开票失败'
        }
      ],
      selectStatus: 2,
      userName: ''
    }
  },
  created() {
    this.tableHeight = window.innerHeight - 250
    this.callGetInvoiceTodo(
        this.pagination.currentPage,
        this.pagination.pageSize
    )
    let company = JSON.parse(cache.getSession('company'))
    let user = JSON.parse(cache.getSession('user'))
    this.userName = user.userName
    this.companyName = company.entName
    this.companyTaxId = company.entTaxId
  },
  mounted() {
    this.tableHeight = window.innerHeight - 250
    window.onresize = () => {
      return (() => {
        this.tableHeight = window.innerHeight - 250
      })()
    }
  },
  computed: {
    // 发票详细的总税额，发票详细弹出使用
    invoiceDetailTotalTaxes() {
      let result = 0
      for (const item of this.todoInvoiceDetail.productList) {
        result += Number.parseFloat(item.taxes)
      }
      return result
    },
  },
  methods: {
    pageIndex(index) {
      let currentPage = this.pagination.currentPage // 当前页码，具体看组件取值
      let pageSize = this.pagination.pageSize // 每页条数，具体是组件取值
      return index + 1 + (currentPage - 1) * pageSize
    },
    onSearch() {
      this.callGetInvoiceTodo(1, this.pagination.pageSize)
    },
    fmtRMB(row, column, cellValue) {
      return cellValue + ' 元'
    },
    handleGoKaipiao(row) {
      console.log('点击开票 row:')
      console.log(row)
      this.todoCommit.recordId = row.recordId
      this.todoCommit.customerType = row.customerType
      this.todoCommit.form.customerName = row.customerName
      this.todoCommit.form.customerEntTaxId = row.customerEntTaxId
      this.todoCommit.form.address = row.address
      this.todoCommit.form.bankName = row.bankName
      this.todoCommit.form.bankAccountNo = row.bankAccountNo
      this.todoCommit.form.interactType = row.interactType
      this.todoCommit.form.customerEmail = row.interactTypeDetail
      this.todoCommit.form.customerMobile = row.interactTypeDetail
      this.todoCommit.form.remark = row.remark
      this.todoCommit.form.totalAmountTaxes = row.totalAmountTaxes
      this.todoCommit.form.interactTypeDetail = row.interactTypeDetail
      this.todoCommit.dialogVisible = true
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      console.log('多选表格行 改变：')
      console.log(this.multipleSelection)
    },
    toggleSelection() {
      this.$refs.multipleTable.clearSelection()
      console.log('多选表格行 全部取消')
      console.log(this.multipleSelection)
    },
    handleDelete() {
      this.callDeleteInvoiceTodo()
    },
    handleSizeChange(val) {
      this.callGetInvoiceTodo(1, val)
    },
    handleCurrentChange(val) {
      this.callGetInvoiceTodo(val, this.pagination.pageSize)
    },
    handleTodoInvoiceDetail() {
      let recordId = this.todoCommit.recordId
      console.log('待开发票详细信息 参数：')
      console.log('recordId:' + recordId)
      getInvoiceTodoDetail(recordId)
          .then((val) => {
            this.todoInvoiceDetail.recordId = recordId
            this.todoInvoiceDetail.productList = val.data
            this.todoInvoiceDetail.dialogVisible = true
          })
          .catch((err) => {
            this.$message.error(err)
          })
    },
    handleTodoCommitOk() {
      this.$refs['todoCommitForm'].validate((valid) => {
        if (valid) {
          let recordId = this.todoCommit.recordId
          let interactType = this.todoCommit.form.interactType
          let interactTypeDetail = ''
          let TTLX = this.todoCommit.customerType
          let SPF_MC = this.todoCommit.form.customerName
          let SPF_DH = this.todoCommit.form.customerMobile
          let SPF_DZ = this.todoCommit.form.address
          let SPF_YHZH = this.todoCommit.form.bankAccountNo
          let SPF_KHHMC = this.todoCommit.form.bankName
          if (this.todoCommit.form.interactType === 1) {
            interactTypeDetail = this.todoCommit.form.customerEmail
          } else if (this.todoCommit.form.interactType === 2) {
            interactTypeDetail = this.todoCommit.form.customerMobile
          }
          getInvoiceTodoCmdParam(recordId)
              .then((val) => {
                let company = JSON.parse(cache.getSession('company'))
                val.data.cmdParamObject.REQUEST_COMMON_FPKJ.SBBH = company.defaultDeviceInfo.taxDiscId
                val.data.cmdParamObject.REQUEST_COMMON_FPKJ.SBLX = company.defaultDeviceInfo.deviceType
                val.data.cmdParamObject.TTLX = TTLX
                val.data.cmdParamObject.SPF_MC = SPF_MC
                val.data.cmdParamObject.SPF_DH = SPF_DH
                val.data.cmdParamObject.SPF_DZ = SPF_DZ
                val.data.cmdParamObject.SPF_YHZH = SPF_YHZH
                val.data.cmdParamObject.SPF_KHHMC = SPF_KHHMC
                val.data.cmdParamObject.REQUEST_COMMON_FPKJ.KPR = this.userName
                return invoiceTodoCommit({
                  interactType: interactType,
                  interactTypeDetail: interactTypeDetail,
                  cmdParam: val.data.cmdParamObject,
                  todoRecordId: recordId
                })
              })
              .then((val) => {
                this.callGetInvoiceTodo(
                    this.pagination.currentPage,
                    this.pagination.pageSize
                )
                this.todoCommit.dialogVisible = false
                this.$message.success(val.msg)
              })
              .catch((err) => {
                this.$message.error(err)
              })
        } else {
          this.$message.error('输入信息不合法，请检查您的输入信息！')
          return false
        }
      })
    },
    handleTodoCommitCancel() {
      this.todoCommit.dialogVisible = false
    },
    /**
     * 分页查询待开发票
     * @param {Number} pageNum :  当前页码  默认为1
     * @param {Number} pageSize : 每页数量  默认为10
     */
    callGetInvoiceTodo(pageNum = 1, pageSize = 10) {
      getInvoiceTodo({
        customerName: this.searchText,
        status: this.selectStatus,
        pageNum: pageNum,
        pageSize: pageSize
      })
          .then((val) => {
            console.log('数据显示')
            console.log(val)
            this.pagination.total = val.data.total
            this.pagination.pageSize = val.data.size
            this.pagination.currentPage = val.data.current
            this.tableData = val.data.records
          })
          .catch((err) => {
            this.$message.error(err)
          })
    },
    /**
     * 待开发票删除
     */
    callDeleteInvoiceTodo() {
      if (this.multipleSelection.length > 0) {
        deleteInvoiceTodo(this.multipleSelection)
            .then((val) => {
              for (let index = 0; index < rowList.length; index++) {
                const element = rowList[index]
                if (this.tableData.indexOf(element) != -1) {
                  this.tableData.splice(index, 1)
                }
              }
              this.$message.success(val.msg)
            })
            .catch((err) => {
              this.$message.error(err)
            })
      }
    },
    // 显示二维码
    showScanCode() {
      // this.$refs.invoiceQrCode.getCompanyInfo(this.companyName, this.companyTaxId)
      this.isScanInvoice = true
    },
    // 二维码隐藏
    qrcodeShow() {
      this.isScanInvoice = false
    },
    qrcodeDownload() {
      this.$refs.invoiceQrCode.qrCodeDownLoad()
    },
    qrCodePrint() {
      this.$refs.invoiceQrCode.qrCodePrint()
    },
  },
}
</script>
<style scoped>
@page {
  size: auto; /* auto is the initial value */
  margin-: 3mm; /* this affects the margin in the printer settings */
}

html {
  background-color: #ffffff;
  margin: 0; /* this affects the margin on the html before sending to printer */
}

body {
  border: solid 1px blue;
  margin: 10mm 15mm 10mm 15mm; /* margin you want for the content */
}
</style>
