<template>
  <d2-container class="page">
    <el-tabs value="first">
      <el-tab-pane :label="title" name="first">
        
        <div style="margin-bottom: 8px;border-left: 3px solid;color: #e6a23c;">
          <div role="alert" class="el-alert el-alert--warning">
            <div class="el-alert__content" v-if="timeControl && year && month">
              <span class="el-alert__title">{{year}}年{{month}}发票申请时间：{{timeControl.start_time}} 到 {{timeControl.end_time}}
                <div style="margin-top:10px" v-if="PayInvoicingControl"  v-html="PayInvoicingControl">
                </div>

              </span>
            
            </div>
           
          </div>
        </div>

       <el-button type="primary" icon="el-icon-tickets" style="margin-bottom:1px;" v-if="timeControl && inTime" @click="goInvoicing()">发票申请</el-button>

       <el-button type="primary" icon="el-icon-refresh" style="margin-bottom:1px;" @click="refresh()">刷新</el-button><br>

        <el-table
          v-loading="loading"
          :data="list"
          style="width: 100%">
         
          <el-table-column
            prop="payerpartytype_text"
            label="交款人类型"
            width="100">
          </el-table-column>
          <el-table-column
            prop="payerpartyname"
            label="开票名称"
            width="120">
          </el-table-column>
          <el-table-column
            prop="payerpartycode"
            label="社会信用统一代码"
            width="180">
          </el-table-column>
          <el-table-column
            prop="bill_no"
            label="订单编号"
            width="240">
          </el-table-column>
          <el-table-column
            prop="bill_amount"
            label="缴费金额"
            width="80" align="right">
            <template slot-scope="scope">
              {{scope.row.bill_amount}} 元
            </template>
          </el-table-column>
          <!--
          <el-table-column
            prop="bill_status"
            label="缴费状态"
            width="80">
          </el-table-column>
          
          <el-table-column
            prop="bill_time"
            label="订单生成时间 "
            width="160">
          </el-table-column>
          -->
         <el-table-column
            prop="status"
            label="申请状态"
            width="100">
          </el-table-column>
          
          <el-table-column
            prop="create_time"
            label="申请时间 "
            width="160">
          </el-table-column>
          <el-table-column
             align="center"
                label="操作"
                width="130">
          <template slot-scope="scope">
          
              <div v-if="scope.row.status=='受理完成'">
                 <center>
                  <el-button @click="downInvoicing(scope.row)" type="success" size="small" style="margin-bottom:1px;">电子发票下载</el-button>

                 </center>
              </div>

          </template>
          </el-table-column>
          
        </el-table>

      </el-tab-pane>
    </el-tabs>
    <el-dialog width="800px" height="300px" id="paymodal" title="发票申请" :visible.sync="payDialogVisible" :show-close="false" :close-on-click-modal="false">
        <el-form ref="itemForm" :model="stdReg" :rules="itemRules" label-width="160px">
              <el-row>
                <el-col :span="24">
                  <!--
                  <el-form-item label="选择批次" prop="year_code">
                     <div style="width:400px">
                   <el-select size="medium" v-model="year_code" filterable clearable placeholder="请选择批次" @change="querybillno()">
                        <el-option v-for="item in exam_times" :key="item.id" :label="item.exam_year_month" :value="item.year_code"></el-option>
                    </el-select>
                     </div>
                  </el-form-item>
-->
                   <el-form-item label="交款人类型" prop="std_name">
                    <div style="width:400px">
                       <el-select size="medium" v-model="payerPartyType" filterable placeholder="请选择交款人类型">
                        <el-option label="个人" value="1"></el-option>
                        <el-option label="单位" value="2"></el-option>
                    </el-select>

                    </div>
                  </el-form-item>

                  <el-form-item label="开票名称" prop="std_name">
                    <div style="width:400px">
                      <el-input size="medium" v-model="stdReg.std_name" maxlength="64" placeholder="请填写开票名称"></el-input>
                    </div>
                  </el-form-item>

                   <el-form-item label="社会信用统一代码" prop="cert_no">
                    <div style="width:400px">
                      <el-input size="medium" v-model="stdReg.cert_no" maxlength="64" placeholder="请填写开票名称"></el-input>
                    </div>
                  </el-form-item>
                 
                </el-col>
              </el-row>
            
            </el-form>
       
          
        
        <el-table
          :data="billList"
          style="width:100%">
           <el-table-column label="请选择" width="100" align="center">
              <template slot-scope="scope">
                <center>
                   <el-checkbox :label="scope.row.bill_no" v-model="checkedCourse[scope.row.index]">&nbsp;</el-checkbox>
                </center>
              </template>
          </el-table-column>
           <el-table-column
            prop="exam_year_month"
            label="批次"
            width="110" align="center"> 
          </el-table-column>
          <el-table-column
            prop="bill_no"
            label="订单编号"
            width="400" align="center"> 
          </el-table-column>
          <el-table-column
            prop="bill_amount"
            label="订单金额"
            width="100" align="right"> 
            <template slot-scope="scope">
              {{scope.row.bill_amount}} 元
            </template>
          </el-table-column>
           
        </el-table>
     

     <div style="margin:10px">
       <center>
         <el-button type="primary" size="mini" v-if="invoicingVisible" @click="invoicing()">提交发票申请</el-button>

         <el-button type="primary" size="mini" v-if="invoicingVisible" @click="closePayWin()">关闭窗口</el-button>
       </center>
     </div>
    </el-dialog>

  </d2-container>
</template>

<script>
import { mapState, mapActions } from "vuex";

