<template>
  <div class="manage-root">
    <Header />
    <div class="manage-root-contain">
      <nav-menu
        class="manage-root-contain-left"
        :activeMenuIndex="activeMenuIndex"
      ></nav-menu>
      <div class="manage-root-contain-right">
        <breadcrumb
          :breadcrumbList="breadcrumbList"
          class="breadcrumb-box"
        ></breadcrumb>
        <div class="personal-inner">
          <div class="common-title-box">
            <h3>发票列表</h3>
          </div>
          <div class="search-box">
            <div class="search-item">
              <label>发票申请状态</label>
              <el-select
                v-model="searchStatus"
                @change="getList(1)"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in transactionList"
                  :key="item.status"
                  :label="item.status_name"
                  :value="item.status"
                >
                </el-option>
              </el-select>
            </div>
          </div>
          <el-table
            class="search-table"
            :data="tableData"
            style="width: 100%"
            @sort-change="handleSort"
            :default-sort="dataSort"
            :max-height="tableHeight"
            v-loading="tableLoading"
          >
            <el-table-column
              type="index"
              label="#"
              sortable
              width="54"
              :index="(pageNumber - 1) * pageSize + 1"
            >
            </el-table-column>
            <!-- <el-table-column prop="id" label="ID" width="250">
            </el-table-column> -->
            <el-table-column prop="sn" label="编号" width="190">
            </el-table-column>
            <el-table-column prop="invoice_type" label="发票类型" width="90">
              <template slot-scope="scope">
                <span>{{ goodsTypeListCss[scope.row.invoice_type].text }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="invoice_object" label="抬头类型" width="90">
              <template slot-scope="scope">
                <span>{{
                  goodsObjectListCss[scope.row.invoice_object].text
                }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="金额" width="90">
              <template slot-scope="scope">
                <span class="currectPrice"
                  >￥{{ scope.row.amount | cutMoneyFiter }}</span
                >
              </template>
            </el-table-column>
            <el-table-column
              prop="submit_person_name"
              label="提交人姓名"
              width="120"
            >
            </el-table-column>
            <el-table-column prop="submit_time" label="提交时间" width="180">
            </el-table-column>

            <el-table-column prop="status" label="状态" width="112">
              <template slot-scope="scope">
                <div class="status-box">
                  <span
                    :style="{
                      background: refundStatusList[scope.row.status].bg,
                    }"
                  ></span>
                  <b
                    :style="{
                      color: refundStatusList[scope.row.status].textColor,
                    }"
                    >{{ refundStatusList[scope.row.status].text }}</b
                  >
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="auditor_name" label="审核人姓名" width="109">
            </el-table-column>

            <el-table-column prop="audit_time" label="审核时间" width="180">
            </el-table-column>

            <el-table-column prop="reject_reason" label="驳回原因" width="180">
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="140">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="small"
                  class="primary-btn"
                  @click.native.prevent="handleDetail(scope.row, scope.$index)"
                >
                  详情
                </el-button>
                <template v-if="scope.row.status === 0">
                  <el-button
                    type="text"
                    size="small"
                    class="primary-btn"
                    @click.native.prevent="
                      passId = scope.row.id;
                      dialogVisiblePass = true;
                    "
                  >
                    通过
                  </el-button>
                  <el-button
                    @click.native.prevent="
                      handleRefuse(scope.row, scope.$index)
                    "
                    type="text"
                    size="small"
                    class="red-btn"
                  >
                    驳回
                  </el-button>
                </template>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNumber"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pageSize"
            layout="total, prev, pager, next, sizes, jumper"
            :total="total_count"
          >
          </el-pagination>
        </div>
      </div>
    </div>
    <el-dialog
      title="发票申请信息"
      :visible.sync="dialogVisible"
      width="600px"
      class="invoice-dialog"
      v-if="ktjeInfo"
    >
      <h5>发票信息</h5>
      <div class="item-info">
        <label>发票类型：</label>
        <b>{{ goodsTypeListCss[ktjeInfo.invoice_type].text }}</b>
      </div>
      <div class="item-info">
        <label>抬头类型：</label>
        <b>{{ goodsObjectListCss[ktjeInfo.invoice_object].text }}</b>
      </div>
      <div class="item-info">
        <label>抬头名称：</label>
        <b>{{ ktjeInfo.buyer_info_mc }}</b>
      </div>
      <template v-if="ktjeInfo.invoice_object === 1">
        <div class="item-info">
          <label>单位税号：</label>
          <b>{{ ktjeInfo.buyer_info_sh }}</b>
        </div>
        <div class="item-info">
          <label>注册地址：</label>
          <b>{{ ktjeInfo.buyer_info_dz }}</b>
        </div>
        <div class="item-info">
          <label>注册电话：</label>
          <b>{{ ktjeInfo.buyer_info_dh }}</b>
        </div>
        <div class="item-info">
          <label>开户银行：</label>
          <b>{{ ktjeInfo.buyer_info_khh }}</b>
        </div>
        <div class="item-info">
          <label>银行账号：</label>
          <b>{{ ktjeInfo.buyer_info_zh }}</b>
        </div>
      </template>
      <template v-else>
        <div class="item-info">
          <label>身份证号：</label>
          <b>{{ ktjeInfo.buyer_info_sfzh }}</b>
        </div>
      </template>

      <div class="item-info">
        <label>金额：</label>
        <b>￥{{ ktjeInfo.amount | cutMoneyFiter }}</b>
      </div>
      <template v-if="ktjeInfo.invoice_file_url">
        <div class="item-info">
          <label>发票地址：</label>
          <b
            ><a
              style="text-decoration: underline; color: #165dff"
              target="_blank"
              :href="ktjeInfo.invoice_file_url"
              >点击查看</a
            ></b
          >
        </div>
      </template>
      <div class="item-info">
        <label>审核状态：</label>
        <b
          :style="{
            color: refundStatusList[ktjeInfo.status].bg,
          }"
          >{{ refundStatusList[ktjeInfo.status].text }}</b
        >
      </div>
      <template v-if="ktjeInfo.reject_reason">
        <div class="item-info">
          <label>驳回原因：</label>
          <b>{{ ktjeInfo.reject_reason }}</b>
        </div>
      </template>

      <template v-if="ktje.length > 0">
        <h5>订单列表</h5>
        <el-table class="search-table" :data="ktje" style="width: 100%">
          <el-table-column type="index" label="#" width="54"> </el-table-column>
          <!-- <el-table-column prop="id" label="订单ID" width="250">
          </el-table-column> -->
          <el-table-column prop="sn" label="订单编号" width="190">
          </el-table-column>

          <el-table-column prop="name" label="订单名称"> </el-table-column>
        </el-table>
      </template>

      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="dialogVisible = false"
          >关 闭</el-button
        >
      </span>
    </el-dialog>
    <!-- 审核通过 -->
    <el-dialog
      title="发票申请审核通过"
      :visible.sync="dialogVisiblePass"
      width="500px"
    >
      <el-upload
        class="upload-demo"
        :action="url"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :before-remove="beforeRemove"
        multiple
        :limit="1"
        :on-exceed="handleExceed"
        :on-success="handleSuccess"
        :file-list="fileList"
      >
        <el-button size="small" type="primary">点击上传发票</el-button>
        <div slot="tip" class="el-upload__tip">只能上传1个文件</div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisiblePass = false"
          >取 消</el-button
        >
        <el-button size="small" type="primary" @click="handleRefund"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其它文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》from ‘《组件路径》';
