<template>
  <div v-loading="loading" element-loading-text="拼命加载中......请稍等">
    <el-form label-position="top" ref="form" style="width: 100%">
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="交易完成起始日期：">
            <el-date-picker v-model="search.beginDate" type="date" :clearable="false" 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.endDate" type="date" :clearable="false" placeholder="选择日期"
                            style="width: 100%">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="6">
          <el-form-item>
                        <span slot="label" style="color: #909399">
                            <span>&nbsp;&nbsp;</span>
                        </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-row :gutter="10">
        <el-col :span="6">
          <el-form-item>
            <el-select v-model="search.payType" clearable placeholder="请选择支付方式" style="width: 100%">
              <el-option v-for="item in payTypeOptions" :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>
            <el-select v-model="search.transStatus" clearable placeholder="请选择交易状态" style="width: 100%">
              <el-option v-for="item in transStatusOptions" :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>
            <el-input v-model="search.productName" clearable placeholder="请输入...">
              <template slot="prepend">商品名称</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <br/>
    <el-container>
      <el-table ref="searchResultMultipleTable" :data="search.resultList" border stripe style="width: 100%"
                max-height="500px" :height="tableHeight">
        <el-table-column type="index" :index="pageIndex" align="center" label="序号" width="50"></el-table-column>
        <el-table-column prop="productName" label="产品名称" width="180" show-overflow-tooltip></el-table-column>
        <el-table-column prop="productDesc" label="产品说明" width="180" show-overflow-tooltip></el-table-column>
        <el-table-column prop="oriPrice" label="原价" width="100" show-overflow-tooltip
                         :formatter="fmtPrice"></el-table-column>
        <el-table-column prop="favouredPrice" label="优惠后价格" width="100" show-overflow-tooltip
                         :formatter="fmtPrice"></el-table-column>
        <el-table-column prop="transAmt" label="金额" width="100" show-overflow-tooltip
                         :formatter="fmtPrice"></el-table-column>
        <el-table-column prop="payType" label="支付方式" width="80" show-overflow-tooltip
                         :formatter="fmtPayType"></el-table-column>
        <el-table-column prop="payTime" label="支付时间" width="150" show-overflow-tooltip></el-table-column>
        <el-table-column prop="transStatus" label="状态" width="70" show-overflow-tooltip
                         :formatter="fmtTransStatus"></el-table-column>
        <el-table-column prop="transErrorMsg" label="状态说明" :formatter="getInfoStatus" show-overflow-tooltip></el-table-column>
        <el-table-column prop="invoiceReqFlowNo" label="开票请求流水号" width="160" show-overflow-tooltip></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="150" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="100">
          <template slot-scope="scope">
            <el-button v-if="scope.row.invoiceReqFlowNo == null" @click="onCreateInvoiceDialogShow(scope.row)"
                       type="primary" size="small">开具发票
            </el-button>
            <el-button v-else @click="getInvoiceInfo(scope.row)" type="primary"
                       size="small">发票查看
            </el-button>
          </template>
        </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 @size-change="handleSearchResultSizeChange" @current-change="handleSearchResultCurrentChange"
                         :current-page="search.resultPagination.currentPage"
                         :page-sizes="search.resultPagination.pageSizes" :page-size="search.resultPagination.pageSize"
                         layout="total, sizes, prev, pager, next"
                         :total="search.resultPagination.total"></el-pagination>
        </div>
      </el-col>
    </el-row>
    <el-dialog title="开具发票" :visible.sync="createInvoiceDialog.visible" center :close-on-press-escape="false"
               :close-on-click-modal="false">
      <div v-loading="createInvoiceDialog.loading" element-loading-text="拼命加载中......请稍等">
        <div>
          <div style="display: flex; flex-direction: column; justify-content: center">
            <div style="display: flex; flex: 1; align-items: center; margin-bottom: 5px">
                <span><span style="color: red">*</span>
                企业名称：
              </span>
              <el-input v-model="entName" style="width:300px"></el-input>
            </div>
            <div style="display: flex; flex: 1; align-items: center; margin-bottom: 5px">
                <span><span style="color: red">*</span>
                企业税号：
              </span>
              <el-input v-model="entTaxId" style="width:300px"></el-input>
            </div>
            <div style="display: flex; flex: 1; align-items: center; margin-bottom: 5px">
                <span>
                联系电话：
              </span>
              <el-input v-model="entPhone" style="width:300px"></el-input>
            </div>
            <div style="display: flex; flex: 1; align-items: center; margin-bottom: 5px">
                <span>
                地址：
              </span>
              <el-input v-model="entAddress" style="width:300px"></el-input>
            </div>
            <div style="display: flex; flex: 1; align-items: center; margin-bottom: 5px">
                <span>
                开户银行：
              </span>
              <el-input v-model="bankName" style="width:300px"></el-input>
            </div>
            <div style="display: flex; flex: 1; align-items: center; margin-bottom: 5px">
                <span>
                银行账号：
              </span>
              <el-input v-model="bankAccountNumber" style="width:300px"></el-input>
            </div>
            <div style="display: flex; flex: 1; align-items: center; margin-bottom: 10px">
                <span>
                发票种类：
              </span>
              <el-select v-model="createInvoiceDialog.form.invoiceCategory" placeholder="发票种类" style="width: 200px">
                <el-option v-for="item in invoiceCategoryOptions" :key="item.value" :label="item.label"
                           :value="item.value" :disabled="item.disabled"></el-option>
              </el-select>
            </div>
            <div style="display: flex; flex: 1; align-items: center; margin-bottom: 10px">
                <span>
                发票交付方式：
              </span>
              <el-radio-group v-model="createInvoiceDialog.form.interactType">
                <el-radio :label="1">邮箱</el-radio>
                <el-radio :label="2">短信</el-radio>
              </el-radio-group>
            </div>
            <div style="display: flex; flex: 1; align-items: center; margin-bottom: 5px"
                 v-if="createInvoiceDialog.form.interactType === 2">
                <span>
                发票交付手机号码：
              </span>
              <el-input v-model="createInvoiceDialog.form.interactTypeDetail" style="width:300px"></el-input>
            </div>
            <div style="display: flex; flex: 1; align-items: center; margin-bottom: 5px"
                 v-if="createInvoiceDialog.form.interactType === 1">
                <span>
                发票交付邮箱账户：
              </span>
              <el-input v-model="createInvoiceDialog.form.interactTypeDetail" style="width:300px"></el-input>
            </div>
          </div>
          <div style="display: flex; justify-content: flex-end">
            <el-button type="primary" @click="onCreateInvoiceSubmit('createInvoiceForm')">立即提交</el-button>
            <el-button @click="createInvoiceDialog.visible = false">取 消</el-button>
          </div>
        </div>
        <!--        <el-form :model="createInvoiceDialog.form" :rules="createInvoiceDialog.rules" ref="createInvoiceForm"-->
        <!--                 label-width="180px">-->
        <!--          <el-form-item style="display: flex; align-items: center" label="发票抬头：">-->
        <!--            <el-card style="margin-left: -180px">-->
        <!--              <div style="display: flex; flex-direction: column">-->
        <!--                <span>抬头名称：{{ entName }}</span>-->
        <!--                <span>抬头税号：{{ entTaxId }}</span>-->
        <!--                <span>地址：{{ entAddress }}</span>-->
        <!--                <span>电话：{{ entPhone }}</span>-->
        <!--                <span>开户行：{{ bankName }}</span>-->
        <!--                <span>账号：{{ bankAccountNumber }}</span>-->
        <!--              </div>-->
        <!--            </el-card>-->
        <!--          </el-form-item>-->
        <!--          <el-form-item label="发票种类：" prop="invoiceCategory">-->
        <!--            <el-select v-model="createInvoiceDialog.form.invoiceCategory" placeholder="发票种类" style="width: 200px">-->
        <!--              <el-option v-for="item in invoiceCategoryOptions" :key="item.value" :label="item.label"-->
        <!--                         :value="item.value" :disabled="item.disabled"></el-option>-->
        <!--            </el-select>-->
        <!--          </el-form-item>-->
        <!--          <el-form-item label="发票交付方式：" prop="interactType">-->
        <!--            <el-radio-group v-model="createInvoiceDialog.form.interactType">-->
        <!--              <el-radio :label="1">邮箱</el-radio>-->
        <!--              <el-radio :label="2">短信</el-radio>-->
        <!--            </el-radio-group>-->
        <!--          </el-form-item>-->
        <!--          <el-form-item v-if="createInvoiceDialog.form.interactType==2" label="发票交付手机号码：" prop="interactTypeDetail">-->
        <!--            <el-input v-model="createInvoiceDialog.form.interactTypeDetail"></el-input>-->
        <!--          </el-form-item>-->
        <!--          <el-form-item v-if="createInvoiceDialog.form.interactType==1" label="发票交付邮箱账户：" prop="interactTypeDetail">-->
        <!--            <el-input v-model="createInvoiceDialog.form.interactTypeDetail" autocomplete="off"></el-input>-->
        <!--          </el-form-item>-->
        <!--          <div v-if="createInvoiceDialog.form.invoiceCategory==2">-->
        <!--            <el-form-item label="企业联系电话：" prop="contactPhone">-->
        <!--              <el-input v-model="createInvoiceDialog.form.contactPhone"></el-input>-->
        <!--            </el-form-item>-->
        <!--            <el-form-item label="企业地址：" prop="address">-->
        <!--              <el-input v-model="createInvoiceDialog.form.address"></el-input>-->
        <!--            </el-form-item>-->
        <!--            <el-row>-->
        <!--              <el-col :span="11">-->
        <!--                <el-form-item label="企业开户银行：" prop="bankName">-->
        <!--                  <el-input v-model="createInvoiceDialog.form.bankName" style="width:100%"></el-input>-->
        <!--                </el-form-item>-->
        <!--              </el-col>-->
        <!--              <el-col :span="13">-->
        <!--                <el-form-item label="企业银行账号：" prop="bankAccountNo">-->
        <!--                  <el-input v-model="createInvoiceDialog.form.bankAccountNo"></el-input>-->
        <!--                </el-form-item>-->
        <!--              </el-col>-->
        <!--            </el-row>-->
        <!--          </div>-->
        <!--          <br>-->
        <!--          <el-form-item>-->
        <!--            <el-button type="primary" @click="onCreateInvoiceSubmit('createInvoiceForm')">立即提交</el-button>-->
        <!--            <el-button @click="createInvoiceDialog.visible = false">取 消</el-button>-->
        <!--          </el-form-item>-->
        <!--        </el-form>-->
      </div>
    </el-dialog>
  </div>