export default {
  computed: {
    title: function() {
      return `您有 ${this.list.length} 条发票申请单`;
    },
     ...mapState({
      stdReg: state => state.enrol.StdReg,
    })
  },
   data() {
    return {
      loading: false,
      payDialogVisible: false,
      invoicingVisible: false,
      exam_times:[],
      year_code:"",
      billList:[],
      checkedCourse: [],
      list:[],
      timeControl: {},
      PayInvoicingControl:null,
      inTime:false,
      year: null,
      month: null,
      payerPartyType: "1",

      itemRules: {
       
       payerPartyType: [
          { required: true, message: "请选择交款人类型", trigger: "blur" }
        ],
        std_name: [
          { required: true, message: "请填写开票名称", trigger: "blur" }
        ],
        cert_no: [
          { required: true, message: "请填写社会信用统一代码", trigger: "blur" }
        ],
       
      },
    };
  },
  async mounted () {
   this.init();
  },
  methods: {
    async init() {
        this.loading = true;

         let listres = await this.$http.post("pay/payInvoicing/init.htm");
         this.timeControl = listres.data.map.timeControl;
         this.inTime = listres.data.map.inTime;
         this.month = listres.data.map.month;
         this.year = listres.data.map.year;
         this.PayInvoicingControl = listres.data.map.PayInvoicingControl;

        let res = await this.$http.post(
        "pay/payInvoicing/queryPayInvoicing.htm",
        this.Qs.stringify({
            std_id: this.stdReg.id,
        }),
        this.$http.headers.FORM
        );
         this.list = res.data.array;

       
        this.loading = false;

        let time_res = await this.$http.post(
        "/pl/plExamTime/listtime.htm",
        {},
        this.$http.headers.FORM
      );
      this.exam_times = time_res.data.array;
   
    },
    async refresh(){
      this.$nextTick(() => {
        this.init();
     })
    },
    async goInvoicing(item) {
      this.billList = [];
      this.checkedCourse = [];
      this.payDialogVisible = true;
      this.invoicingVisible = true;
      this.querybillno();
     
    },
     async invoicing() {
       if(!this.payerPartyType) {
        this.alert("请选择交款人类型");
        return;
      }
       if(!this.stdReg.std_name) {
        this.alert("请填写开票名称");
        return;
      }
       if(!this.stdReg.cert_no) {
        this.alert("请填写社会信用统一代码");
        return;
      }
      if(this.checkedCourse.length == 0) {
        this.alert("请选择订单信息");
        return;
      }

      this.confirm("确定提交发票申请吗?", "操作确定", {
        confirm: function() {
            this.doinvoicing();
        }
      });
     
    },


    async doinvoicing() {
      
            let cloneItem = _.cloneDeep(this.stdReg);
            let reqCheckedCourse = [];
            for (let index = 0; index < this.checkedCourse.length; index++) {
              const checked = this.checkedCourse[index];
              if(checked == true)
                reqCheckedCourse.push(this.billList[index].bill_no);
              
            }
            cloneItem.billnos = reqCheckedCourse.join();
            cloneItem.payerPartyType =this.payerPartyType;


            this.loading = true;
            this.invoicingVisible = false;
            
            let { data } = await this.$http.post(
              "pay/payInvoicing/invoicing.htm",
              this.Qs.stringify(cloneItem),
              this.$http.headers.FORM
            );

            this.loading = false;
            if (data.success) {
              this.alert("发票申请提交成功。");
              this.closePayWin();
              this.init();
            } else {
              this.invoicingVisible = true;
              this.alert(data.errorMsg);
            }
     
    },
    
    
    async closePayWin() {
     
      this.payDialogVisible = false;
     
    },

     async querybillno() {
      
      this.loading = true;
      
      let res = await this.$http.post(
        "pay/payInvoicing/queryBillNo.htm",
        this.Qs.stringify({
          year_code: this.year_code        
        }),
        
        this.$http.headers.FORM
      );
      
      this.billList = res.data.array;
      this.loading = false;
    },

    //电子发票下载
    //async downInvoicing(item) {
    //  window.open(item.path);
    //},

    //电子发票下载
    async downInvoicing(item) {
      let res_ = await this.$http.post("pay/payInvoicing/checkDownInvoicing.htm",this.Qs.stringify({
                     bill_no: item.bill_no
                 }));
      if (!res_.data.success) {
        this.alert(res_.data.errorMsg);
        return;
      }

      let res = await this.$http({
        method: "post",
        url: `pay/payInvoicing/downInvoicing.htm?bill_no=`+item.bill_no,
        responseType: "blob"
      });
      let fileName = null;
      fileName = `${item.bill_no}.pdf`;

      if (window.navigator.msSaveBlob) {
        try {
          var blobObject = new Blob([res.data]);
          window.navigator.msSaveBlob(blobObject, fileName);
        } catch (e) {
          console.log(e);
        }
      } else {
        let loading = this.showLoading();
        let url = window.URL.createObjectURL(new Blob([res.data]));
        let link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        link.setAttribute("download", fileName);

        document.body.appendChild(link);
        link.click();
        this.hideLoading(loading);
      }
    },

  },
 
};
</script>

<style lang="scss" scoped>
@import "~@/assets/style/public.scss";
.page {
  .page__btn-group {
    color: $color-text-placehoder;
    font-size: 12px;
    margin-top: -10px;
    margin-bottom: 20px;
    span {
      color: $color-text-sub;
      &:hover {
        color: $color-text-main;
      }
    }
  }
}
</style>