import Header from "../../components/Header.vue";
import NavMenu from "../../components/NavMenu.vue";
import Breadcrumb from "../../components/Breadcrumb.vue";
import { getLogin } from "@/api/ajax";
import { cutMoneyFiter } from "@/utils/defined";
import { getToken } from "@/utils/auth";

export default {
  //import引入的组件需要注入到对象中才能使用
  components: { Header, NavMenu, Breadcrumb },
  props: {},
  filters: {
    cutMoneyFiter,
  },
  data() {
    //这里存放数据
    return {
      activeMenuIndex: "invoice_manage",
      breadcrumbList: [
        {
          icon: "money-cny-box-line",
          url: "",
          text: "",
        },
        {
          icon: "",
          url: "",
          notLink: true,
          text: "财务中心",
        },
        {
          icon: "",
          url: "",
          text: "发票管理",
        },
      ],
      searchStatus: -1,
      transactionList: [
        {
          status_name: "全部",
          status: -1,
        },
        {
          status_name: "待审核",
          status: 0,
        },
        {
          status_name: "驳回",
          status: 1,
        },
        {
          status_name: "审核通过",
          status: 2,
        },
      ], //交易状态列表
      goodsTypeListCss: {
        0: {
          text: "普通发票",
          color: "#722ED1",
        },
        1: {
          text: "专用发票",
          color: "#722ED1",
        },
      },
      goodsObjectListCss: {
        0: {
          text: "个人",
          color: "#722ED1",
        },
        1: {
          text: "企业",
          color: "#722ED1",
        },
      },
      refundStatusList: {
        2: {
          text: "审核通过",
          bg: "#00B42A",
          textColor: "#1D2129",
        },
        0: {
          text: "待审核",
          bg: "#165DFF",
          textColor: "#1D2129",
        },
        1: {
          text: "驳回",
          bg: "#FF7D00",
          textColor: "#1D2129",
        },
      },
      tableData: [],
      pageSize: window.localStorage.getItem("pageSize")
        ? Number(window.localStorage.getItem("pageSize"))
        : 10,
      pageNumber: window.localStorage.getItem("pageNumber")
        ? Number(window.localStorage.getItem("pageNumber"))
        : 1,
      tableHeight: "", // 表格高度
      total_count: 0,
      dataSort: {},
      props: { multiple: true },
      tableLoading: false,
      exportLoading: false,
      exportFlag:
        getToken() && JSON.parse(getToken())
          ? JSON.parse(getToken()).popedom_code_list.indexOf(40002) > -1
          : false,
      dialogVisible: false,
      ktje: [],
      refundId: "",
      ktjeInfo: null,
      dialogVisiblePass: false,
      passId: "",
      fileList: [],
    };
  },
  //计算属性 类似于data概念
  computed: {
    url() {
      let userInfor = getToken();
      let access_token = "";
      if (userInfor) {
        let user = JSON.parse(getToken());
        access_token = user.access_token;
      }
      return (
        process.env.VUE_APP_BASE_API +
        "/FileServer/WebFileUpload?AccessToken=" +
        access_token +
        "&SecurityLevel=High"
      );
    },
  },
  //监控data中数据变化
  watch: {},
  //方法集合
  methods: {
    handleSort(value) {
      let dataSort = {
        prop: value.prop,
        order: value.order,
      };
      this.dataSort = dataSort;
      this.getList();
    },
    // 查询列表
    getList(page) {
      this.tableLoading = true;
      if (page) {
        this.pageNumber = page;
      }
      let MethodName =
        "/ShopServer/Manager/FinanceManager/PageQueryInvoiceApplyList";
      let order_column_list = [];
      if (this.dataSort != {}) {
        if (this.dataSort.order == "descending") {
          order_column_list = [this.dataSort.prop + ":desc"];
        } else if (this.dataSort.order == "ascending") {
          // 升序不传值
          order_column_list = [this.dataSort.prop];
        } else {
          order_column_list = ["submit_time:desc"];
        }
      } else {
        order_column_list = ["submit_time:desc"];
      }

      let data = {
        page_capacity: this.pageSize,
        cur_page: this.pageNumber,
        order_column_list: order_column_list,
        status: this.searchStatus,
      };
      getLogin(MethodName, data)
        .then((res) => {
          this.tableLoading = false;
          if (res.status === 1) {
            this.tableData = res.invoice_apply_list;
            this.total_count = res.total_count;
          }
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    // 发票申请详情
    handleDetail(row) {
      this.ktjeInfo = null;
      let Mnames = "/ShopServer/Manager/FinanceManager/GetInvoiceApplyInfo";
      let datas = {
        id: row.id,
      };
      getLogin(Mnames, datas).then((res) => {
        if (res.status === 1) {
          this.ktje = res.order_list;
          this.ktjeInfo = res.invoice_apply;
          this.dialogVisible = true;
        }
      });
    },
    // 拒绝
    handleRefuse(row, index) {
      this.$prompt("请输入驳回原因", "确定驳回吗？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(({ value }) => {
          let Mname = "/ShopServer/Manager/FinanceManager/AuditInvoiceApply";
          let data = {
            id: row.id,
            is_pass: "false",
            reject_reason: value,
          };
          getLogin(Mname, data).then((res) => {
            this.$message.success("操作成功");
            this.getList();
          });
        })
        .catch(() => {
          // this.$message({
          //   type: "info",
          //   message: "取消输入",
          // });
        });
    },
    // 审核通过
    handleRefund() {
      if (this.fileList.length === 0) {
        this.$message.warning("请上传发票文件");
        return;
      }
      let Mnames = "/ShopServer/Manager/FinanceManager/AuditInvoiceApply";
      let datas = {
        id: this.passId,
        is_pass: "true",
        invoice_file_id: this.fileList[0].response.file_info_list[0].file_id,
      };
      getLogin(Mnames, datas)
        .then((res) => {
          if (res.status === 1) {
            this.$message.success("操作成功");
            this.getList();
            this.dialogVisiblePass = false;
          }
        })
        .catch(() => {
          this.dialogVisiblePass = false;
        });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.pageNumber = 1;
      this.getList();
    },
    handleCurrentChange(val) {
      this.pageNumber = val;
      this.getList();
    },
    //计算table高度(动态设置table高度)
    getTableHeight() {
      let tableH = 370; //距离页面下方的高度
      let tableHeightDetil = window.innerHeight - tableH;
      if (tableHeightDetil <= 300) {
        this.tableHeight = 300;
      } else {
        this.tableHeight = window.innerHeight - tableH;
      }
    },
    handleRemove(file, fileList) {
      this.fileList = [];
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleSuccess(response, file, fileList) {
      if (response.status == 1) {
        this.fileList = fileList;
      } else {
        this.fileList = [];
        this.$message.warning(response.msg);
      }
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getTableHeight();
    this.getList();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    let _this = this;
    let input = document.querySelector("input");
    input.addEventListener("keyup", function (event) {
      // 判断是否按下回车键
      if (event.keyCode === 13) {
        // 回车键被按下，执行你想要的操作
        _this.getList(1);
      }
    });
  },
  //生命周期-创建之前
  beforeCreated() {},
  //生命周期-挂载之前
  beforeMount() {},
  //生命周期-更新之前
  beforUpdate() {},
  //生命周期-更新之后
  updated() {},
  //生命周期-销毁之前
  beforeDestory() {},
  //生命周期-销毁完成
  destoryed() {},
  //如果页面有keep-alive缓存功能，这个函数会触发
  activated() {},
};
</script>
<style lang="scss" scoped>
/* @import url(); 引入css类 */
</style>
<style lang="scss">
.btn-box {
  display: flex;
}
.search-item {
  margin-bottom: 20px;
}
.search-table {
  margin-top: 0;
}
.code {
  color: #175dff;
}
.item-info {
  display: flex;
  width: 100%;
  margin: 10px 0;
  label {
    width: 90px;
    text-align: right;
    flex-shrink: 0;
  }
}
.invoice-dialog {
  h5 {
    font-size: 16px;
    margin: 10px 0 15px 0;
  }
  .el-dialog__body {
    padding: 0px 20px;
  }
}
</style>
