<template>
  <div class="divBox">
    <el-card class="box-card">
      <div slot="header" class="clearfix" v-hasPermi="['platform:finance:merchant:closing:page:list']">
        <div class="container">
          <el-form size="small" inline label-width="100px">
            <el-form-item label="时间选择：">
              <el-date-picker
                v-model="timeVal"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
                size="small"
                type="daterange"
                placement="bottom-end"
                placeholder="自定义时间"
                style="width: 250px"
                @change="onchangeTime"
              />
            </el-form-item>
            <el-form-item label="关键字：">
              <el-input
                v-model.trim="searchInfo.keyword"
                @keyup.enter.native="searchList"
                placeholder="请输入订单号/申请单号/发票号码"
                class="selWidth"
                size="small"
              >
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  size="small"
                  class="el-button-solt"
                  @click="getList(1)"
                  v-hasPermi="['platform:finance:merchant:closing:page:list']"
                />
              </el-input>
            </el-form-item>
            <el-form-item label="开票状态：" class="width100" style="display: block">
              <el-select v-model="searchInfo.fapiaoStatus" placeholder="请选择" @change="searchList">
                <el-option label="全部" :value="-1"></el-option>
                <el-option label="未开票" :value="0"></el-option>
                <el-option label="已开票" :value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <el-button size="small" type="primary" @click="importInvoice" > 导入 </el-button>
        <el-button size="small" type="primary" @click="exportInvoice" > 导出 </el-button>
      </div>
      <el-table
        v-loading="listLoading"
        tooltip-effect="dark"
        :data="invoiceList"
        style="width: 100%"
        class="table"
        row-key="id"
        ref="elTable"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
        <el-table-column prop="applyNo" label="流水号" min-width="220" />
        <el-table-column prop="userName" label="用户昵称" min-width="120" align="center" />
        <el-table-column prop="bizType" label="商品类型" min-width="260" align="center">
          <template slot-scope="scope">
            <span>{{ bizTypeList[scope.row.bizType] }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="productInfo" label="商品信息" min-width="180" align="center" />
        <el-table-column prop="amount" label="发票金额" min-width="120" align="center" />
        <el-table-column prop="fapiaoNo" label="发票单号" min-width="120" align="center" />
        <el-table-column prop="amount" label="发票类型" min-width="80" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.fapiaoType === 0 ? '普通发票' : '专用发票' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="taxNo" label="企业税号" min-width="120" align="center" />
        <el-table-column prop="bankName" label="开户银行" min-width="120" align="center" />
        <el-table-column prop="bankAccount" label="银行账号" min-width="120" align="center" />
        <el-table-column prop="address" label="企业地址" min-width="120" align="center" />
        <el-table-column prop="phone" label="企业电话" min-width="120" align="center" />
        <el-table-column prop="amount" label="发票抬头" min-width="80" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.titleType === 0 ? '个人' : '企业' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="发票联系人" min-width="120" align="center" />
        <el-table-column prop="email" label="发票联系信息" min-width="170" align="center" />
        <el-table-column prop="amount" label="开票状态" min-width="80" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.fapiaoStatus === 0 ? '未开票' : '已开票' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="发票备注" min-width="120" align="center" />
        <el-table-column label="操作" min-width="100" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="openInvoiceDetailDialog(scope.row)"
              v-hasPermi="['platform:finance:merchant:closing:detail']"
              >详情</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="openInvoiceDetailDialog(scope.row, 'edit')"
              :disabled="scope.row.fapiaoStatus === 1"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :page-sizes="[20, 40, 60, 80]"
          :page-size="limit"
          :current-page="page"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="pageChange"
        />
      </div>
    </el-card>
    <invoiceDetailDialog
      :showInvoiceDetailDialog="showInvoiceDetailDialog"
      :invoiceDetailInfo="invoiceDetailInfo"
      :type="type"
      :ids="ids"
      @closeInvoiceDetailDialog="closeInvoiceDetailDialog"
    />
    <mergeInvoiceDialog
      :showMergeInvoiceDialog="showMergeInvoiceDialog"
      :ids="ids"
      @closeMergeInvoiceDialog="closeMergeInvoiceDialog"
    />
    <!-- 导入 -->
    <importInvoiceDialog ref="importdialog" @closeImportInvoiceDialog="closeImportInvoiceDialog" />
  </div>
</template>
<script>
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
import { getInvoiceListApi, exportInvoiceApi } from '@/api/finance';
import { checkPermi } from '@/utils/permission'; // 权限判断函数
import invoiceDetailDialog from './components/invoiceDetailDialog';
import mergeInvoiceDialog from './components/mergeInvoiceDialog';
import importInvoiceDialog from './components/importInvoiceDialog';

export default {
  name: 'FinanceInvoice',
  components: { invoiceDetailDialog, mergeInvoiceDialog, importInvoiceDialog },
  data() {
    // 商品类型枚举
    const bizTypeList =  ['实体商品','虚拟商品','特殊商品','保险','风评报告'];
    return {
      listLoading: true,
      bizTypeList,
      showInvoiceDetailDialog: false,
      showMergeInvoiceDialog: false,
      timeVal: [],
      page: 1,
      limit: 20,
      total: 0,
      totalPage: null,
      invoiceList: [],
      searchInfo: {
        keyword: '',
        timeFrom: '',
        timeTo: '',
        fapiaoStatus: null,
      },
      invoiceDetailInfo: {},
      type: '',
      ids: [],
      selectList: [],
    };
  },

  mounted() {
    if (checkPermi(['platform:finance:merchant:closing:page:list'])) this.getList();
  },

  methods: {
    checkPermi,

    getList() {
      let params = {
        page: this.page,
        limit: this.limit,
      };
      this.listLoading = true;
      this.searchInfo.keyword ? (params.keyword = this.searchInfo.keyword) : null;
      this.searchInfo.timeFrom ? (params.timeFrom = this.searchInfo.timeFrom) : null;
      this.searchInfo.timeTo ? (params.timeTo = this.searchInfo.timeTo) : null;
      this.searchInfo.fapiaoStatus >= 0 ? (params.fapiaoStatus = this.searchInfo.fapiaoStatus) : null;

      getInvoiceListApi(params)
        .then((res) => {
          let { limit, list, page, total, totalPage } = res;

          this.limit = limit;
          this.invoiceList = list;
          this.page = page;
          this.total = total;
          this.totalPage = totalPage;
          this.listLoading = false;
        })
        .catch(() => {
          this.listLoading = false;
        });
    },
  
    // 选择时间
    selectChange(tab) {
      this.timeVal = [];
      this.page = 1;
      this.getList();
    },
    // 具体日期
    onchangeTime(e) {
      this.page = 1;
      this.timeVal = e;
      if (!this.timeVal) {
        this.searchInfo.timeFrom = '';
        this.searchInfo.timeTo = '';
        this.getList();
        return;
      }

      [this.searchInfo.timeFrom, this.searchInfo.timeTo] = this.timeVal;
      this.getList();

    },

    searchList() {
      this.page = 1;
      this.getList();
    },

    // 导入
    importInvoice() {
      this.$refs.importdialog.open();
    },
    // 导出
    exportInvoice() {
      // 1. 获取当前查询条件
      const { keyword, timeFrom, timeTo, fapiaoStatus } = this.searchInfo;
      const params = {
        keyword: keyword || '',
        timeFrom: timeFrom || '',
        timeTo: timeTo || '',
        fapiaoStatus: fapiaoStatus,
        fapiaoIds: []
      };
      const fapiaoIds = [];
      if (this.selectList && this.selectList.length) {
        this.selectList.forEach(element => {
          fapiaoIds.push(element.id);
        });
      }
      params.fapiaoIds = fapiaoIds;
      // 2. 导出接口
      exportInvoiceApi(params).then((res) => {
        const blob = new Blob([res], {
          type: 'application/vnd.ms-excel;charset=utf-8',
        });
        const a = document.createElement('a');
        const href = window.URL.createObjectURL(blob);
        a.href = href;
        a.download = localStorage.getItem('filename');
        localStorage.removeItem('filename');
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(href);
        this.$refs.elTable.clearSelection();
      });
    },
    mergeInvoice() {
      this.ids = [];
      if (this.selectList.length === 0) {
        this.$message({
          message: '至少选择一条记录',
          type: 'warning',
          showClose: true,
        });

        return;
      }

      if (this.selectList.some((el) => el.fapiaoStatus === 1)) {
        this.$message({
          message: '不能包含已开票记录',
          type: 'warning',
          showClose: true,
        });

        return;
      }

      let isConsistent = true;
      if (this.selectList.length > 1) {
        for (let i = 1; i < this.selectList.length; i++) {
          if (this.selectList[i].titleType !== this.selectList[i - 1].titleType) {
            isConsistent = false;
            break;
          }

          if (this.selectList[i].fapiaoType !== this.selectList[i - 1].fapiaoType) {
            isConsistent = false;
            break;
          }

          if (this.selectList[i].title !== this.selectList[i - 1].title) {
            isConsistent = false;
            break;
          }

          if (this.selectList[i].email !== this.selectList[i - 1].email) {
            isConsistent = false;
            break;
          }

          if (this.selectList[i].titleType === 1) {
            if (this.selectList[i].taxNo !== this.selectList[i - 1].taxNo) {
              isConsistent = false;
              break;
            }
          }

          if (this.selectList[i].titleType === 1 && this.selectList[i].fapiaoType === 1) {
            if (this.selectList[i].bankName !== this.selectList[i - 1].bankName) {
              isConsistent = false;
              break;
            }

            if (this.selectList[i].bankAccount !== this.selectList[i - 1].bankAccount) {
              isConsistent = false;
              break;
            }

            if (this.selectList[i].bankAccount !== this.selectList[i - 1].bankAccount) {
              isConsistent = false;
              break;
            }

            if (this.selectList[i].phone !== this.selectList[i - 1].phone) {
              isConsistent = false;
              break;
            }

            if (this.selectList[i].address !== this.selectList[i - 1].address) {
              isConsistent = false;
              break;
            }
          }
        }
      }

      if (!isConsistent) {
        this.$message({
          message: '开票信息不一致不能合并',
          type: 'warning',
          showClose: true,
        });

        isConsistent = true;
        return;
      }

      this.selectList.forEach((el) => {
        this.ids.push(el.id);
      });
      this.showMergeInvoiceDialog = true;
      console.info('sf', this.selectList);
    },

    handleSelectionChange(selection) {
      this.selectList = selection;
    },

    openInvoiceDetailDialog(row, type) {
      this.ids.push(row.id);
      this.invoiceDetailInfo = row;
      this.type = type;
      this.showInvoiceDetailDialog = true;
    },

    closeInvoiceDetailDialog() {
      this.showInvoiceDetailDialog = false;
      this.getList();

    },

    pageChange(page) {
      this.page = page;
      this.getList();
    },

    handleSizeChange(val) {
      this.limit = val;
      this.getList();
    },

    closeMergeInvoiceDialog() {
      this.showMergeInvoiceDialog = false;
    },
    closeImportInvoiceDialog() {
      this.searchInfo = {
        keyword: '',
        timeFrom: '',
        timeTo: '',
        fapiaoStatus: null,
      };
      this.page = 1;
      this.limit = 20;
      this.getList();

    },
  },
};
</script>

<style lang="scss" scoped>
.demo-image__preview {
  width: 60px;
  height: 60px;
  .el-image {
    width: 100%;
    height: 100%;
  }
}
.title {
  font-size: 20px;
}
.wid100 {
  width: 100px;
}
.ml100 {
  margin-left: 100px;
}
.transferMinAmount {
  ::v-deep.el-form-item__content {
    line-height: normal;
  }
}
::v-deep .el-dialog__title {
  font-weight: bold;
}
.selWidth {
  width: 300px;
}
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
  font-size: 12px;
}
.el-icon-arrow-down {
  font-size: 12px;
}
.font-red {
  color: #ff4949;
}
.tabBox_tit {
  width: 60%;
  font-size: 12px !important;
  margin: 0 2px 0 10px;
  letter-spacing: 1px;
  padding: 5px 0;
  box-sizing: border-box;
}
.pictrue {
  width: 60px;
  height: 60px;
  border: 1px dotted rgba(0, 0, 0, 0.1);
  margin-right: 10px;
  position: relative;
  cursor: pointer;
  img {
    width: 100%;
    height: 100%;
  }
}
.box-container {
  overflow: hidden;
  padding: 0 30px;
  font-size: 14px;
}

.box-container .list.image {
  margin: 20px 0;
  position: relative;
}
.box-container .list.image img {
  position: absolute;
  top: -20px;
}
.box-container .list {
  float: left;
  line-height: 40px;
}
.box-container .sp100 {
  width: 100%;
}

.acea-row {
  margin-bottom: 25px;
}
.pictures {
  width: 100%;
  height: 100%;
}

.open-invoice-btn {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 80px;
  height: 30px;
  box-sizing: border-box;
  background-color: #409eff;
  border-radius: 5px;
  margin: 10px 0px;
  color: white;
}
</style>
