<template>
  <div class="my-invoice">
    <div class="my-invoice__header">
      <el-button type="primary" @click="apply">申请发票</el-button>
    </div>
    <div class="my-invoice__body">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column
          align="center"
          header-align="center"
          type="index"
          label="序号"
        />
        <el-table-column
          align="center"
          header-align="center"
          prop="invoiceTitle"
          label="发票抬头"
        >
        </el-table-column>
        <el-table-column
          align="center"
          header-align="center"
          prop="amount"
          label="开票金额"
        >
          <template slot-scope="scope">
            ￥{{ scope.row.amount | toFixed }}
          </template>
        </el-table-column>
        <el-table-column align="center" header-align="center" label="发票类型">
          <template slot-scope="scope">
            {{
              scope.row.type == 1
                ? "普通发票"
                : scope.row.type == 2
                ? "增值税专用发票"
                : ""
            }}
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" header-align="center" label="开票状态"
          ><template slot-scope="scope">
            {{
              scope.row.invoiceStatus == 1
                ? "未开票"
                : scope.row.invoiceStatus == 2
                ? "已开票"
                : scope.row.invoiceStatus == -1
                ? "已退票"
                : ""
            }}
          </template>
        </el-table-column> -->
        <el-table-column align="center" header-align="center" label="申请时间">
          <template slot-scope="scope">
            {{ $tools.timestampToTime(scope.row.applyTime, false, false) }}
          </template>
        </el-table-column>
        <el-table-column align="center" header-align="center" label="开票订单">
          <template slot-scope="scope">
            <div v-for="(item, index) in scope.row.orderList" :key="index">
              {{ index + 1 }}.{{ item.goodsName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" header-align="center" label="审核状态">
          <template slot-scope="scope">
            {{
              scope.row.periodStatus == 1
                ? "待审核"
                : scope.row.periodStatus == 3
                ? "通过"
                : scope.row.periodStatus == 2
                ? "驳回"
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column align="center" header-align="center" label="发票状态">
          <template slot-scope="scope">
            {{
              scope.row.invoiceStatus == 1
                ? "未开票"
                : scope.row.invoiceStatus == 2
                ? "已开票"
                : scope.row.invoiceStatus == -1
                ? "已退票"
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column align="center" header-align="center" label="操作">
          <template slot-scope="scope">
            <el-button
              @click.native.prevent="showDetail(scope.row)"
              type="text"
              size="small"
            >
              查看
            </el-button>
            <el-button
              v-if="
                scope.row.periodStatus == 3 &&
                (scope.row.invoiceStatus == 2 ||
                  scope.row.invoiceStatus == -1) &&
                scope.row.invoiceImg
              "
              @click.native.prevent="download(scope.row)"
              type="text"
              size="small"
            >
              下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          @current-change="currentChange"
          background
          layout="prev, pager, next"
          :total="total"
          :pager-count="5"
          :page-size="params.pageSize"
        >
        </el-pagination>
      </div>
    </div>

    <el-dialog
      :title="$tools.timestampToTime(invoiceDetail.applyTime, false, false)"
      :visible.sync="invoiceDetailModal"
      custom-class="invoice-modal"
    >
      <el-row>
        <el-col :span="12">
          <el-descriptions title="发票申请信息" :column="1">
            <el-descriptions-item label="发票类型"
              ><span v-if="invoiceDetail.type == 1">普通发票</span>
              <span v-if="invoiceDetail.type == 2"
                >增值税专用发票</span
              ></el-descriptions-item
            >
            <el-descriptions-item label="申请主体"
              ><span v-if="invoiceDetail.subject == 1">个人</span>
              <span v-if="invoiceDetail.subject == 2"
                >企业</span
              ></el-descriptions-item
            >
            <el-descriptions-item label="发票抬头">{{
              invoiceDetail.invoiceTitle
            }}</el-descriptions-item>

            <template v-if="invoiceDetail.subject == 2">
              <el-descriptions-item label="纳税登记号">
                {{ invoiceDetail.taxRegistryNumber || "" }}
              </el-descriptions-item>
            </template>

            <el-descriptions-item label="开票订单">
              <div
                class="order-item"
                v-for="(orderItem, orderIndex) in invoiceDetail.orderList"
                :key="orderIndex"
              >
                <div>{{ orderItem.goodsName }}</div>
                <div>{{ orderItem.orderSn }}</div>
                <div>￥{{ orderItem.goodsRealPrice | toFixed }}</div>
              </div>
            </el-descriptions-item>

            <el-descriptions-item label="开票金额">
              ¥ {{ invoiceDetail.amount | toFixed }}
            </el-descriptions-item>

            <template v-if="invoiceDetail.type == 2">
              <el-descriptions-item label="单位地址">{{
                invoiceDetail.companyAddress || ""
              }}</el-descriptions-item
              ><el-descriptions-item label="电话号码">{{
                invoiceDetail.phone || ""
              }}</el-descriptions-item
              ><el-descriptions-item label="开户银行">{{
                invoiceDetail.bankName || ""
              }}</el-descriptions-item
              ><el-descriptions-item label="银行账号">{{
                invoiceDetail.bankAccount || ""
              }}</el-descriptions-item
              ><el-descriptions-item label="收件地址">{{
                invoiceDetail.receivingAddress || ""
              }}</el-descriptions-item
              ><el-descriptions-item label="收件人">{{
                invoiceDetail.receivingName || ""
              }}</el-descriptions-item
              ><el-descriptions-item label="收件手机">{{
                invoiceDetail.receivingTel || ""
              }}</el-descriptions-item>
            </template>
          </el-descriptions>
        </el-col>
        <el-col :span="12">
          <el-descriptions title="发票申请结果" :column="1">
            <el-descriptions-item label="审核结果">
              <span class="text wait" v-if="invoiceDetail.periodStatus == 1"
                >待审核</span
              >
              <span class="text agree" v-if="invoiceDetail.periodStatus == 3"
                >通过</span
              >
              <span class="text refuse" v-if="invoiceDetail.periodStatus == 2"
                >驳回</span
              >
            </el-descriptions-item>
            <el-descriptions-item label="审核反馈">{{
              invoiceDetail.periodReason || ""
            }}</el-descriptions-item>
            <el-descriptions-item label="发票状态">
              <span class="text refuse" v-if="invoiceDetail.invoiceStatus == 1"
                >未开票</span
              >
              <span class="text agree" v-if="invoiceDetail.invoiceStatus == 2"
                >已开票</span
              >
              <span class="text refuse" v-if="invoiceDetail.invoiceStatus == -1"
                >已退票</span
              >
            </el-descriptions-item>
            <el-descriptions-item
              label="发票预览"
              v-if="
                invoiceDetail.periodStatus == 3 &&
                (invoiceDetail.invoiceStatus == 2 ||
                  invoiceDetail.invoiceStatus == -1) &&
                invoiceDetail.invoiceImg
              "
            >
              <div class="preview-wrap">
                <el-image
                  class="preview"
                  :src="$tools.splitImgHost(invoiceDetail.invoiceImg)"
                  :preview-src-list="[
                    $tools.splitImgHost(invoiceDetail.invoiceImg),
                  ]"
                ></el-image>
              </div>

              <el-button type="primary" @click="download(invoiceDetail)"
                >下载电子发票</el-button
              >
            </el-descriptions-item>
            <el-descriptions-item
              label="机构发票邮寄状态"
              v-if="
                invoiceDetail.periodStatus == 3 &&
                (invoiceDetail.invoiceStatus == 2 ||
                  invoiceDetail.invoiceStatus == -1) &&
                invoiceDetail.type == 2 &&
                invoiceDetail.subject == 2
              "
            >
              <span class="text" v-if="invoiceDetail.sendInvoice == 1">是</span>
              <span class="text" v-else>否</span>
            </el-descriptions-item>

            <el-descriptions-item
              label="发票邮寄快递单号：(点击可复制)"
              v-if="
                invoiceDetail.periodStatus == 3 &&
                (invoiceDetail.invoiceStatus == 2 ||
                  invoiceDetail.invoiceStatus == -1) &&
                invoiceDetail.sendInvoice == 1 &&
                invoiceDetail.type == 2 &&
                invoiceDetail.subject == 2
              "
            >
              {{ invoiceDetail.trackingNum }}
            </el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>

      <span slot="footer" class="dialog-footer">
        <el-button
          @click="cancelApply(invoiceDetail)"
          v-if="invoiceDetail.periodStatus == 1"
          >撤销申请</el-button
        >
        <el-button type="primary" @click="invoiceDetailModal = false"
          >知道了</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from "@/axios";
export default {
  name: "MyInvoice",
  data() {
    return {
      invoiceDetail: {
        amount: 0,
      },
      invoiceDetailModal: false,
      tableData: [],
      params: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
    };
  },
  mounted() {
    this.orderInvoiceList();
  },
  methods: {
    cancelApply(row) {
      const confirmText = [
        "撤销申请后，",
        "本次的发票申请内容将不存在。",
        "请慎重考虑。",
        "您确定要取消本次发票申请吗？",
      ];
      const newDatas = [];
      const h = this.$createElement;
      for (const i in confirmText) {
        newDatas.push(h("p", null, confirmText[i]));
      }
      this.$confirm(h("div", null, newDatas), "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        closeOnPressEscape: false,
        distinguishCancelAndClose: false,
        showClose: false,
      })
        .then((_) => {
          let invoiceDetail = JSON.parse(JSON.stringify(this.invoiceDetail));
          invoiceDetail.status = -1;
          this.$request.orderInvoiceCancel(invoiceDetail).then((res) => {
            this.orderInvoiceList();
            this.invoiceDetailModal = false;
            this.$message({
              type: "success",
              message: "撤销成功",
            });
          });
        })
        .catch((_) => {
          console.log(_);
        });
    },
    apply() {
      this.$router.push({
        path: "/person-center/my-invoice/add",
      });
    },

    currentChange(e) {
      this.params.pageNum = e;
      this.orderInvoiceList();
    },

    orderInvoiceList() {
      this.$request
        .orderInvoiceList(this.params)
        .then((res) => {
          this.tableData = res.rows;
          this.total = res.total;
        })
        .catch((err) => {
          this.$message({
            type: "error",
            message: err.msg,
          });
        });
    },

    showDetail(row) {
      this.invoiceDetail = row;
      this.invoiceDetailModal = true;
    },

    /**
     ** 下载图片到本地
     ** @param blobUrl： blob 格式的图片文件
     ** @param name: 图片名称
     */
    download(row) {
      // 创建虚拟a标签

      let url = this.$tools.splitImgHost(row.invoiceImg);
      let name = row.invoiceImg.substring(row.invoiceImg.lastIndexOf("/") + 1);

      var image = new Image();
      // 解决跨域 Canvas 污染问题,
      image.setAttribute("crossorigin", "anonymous");
      image.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        var context = canvas.getContext("2d");
        context.drawImage(image, 0, 0, image.width, image.height);
        var url = canvas.toDataURL("image/png"); //将图片格式转为base64
        var a = document.createElement("a"); // 生成一个a元素
        var event = new MouseEvent("click"); // 创建一个单击事件
        a.download = name; // 设置图片名称
        a.href = url; // 将生成的URL设置为a.href属性
        a.dispatchEvent(event); // 触发a的单击事件
      };
      image.src = url + "?time=" + Date.now(); //注意，这里是灵魂，否则依旧会产生跨域问题
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.my-invoice {
  overflow: hidden;
  &__header {
    margin-top: 24px;
  }
  &__body {
    margin-top: 20px;

    /deep/ .el-table {
      border: 1px solid #eeeeee;
      box-shadow: 0px 0px 7px 1px rgba(0, 0, 0, 0.04);
      border-radius: 8px;
    }

    .pagination {
      padding: 30px 0;
      text-align: center;
    }
  }

  .invoice-modal {
    .preview-wrap {
      /deep/ img {
        max-width: 200px;
      }
    }

    .text {
      &.wait {
        color: #007aff;
      }
      &.refuse {
        color: #ff3b30;
      }
      &.agree {
        color: #34c759;
      }
    }

    .order-item {
      background: #ccc;
      padding: 5px 10px;
      border-radius: 10px;
      margin-top: 10px;
    }
  }
}
</style>
