<!--
  @description: 标书费开票管理
  @Modifier: sunxinman/haofengxian
  @routerPath: /fee/tenderFeeInvoiceManage
  @date: 2020/03/20-11:18
-->
<template>
  <div>
    <table-crud
      ref="tableCrud"
      :menu="true"
      :search-form="searchForm"
      search-label-width="110px"
      @on-load="loadData"
    >
      <template v-slot:header>
        标书费开票管理
      </template>
      <template v-slot:search="search">
        <!-- 标段（包）编号 -->
        <el-form-item ref="packNo" label="标段（包）编号" prop="packNo">
          <el-input v-model.trim="searchForm.packNo" placeholder="标段（包）编号" style="width:228px" @keyup.enter.native="search.onSearch" />
        </el-form-item>
        <!-- 投标人 -->
        <el-form-item ref="supplierName" label="投标人" prop="supplierName">
          <el-input v-model.trim="searchForm.supplierName" placeholder="投标人" style="width:228px" @keyup.enter.native="search.onSearch" />
        </el-form-item>
        <!-- 标段（包）名称 -->
        <el-form-item ref="packName" label="标段（包）名称" prop="packName">
          <el-input v-model.trim="searchForm.packName" placeholder="标段（包）名称" style="width:228px" @keyup.enter.native="search.onSearch" />
        </el-form-item>
        <!-- 项目名称 -->
        <el-form-item ref="tenderName" label="项目名称" prop="tenderName">
          <el-input v-model.trim="searchForm.tenderName" placeholder="项目名称" style="width:228px" @keyup.enter.native="search.onSearch" />
        </el-form-item>
        <!-- 项目编号 -->
        <el-form-item ref="tenderNo" label="项目编号" prop="tenderNo">
          <el-input v-model.trim="searchForm.tenderNo" placeholder="项目编号" style="width:228px" @keyup.enter.native="search.onSearch" />
        </el-form-item>
        <!-- 项目经理 -->
        <el-form-item label="项目经理" prop="tenderManager">
          <el-input v-model.trim="searchForm.tenderManager" placeholder="项目经理" style="width:228px" @keyup.enter.native="search.onSearch" />
        </el-form-item>
        <!-- 业务部门 -->
        <el-form-item ref="department" label="业务部门" prop="department">
          <el-input v-model.trim="searchForm.department" placeholder="业务部门" style="width:228px" @keyup.enter.native="search.onSearch" />
        </el-form-item>
        <!--开票类型-->
        <el-form-item ref="feeType" label="开票类型" prop="feeType">
          <el-select v-model="searchForm.invoiceType" placeholder="请选择" style="width:228px">
            <el-option
              v-for="(item,index) in invoiceTypeList"
              :key="index"
              :label="item.typename"
              :value="item.typecode"
            />
          </el-select>
        </el-form-item>
        <!-- 开票状态 -->
        <el-form-item label="开票状态" prop="invoiceStatus">
          <el-select v-model="searchForm.invoiceStatus" placeholder="请选择" style="width:228px">
            <el-option
              v-for="(item,index) in docInvoiceStatusList"
              :key="index"
              :label="item.typename"
              :value="item.typecode"
            />
          </el-select>
        </el-form-item>
        <!--费用类型-->
        <el-form-item ref="feeType" label="费用类型" prop="feeType">
          <el-select v-model="searchForm.feeType" placeholder="请选择" style="width:228px">
            <el-option
              v-for="(item,index) in costTypeList"
              :key="index"
              :label="item.typename"
              :value="item.typecode"
            />
          </el-select>
        </el-form-item>
        <!-- 开票金额 -->
        <el-form-item ref="documentPrice" label="开票金额（元）" prop="documentPrice">
          <el-input v-model.trim="searchForm.documentPrice" placeholder="开票金额（元）" style="width:228px" @keyup.enter.native="search.onSearch" />
        </el-form-item>
        <!-- 到账日期 -->
        <el-form-item ref="accountingTime" label="到账日期" prop="accountingTime">
          <el-date-picker
            v-model="searchForm.accountingTime"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width:228px"
            @change="changeAccountingTime"
          />
        </el-form-item>
        <!-- 开票日期 -->
        <el-form-item ref="invoiceTime" label="开票日期" prop="invoiceTime">
          <el-date-picker
            v-model="searchForm.invoiceTime"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width:228px"
            @change="changeInvoiceTime"
          />
        </el-form-item>
      </template>
      <template v-slot:menuLeft>
        <el-row class="table-alert-info">
          <el-col>
            <el-button type="primary" @click="batchInvoice">
              批量电子开票
            </el-button>
            <el-button type="primary" plain @click="exportInvoiceRecordList('00')">
              导出开票信息
            </el-button>
            <el-button type="primary" plain @click="importTenderFeeInvoice('00')">
              导入开票信息
            </el-button>
            <el-button type="primary" plain @click="exportInvoiceRecordList('01')">
              导出发票邮寄信息
            </el-button>
            <el-button type="primary" plain @click="importTenderFeeInvoice('01')">
              导入发票邮寄信息）
            </el-button>
          </el-col>
          <el-col>
            <el-link :underline="false">
              单页开票金额<span class="sum_color">{{ statistics.pageDocumentPrice }}</span>元
            </el-link>
            <el-link :underline="false">
              单页开票不含税金额<span class="sum_color">{{ statistics.pageNoTaxRatePrice }}</span>元
            </el-link>
            <el-link :underline="false">
              单页开票税额<span class="sum_color">{{ statistics.pageTaxAmount }}</span>元
            </el-link>
            <el-link :underline="false">
              总开票金额<span class="sum_color">{{ statistics.totalDocumentPrice }}</span>元
            </el-link>
            <el-link :underline="false">
              总页开票不含税金额<span class="sum_color">{{ statistics.totalNoTaxRatePrice }}</span>元
            </el-link>
            <el-link :underline="false">
              总页开票税额<span class="sum_color">{{ statistics.totalTaxAmount }}</span>元
            </el-link>
          </el-col>
          <el-col>
            <el-link :underline="false">
              已选中<span class="sum_color">{{ checkedTr.length }}</span>条
            </el-link>
            <el-link :underline="false">
              已选中开票金额<span class="sum_color">{{ moneyFormat(selectDocumentPrice) }}</span>元
            </el-link>
            <el-link :underline="false">
              已选中不含税金额<span class="sum_color">{{ moneyFormat(selectNoTaxRatePrice) }}</span>元
            </el-link>
            <el-link :underline="false">
              已选中税额<span class="sum_color">{{ moneyFormat(selectTaxAmount) }}</span>元
            </el-link>
          </el-col>
        </el-row>
      </template>
      <template v-slot:GXTable>
        <el-table
          ref="invoiceListTable"
          v-loading="loading"
          :row-key="getRowKeys"
          :data="tableData"
          row-class-name="row-line-height-cell16"
          size="mini"
          @selection-change="selectionChange"
        >
          <el-table-column
            :reserve-selection="true"
            disabled="true"
            type="selection"
            fixed="left"
            width="55"
            align="center"
          />
          <el-table-column
            type="index"
            label="序号"
            fixed="left"
            width="60px"
            align="center"
          />
          <!-- 招标项目编号/名称  -->
          <el-table-column

            fixed="left"
            label="招标项目编号/名称"
            min-width="260"
          >
            <template slot-scope="scope">
              <p>{{ scope.row.tenderNo }}</p>
              <p>{{ scope.row.tenderName }}</p>
            </template>
          </el-table-column>
          <!-- 标段（包）编号/名称 -->
          <el-table-column

            header-align="center"
            label="标段（包）编号/名称"
            prop="packNo"
            fixed="left"
            min-width="260"
          >
            <template slot-scope="scope">
              <p>{{ scope.row.packNo }}</p>
              <p>{{ scope.row.packName }}</p>
            </template>
          </el-table-column>
          <!-- 投标人 -->
          <el-table-column

            header-align="center"
            prop="supplierName"
            label="投标人"
            min-width="160"
          />
          <!-- 发票号码 -->
          <el-table-column
            header-align="center"
            label="发票号码"
            prop="invoiceNo"
            align="center"
            min-width="140"
          />
          <!-- 开票金额（元） -->
          <el-table-column
            header-align="center"
            label="开票金额（元）"
            prop="documentPrice"
            align="right"
            width="110"
          />
          <!-- 不含税金额（元） -->
          <el-table-column
            header-align="center"
            label="不含税金额（元）"
            prop="noTaxRatePrice"
            align="right"
            width="130"
          />
          <!-- 税率 -->
          <el-table-column
            header-align="center"
            label="税率 (%)"
            prop="documentRate"
            align="right"
            width="90"
          />
          <!-- 税额 -->
          <el-table-column
            header-align="center"
            label="税额 （元）"
            prop="taxAmount"
            align="right"
            min-width="90"
          />
          <!-- 开票类型 -->
          <el-table-column
            :formatter="formatInvoiceType"
            label="开票类型"
            prop="invoiceType"
            align="center"
            width="120"
          />
          <!-- 费用类型 -->
          <el-table-column
            :formatter="formatFeeType"
            header-align="center"
            label="费用类型"
            prop="feeType"
            align="left"
            width="120"
          />
          <!-- 业务部门 -->
          <el-table-column

            header-align="center"
            label="业务部门"
            prop="department"
            align="left"
            min-width="160"
          />
          <!-- 到账时间 -->
          <el-table-column
            header-align="center"
            label="到账时间"
            prop="accountingTime"
            align="left"
            width="140"
          />
          <!-- 开票状态 -->
          <el-table-column
            :formatter="formatInvoiceStatus"
            header-align="center"
            label="开票状态"
            prop="invoiceStatus"
            align="center"
            min-width="90"
          />
          <!-- 开票时间 -->
          <el-table-column
            header-align="center"
            label="开票时间"
            prop="invoiceTime"
            align="center"
            width="140"
          />
          <!-- 项目经理 -->
          <el-table-column
            label="项目经理"
            prop="tenderManager"
            align="center"
            min-width="80"
          />
          <!-- 操作 -->
          <el-table-column
            header-align="center"
            label="操作"
            fixed="right"
            width="200"
          >
            <template slot-scope="scope">
              <el-link
                v-if="scope.row.invoiceStatus==='00'"
                type="primary"
                @click.stop="invoice(scope.row)"
              >
                [开票]
              </el-link>
              <el-link
                v-if="scope.row.invoiceStatus==='02'"
                type="primary"
                @click.stop="invoiceChange(scope.row)"
              >
                [换票红冲]
              </el-link>
              <el-link
                v-if="scope.row.invoiceStatus==='02'"
                type="primary"
                @click.stop="downloadInvoice(scope.row)"
              >
                [下载发票]
              </el-link>
              <el-link
                type="primary"
                @click.stop="invoiceView(scope.row)"
              >
                [查看]
              </el-link>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </table-crud>
    <!--导入邮寄信息-->
    <importTenderFeeInvoice ref="importTenderFeeInvoice" />
  </div>