</template>

<script>

import MarketingService from '@/api/marketing'
import DateHelper from '@/utils/date'
import cache from '@/utils/cache'
import { AxiosRequestByBearer } from '@/data/axios_request'

// 支付方式选项列表
const payTypeOptions = [
  {
    value: 'W01',
    label: '微信',
  },
  {
    value: 'A01',
    label: '支付宝',
  },
]

// 交易状态选项列表
const transStatusOptions = [
  {
    value: '1',
    label: '未付款',
  },
  {
    value: '2',
    label: '已付款',
  },
]

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

export default {
  name: 'TransRecords',
  components: {},
  data() {
    return {
      loading: false,
      payTypeOptions: payTypeOptions,
      transStatusOptions: transStatusOptions,
      invoiceCategoryOptions: invoiceCategoryOptions,
      entTaxId: '-',
      entName: '-',
      device: '-',
      taxDiscId: '-',
      deviceType: '-',
      search: {
        productName: '',
        payType: '',
        transStatus: '',
        beginDate: DateHelper.LocalCurrentMonthStart(),
        endDate: DateHelper.LocalCurrentMonthEnd(),
        resultList: [],
        resultMultipleSelection: [],
        resultPagination: {
          currentPage: 1,
          pageSizes: [10, 30, 50, 100],
          pageSize: 10,
          total: 0,
        },
      },
      createInvoiceDialog: {
        visible: false,
        loading: false,
        rowData: null,
        form: {
          invoiceCategory: 1,
          interactType: 1,
          interactTypeDetail: '',
          contactPhone: '',
          address: '',
          bankName: '',
          bankAccountNo: '',
        },
        rules: {
          invoiceCategory: [
            {
              required: true,
              message: '请选择发票种类',
              trigger: 'change',
            },
          ],
          interactType: [
            {
              required: true,
              message: '请选择发票交付方式',
              trigger: 'change',
            },
          ],
          interactTypeDetail: [
            {
              required: true,
              message: '请输入发票交付的电话号码或邮箱',
              trigger: 'change',
            },
          ],
          contactPhone: [
            {
              required: true,
              message: '请输入企业联系电话',
              trigger: 'change',
            },
          ],
          address: [
            {
              required: true,
              message: '请输入企业地址',
              trigger: 'change',
            },
          ],
          bankName: [
            {
              required: true,
              message: '请输入企业开户银行',
              trigger: 'change',
            },
          ],
          bankAccountNo: [
            {
              required: true,
              message: '请输入企业银行账号',
              trigger: 'change',
            },
          ],
        },
      },
      bankName: '',
      bankAccountNumber: '',
      entAddress: '',
      entPhone: '',
      token: '',
      tableHeight: ''
    }
  },
  created() {
    this.tableHeight = window.innerHeight - 250
    this.token = cache.getToken()
    const company = JSON.parse(cache.getSession('company'))
    this.entTaxId = company.entTaxId
    this.entName = company.entName
    this.bankName = company.bankName
    this.bankAccountNumber = company.bankAccountNumber
    this.entAddress = company.entAddress
    this.entPhone = company.entPhone
    this.device = company.defaultDeviceInfo.deviceLabel
    this.taxDiscId = company.defaultDeviceInfo.taxDiscId
    this.deviceType = company.defaultDeviceInfo.deviceType
    this.callFindAllTrans(
        this.search.resultPagination.currentPage,
        this.search.resultPagination.pageSize
    )
  },
  mounted() {
    this.tableHeight = window.innerHeight - 250
    window.onresize = () => {
      return (() => {
        this.tableHeight = window.innerHeight - 250
      })()
    }
  },
  methods: {
    pageIndex(index) {
      let currentPage = this.search.resultPagination.currentPage // 当前页码，具体看组件取值
      let pageSize = this.search.resultPagination.pageSize // 每页条数，具体是组件取值
      return index + 1 + (currentPage - 1) * pageSize
    },
    fmtPrice(row, column, cellValue) {
      return cellValue != null ? '￥' + cellValue : ''
    },
    fmtPayType(row, column, cellValue) {
      let result = cellValue
      for (const item of payTypeOptions) {
        if (item.value === cellValue) {
          result = item.label
          break
        }
      }
      return result
    },
    fmtTransStatus(row, column, cellValue) {
      let result = cellValue
      for (const item of transStatusOptions) {
        if (item.value === cellValue) {
          result = item.label
          break
        }
      }
      return result
    },
    handleSearch() {
      this.callFindAllTrans(1, this.search.resultPagination.pageSize)
    },
    handleResetSearch() {
      this.search.productName = ''
      this.search.payType = ''
      this.search.transStatus = ''
      this.search.beginDate = ''
      this.search.endDate = ''
    },
    handleSearchResultSizeChange(val) {
      this.callFindAllTrans(1, val)
    },
    handleSearchResultCurrentChange(val) {
      this.callFindAllTrans(val, this.search.resultPagination.pageSize)
    },
    onCreateInvoiceDialogShow(row) {
      this.createInvoiceDialog.form.invoiceCategory = 1
      this.createInvoiceDialog.form.interactType = 1
      this.createInvoiceDialog.form.interactTypeDetail = ''
      this.createInvoiceDialog.rowData = JSON.parse(JSON.stringify(row))
      this.createInvoiceDialog.visible = true
    },
    onCreateInvoiceSubmit(formName) {
      if (!this.entName) {
        this.$message({
          message: '企业名称不能为空！',
          type: 'warning'
        })
        return
      }
      if (!this.entTaxId) {
        this.$message({
          message: '企业税号不能为空！',
          type: 'warning'
        })
        return
      }
      if (this.createInvoiceDialog.form.interactType === 1) {
        if (!this.createInvoiceDialog.form.interactTypeDetail) {
          this.$message({
            message: '发票交付邮箱不能为空！',
            type: 'warning'
          })
          return
        }
      }
      if (this.createInvoiceDialog.form.interactType === 2) {
        if (!this.createInvoiceDialog.form.interactTypeDetail) {
          this.$message({
            message: '发票交付手机号码不能为空！',
            type: 'warning'
          })
          return
        }
      }
      let _this = this
      _this.createInvoiceDialog.loading = true
      MarketingService.transInvoiceCommit({
        transId: _this.createInvoiceDialog.rowData.transId,
        customerType: 2, // 企业客户
        interactType:
        _this.createInvoiceDialog.form.interactType,
        interactTypeDetail:
        _this.createInvoiceDialog.form.interactTypeDetail,
        invoiceCategory:
        _this.createInvoiceDialog.form.invoiceCategory,
        customerName: _this.entName,
        customerEntTaxId: _this.entTaxId,
        address: _this.entAddress,
        contactPhone:
        _this.entPhone,
        bankName: _this.bankName,
        bankAccountNo:
        _this.bankAccountNumber,
      })
          .then((val) => {
            _this.$message.success(val.msg)
            _this.createInvoiceDialog.visible = false
          })
          .catch((error) => {
            _this.$message.error(error)
          })
          .finally(() => {
            _this.createInvoiceDialog.loading = false
          })
    },
    /**
     * 分页查询所有支付交易记录
     * @param {Number} pageNum : 当前页码
     * @param {Number} pageSize : 每页数量
     */
    callFindAllTrans(pageNum, pageSize) {
      let beginTime = this.search.beginDate
      let endTime = this.search.endDate

      if (!beginTime || !endTime) {
        this.$message.error(
            '起始日期与结束日期为必输项，请确定后重试！'
        )
        return false
      }

      beginTime = this.dateFormat(
          new Date(beginTime),
          'yyyy-MM-dd HH:mm:ss'
      )

      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
        }
      }

      MarketingService.findAllTrans({
        // entName: this.entName,
        entTaxId: this.entTaxId,
        // deviceType: this.deviceType,
        // taxDiscId: this.taxDiscId,
        productName: this.search.productName,
        payType: this.search.payType,
        transStatus: this.search.transStatus,
        payTimeBegin: beginTime,
        payTimeEnd: endTime,
        pageNum: pageNum,
        pageSize: pageSize,
      })
          .then((val) => {
            if (val.data) {
              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
            }
          })
          .catch((error) => {
            this.$message.error(error)
          })
    },
    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 getInvoiceInfo(row) {
      if (this.token) {
        this.loading = true
        const url = '/sys/invoiceExt/getResultData'
        let response = await AxiosRequestByBearer(
            url,
            this.token,
            {
              reqFlowNo: row.invoiceReqFlowNo
            },
            false,
            2
        )
        if (response) {
          if (response.code === 0) {
            this.loading = false
            if (response.data.invoiceStatus) {
              window.open(response.data.invoiceData.fileUrl + response.data.invoiceData.fileType)
            } else {
              this.$message.error('发票暂未开具成功，请稍后再查看！')
            }
          } else {
            this.loading = false
            this.$message.error(response.msg)
          }
        }
      }
    },
    // 处理状态信息
    getInfoStatus(row, column, cellValue) {
      if (row.invoiceReqFlowNo === null) {
        return cellValue
      } else {
        return '已提交开票'
      }
    }
  }
}
</script>