</template>
<script>
/* 接口*/
import { queryInvoiceList, queryInvoiceStatistics, electronicBllingByFeeDocId, exportInvoiceList, updatefeeDocInfo } from '@api/fee/docfee'
import { downLoadFileUrl, getFileDetail } from '@/api/common/uploadCenter'
/* 公用方法*/
import { filterDictText, moneyFormat, download } from '@assets/js/utils'// 常用方法
/* 混合开发方法-参数字段*/
import { TenderFeeGroupMixin } from '../mixins/tenderFeeGroupMixin'
/* 组件*/
import importTenderFeeInvoice from './importTenderFeeInvoice-dialog'// 标书费开票管理-标书费开票上传/标书费开票邮寄信息上传

export default {
  name: 'TenderFeeIncoiceManageList',
  components: {
    importTenderFeeInvoice// 标书费开票管理-标书费开票上传/标书费开票邮寄信息上传
  },
  mixins: [TenderFeeGroupMixin],
  data() {
    return {
      /* 字典信息-start */
      invoiceTypeList: [], // 开票类型
      /* 字典信息-end */
      // 获取row的key值
      getRowKeys(row) {
        return row.feeDocId
      },
      downLoadFileUrl: downLoadFileUrl,
      moneyFormat: moneyFormat, // 金额添加千分位
      loading: true,
      selectDocumentPrice: 0, // 已选中开票金额
      selectNoTaxRatePrice: 0, // 已选中不含税金额
      selectTaxAmount: 0, // 已选中税额
      // 开标费用统计数据
      statistics: {
        pageDocumentPrice: 0, // 单页开票金额
        pageNoTaxRatePrice: 0, // 单页开票不含税金额
        pageTaxAmount: 0, // 单页开票税额
        totalDocumentPrice: 0, // 总开票金额
        totalNoTaxRatePrice: 0, // 总开票不含税金额
        totalTaxAmount: 0 // 总页开票税额
      },
      // 搜索
      searchForm: {
        accountingTime: '', // 到账时间
        invoiceTime: '', // 开票时间
        accountingEndTime: '', // 到账结束时间
        accountingStartTime: '', // 到账开始时间
        department: '', // 业务部门
        documentPrice: '', // 开票金额
        invoiceType: '', // 开票类型 00普票 01开票
        feeType: '', // 费用类型: 00资格预审文件费 01招标文件费
        invoiceEndTime: '', // 开票结束时间
        invoiceStartTime: '', // 开票开始时间
        invoiceStatus: '', // 开票状态: 00 未开票 01已开票 02 开票失败 03 开票申请中 04已电子开票重开 05电子红冲中 06已电子红冲 07电子红冲失败
        packName: '', // 标段名称
        packNo: '', // 标段编号
        supplierName: '', // 投标人
        tenderManager: '', // 项目经理
        tenderName: '', // 项目名称
        tenderNo: '' // 项目编号
      },
      tableData: [],
      checkedTr: [], // 批量电子开票存放数据
      downloadInvoiceFileUrl: '' // 电子发票下载url
    }
  },
  created() {
    this.initGroup()// 获取字典
  },
  methods: {
    // 获取字典方法
    initGroup() {
      const data = [
        'invoiceType' // 开票类型
      ]
      this.$store.dispatch('getGroupType', data).then(res => {
        Object.keys(res.bidTypeData).forEach((key) => {
          this[key] = res.bidTypeData[key]
        })
      })
    },
    // 标书费开票管理-开票记录列表
    loadData(params, callback) {
      this.$refs.invoiceListTable.clearSelection()
      queryInvoiceList(params).then(response => {
        this.loading = false
        this.tableData = response.data.records
        callback(response.data.total)
      }).catch(() => {
        this.loading = false
      })
      // 标书费开票管理-开票费用统计数据
      this.getInvoiceStatistics(params)
    },
    // 表格字典值替换文本-开票类型
    formatInvoiceType(row, column, cellValue) {
      return filterDictText(this.invoiceTypeList, cellValue)
    },
    // 标书费开票管理-开票费用统计数据
    getInvoiceStatistics(params) {
      queryInvoiceStatistics(params).then(response => {
        this.statistics = response.data
      }).catch(() => {
      })
    },
    // 到账时间
    changeAccountingTime(val) {
      if (val) {
        this.searchForm.accountingStartTime = this.$Moment(val[0]).format(this.momentDate)// 到账开始时间
        this.searchForm.accountingEndTime = this.$Moment(val[1]).format(this.momentDate)// 到账结束时间
      }
    },
    // 开票时间
    changeInvoiceTime(val) {
      if (val) {
        this.searchForm.invoiceStartTime = this.$Moment(val[0]).format(this.momentDate)//  开票开始时间
        this.searchForm.invoiceEndTime = this.$Moment(val[1]).format(this.momentDate)// 开票结束时间
      }
    },
    // 开票
    electronicBlling(feeDocIds) {
      const params = {
        feeDocIds
      }
      electronicBllingByFeeDocId(params).then(res => {
        this.$message.success(res.header.msg)
        // 获取列表信息
        this.$refs.tableCrud.onSearchChange()
        this.$refs.invoiceListTable.clearSelection()
      }).catch(() => {
      })
    },
    // 开票
    invoice(row) {
      this.$confirm('确认电子开票吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'confirmBtn',
        cancelButtonClass: 'cancelBtn',
        type: 'warning'
      }).then(() => {
        this.electronicBlling(row.feeDocId)
      })
    },
    // 批量电子开票
    batchInvoice() {
      if (!this.checkedTr.length) {
        this.$message({
          message: '请选择一条记录',
          type: 'warning'
        })
      } else {
        // 批量开票中不能同时出现两种及以上发票类型
        const rulsLength = this.checkedTr.filter(item => this.checkedTr[0].invoiceType !== item.invoiceType).length
        if (rulsLength > 0) {
          this.$alert('批量开票中不能同时出现两种及以上发票类型，请重新选择。', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          })
        } else {
          this.$confirm('确认批量电子开票吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            confirmButtonClass: 'confirmBtn',
            cancelButtonClass: 'cancelBtn',
            type: 'warning'
          }).then(() => {
            // 过滤 得到 00 未开票信息
            const feeDocIds = this.checkedTr.filter(row => row.invoiceStatus === '00').map(row => row.feeDocId).join(',')
            this.electronicBlling(feeDocIds)
          })
        }
      }
    },
    // 换票红冲
    invoiceChange(row) {
      this.$confirm('确认换票红冲,重新开票吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'confirmBtn',
        cancelButtonClass: 'cancelBtn',
        type: 'warning'
      }).then(() => {
        const data = {
          feeDocId: row.feeDocId
        }
        updatefeeDocInfo(data).then(res => {
          this.$refs.tableCrud.onSearchChange()
          this.$refs.invoiceListTable.clearSelection()
        })
      })
    },
    /*
     * 标书费开票管理-标书费开票导出/标书费开票邮寄信息导出
     * upType ：上传类型 00 标书费开票导出 01 标书费开票邮寄信息导出
    */
    exportInvoiceRecordList(upType) {
      if (!this.checkedTr.length) {
        this.$message({
          message: '请选择一条记录',
          type: 'warning'
        })
      } else {
        // upType = 01 标书费开票邮寄信息导出时 && 只能导出已开票信息 invoiceStatus = 02
        // upType = 00 标书费开票导出时 && 导出已选中的所有信息
        const feeDocIds = this.checkedTr.filter(row => upType === '01' && row.invoiceStatus === '02' || upType === '00').map(row => row.feeDocId).join(',')
        exportInvoiceList({ feeDocIds, upType }).then(res => {
          download(res, upType === '00' ? '标书费开票信息表.xls' : '标书费开票邮寄信息表.xls')
        }).catch(() => {
        })
      }
    },
    /*
     * 标书费开票管理-标书费开票上传/标书费开票邮寄信息上传
     * upType ：上传类型 00 标书费开票上传 01 标书费开票邮寄信息上传
    */
    importTenderFeeInvoice(upType) {
      this.$refs.importTenderFeeInvoice.openDialog(upType)
    },
    // 返回
    back() {
      this.$router.push({
        path: '/fee/tenderFeeManage'
      })
    },
    // 查看
    invoiceView(row) {
      this.$router.push({
        path: '/fee/tenderFeeInvoiceDetail',
        name: 'TenderFeeInvoiceDetail',
        params: {
          feeDocId: row.feeDocId
        }
      })
    },
    // 复选框事件
    selectionChange(val) {
      this.checkedTr = val
      this.handleDocumentPrice()
    },
    // 已选中开票金额/不含税金额/税额计算
    handleDocumentPrice() {
      let documentPrice = 0
      let noTaxRatePrice = 0
      let taxAmount = 0
      this.checkedTr.forEach(item => {
        documentPrice += Number(item.documentPrice) // 开票金额
        noTaxRatePrice += Number(item.noTaxRatePrice) // 不含税金额
        taxAmount += Number(item.taxAmount) // 税额
      })
      this.selectDocumentPrice = documentPrice.toFixed(2)
      this.selectNoTaxRatePrice = noTaxRatePrice.toFixed(2)
      this.selectTaxAmount = taxAmount.toFixed(2)
    },
    // 下载发票
    downloadInvoice(row) {
      const data = {
        bizId: row.feeDocId, // 业务主键Id
        fileType: 'invoiceFile'// 文件类型
      }
      let downLoadFileUrl = '' // 下载附件地址
      getFileDetail(data).then(response => {
        const fileData = response.data
        if (fileData && fileData.length > 0) {
          downLoadFileUrl = this.downLoadFileUrl + '?fileId=' + fileData[0].fileId + '&fileType=invoiceFile'
          window.location.href = downLoadFileUrl
        }
      }).catch(() => {
      })
    }
  }
}
</script>
<style lang="less" scoped>
</style>
