<template>
  <div class="app-container" >
      <div id="print" style="font-size: 18px;">

        <div style="position:relative;text-align: center;font-weight: bold;font-size: 26px;padding: 22px 0;border-top: 1px solid #666;border-left:1px solid #666;border-right: 1px solid #666;">
          <div style="position:absolute;left:4px;top:4px">{{$t('广州市捷道国际货运代理有限公司')}}
          </div>
          <span>{{$t('收款单')}}</span>
        </div>
          <table border="1" style="width: 100%;text-align: center;border-collapse: collapse; ">
            <tr>
              <td style="font-weight: bold;width:12.5%">{{$t('部门')}}</td>
              <td style="width:12.5%">{{form?form.departmentName:$t('无')}}</td>
              <td style="font-weight: bold;width:12.5%">{{$t('客户名称')}}</td>
              <td colspan="2" style="width: 25%;">{{form.customerName||$t('无')}}</td>
              <td style="font-weight: bold;width:12.5%">{{$t('收款日期')}}</td>
              <td colspan="2" style="width: 25%;">{{form&&form.payedAt?parseTime(form.payedAt):$t('无')}}</td>
            </tr>
            <tr>
              <td style="font-weight: bold;width:12.5%">{{$t('收款单号')}}</td>
              <td style="width:12.5%">{{form?form.receiptNo:$t('无')}}</td>
              <td style="font-weight: bold;width:12.5%">{{$t('备注')}}</td>
              <td colspan="4" style="width: 50%;">{{form?form.remark:$t('无')}}</td>
            </tr>
            <tr>
              <td colspan="8">Form/To:{{orderData.logisticsInfoDto?orderData.logisticsInfoDto.startTitleZh:''}}>{{orderData.logisticsInfoDto?orderData.logisticsInfoDto.destAddressZh:''}}</td>
            </tr>
            </table>
      <table border="1" style="width: 100%;text-align: center;border-collapse: collapse; border-top: 0;">
          <tr>
            <th style="width: 12.5%;">{{$t('序号')}}</th>
            <th style="width: 12.5%;">{{$t('提单号')}}</th>
            <th style="width: 12.5%;">{{$t('订单号')}}</th>
            <!-- <th style="width: 12.5%;">{{$t('品名')}}</th> -->
            <th style="width: 12.5%;">{{$t('收入类型')}}</th>
            <th style="width: 12.5%;">{{$t('币种')}}</th>
            <th style="width: 12.5%;">{{$t('金额')}}</th>
            <th style="width: 12.5%;">{{$t('优惠金额')}}</th>
          </tr>
          <tr v-for="(item, index) in list" :key="item.id">
            <td>{{ index + 1 }}</td>
            <td>{{ orderData.tidanNo||''}}</td>
            <td>{{ item.orderNo }}</td>
            <!-- <td>{{ $i18n.locale=='zh_CN'?item.titleZh:item.titleEn }}</td> -->
            <td><dict-tag :value="item.feeType" :type="DICT_TYPE.RECEIPT_FEE_TYPE"></dict-tag></td>
            <td>{{getCurrencyLabel(item.currencyId)}}</td>
            <td> {{item.totalAmount}}</td>
            <td>{{ item.discountTotal||0 }}</td>
          </tr>
          <tr v-for="(items, indexs) in receiptAccountList" :key="indexs">
            <td>{{getCurrencyLabel(items.currencyId)}}{{$t('应收合计')}}</td>
            <td ><span v-if="items.discountTotal>0">{{ `${items.receivableAmount - items.discountTotal }(${items.receivableAmount} - ${items.discountTotal})` }}</span>
            <span v-else>{{ `${items.receivableAmount}` }}</span>
            </td>
            <td>{{$t('汇率')}}</td>
            <td>{{ items.collectionRate}}</td>
            <td>{{$t('收款金额')}}({{getCurrencyLabel(items.collectionCurrencyId)}})</td>
            <td colspan="3">{{ items.collectionAmount}}</td>
          </tr>
        </table>
        <div style="text-align: center;border-left:1px solid #666;border-right: 1px solid #666;height: 36px;line-height: 36px;">
           {{$t('银行信息')}}
        </div>
        <div style="display: flex;align-items: center;border-top: 1px solid #666;border-left:1px solid #666;border-right: 1px solid #666;" v-for="(bankTiem,index) in detailed" :key="index">
          <div style="padding:6px 0;width: 12.5%;text-align: center;border-right: 1px solid #666;" >
            <p style="margin: 0;word-break: break-all;">{{$t('户名')}}:{{bankTiem.accountName}}</p>
            <p style="margin: 0;word-break: break-all;">{{$t('银行名称')}}:{{bankTiem.accountBankName||''}}</p>
            <p style="margin: 0;word-break: break-all;">A/C NO:{{bankTiem.accountNo}}</p>
          </div>
          <div style="padding:6px 0;width: 87.5%;text-align: center;">
            <p style="margin: 0;">{{$t('实收')}}{{getCurrencyLabel(bankTiem.currencyId)}}:{{bankTiem.amount}}{{getCurrencyFuhao(bankTiem.currencyId)}}</p>
            <!-- <p style="margin: 0;">未收:¥{{bankTiem.noReceipt}}</p> -->
          </div>
        </div>
        <div style="display: flex;align-items: center;border: 1px solid #666;">
          <div style="font-weight: bold;width: 12.5%;text-align: center;border-right: 1px solid #666;height: 36px;line-height: 36px;">{{$t('主管')}}</div>
          <div style="width: 12.5%;text-align: center;border-right: 1px solid #666;height: 36px;line-height: 36px;"></div>
          <div style="font-weight: bold;width: 12.5%;text-align: center;border-right: 1px solid #666;height: 36px;line-height: 36px;">{{$t('会计')}}</div>
          <div style="width: 12.5%;text-align: center;border-right: 1px solid #666;height: 36px;line-height: 36px;"></div>
          <div style="font-weight: bold;width: 12.5%;text-align: center;border-right: 1px solid #666;height: 36px;line-height: 36px;">{{$t('出纳')}}</div>
          <div style="width: 12.5%;text-align: center;height: 36px;line-height: 36px;border-right: 1px solid #666;"></div>
          <div style="font-weight: bold;width: 12.5%;text-align: center;border-right: 1px solid #666;height: 36px;line-height: 36px;">{{$t('经手人')}}</div>
          <div style="width: 12.5%;text-align: center;height: 36px;line-height: 36px;"></div>
        </div>
      </div>
      <div slot="footer" class="card">
        <el-button type="primary" @click="print">{{ $t('确定打印') }}</el-button>
      </div>
  </div>
</template>

<script>
  import { listSimpleUsers } from "@/api/system/user"
  import {DICT_TYPE} from  '@/utils/dict'
  import CustomerSelector from '@/components/CustomerSelector'
  import { getBankAccountPage } from "@/api/ecw/bankAccount";
  import { listSimpleDepts } from "@/api/system/dept"
  import { getReceipt} from "@/api/ecw/receipt";
  import lodop from '@/utils/lodop'
  import NP from 'number-precision'
  import {getOrder} from '@/api/ecw/order'
  import { getCurrencyPage } from "@/api/ecw/currency";
  import { getReceiptInfoByIds, getInvoicingItem,getReceiptAccountList,getReceivableItem} from "@/api/ecw/financial";

  export default {
    name: "PrintVoucher",
  components: {
     CustomerSelector
  },
    data() {
      return {
        loadings: false,
        form:{},
        title:this.$t('收款单'),
         // creatorData:[],
         list:[],
         fileList:[],
         bankData:[],
         params:{
           page:1,
           rows:20,
         },
         receiptAccountList:[],
         deptData:[],
         deptArr:[],
         id:0,
         orderData:{},
         detailed:[],
         date:'',
		 currencyList:[]
      }
    },
    async created() {
      let that = this
      // listSimpleUsers().then(res =>that.creatorData = res.data)
      // getBankAccountPage(that.params).then(res =>that.bankData = res.data.list)
	  await getCurrencyPage(this.params).then(res => this.currencyList = res.data.list)
      await listSimpleDepts().then(res =>{
        res.data.forEach((item)=>{
          if(item.parentId==0){

            that.deptArr.push(item)

          }
          that.deptData.push(item)
          
        })

        that.deptData.forEach((value)=>{
           var dept = that.deptArr.filter(itt=>itt.id==value.parentId)
           if(dept.length>0){
             value.name =dept[0].name+' | '+ value.name
           }

        })
      })
      if(that.$route.query.id){
        that.id = that.$route.query.id
        that.getCollectionData()
        that.getList()
        getInvoicingItem({id: this.id}).then(res => {
          this.list = res.data
          if(this.list.length>0) this.getOrder(this.list[0].orderId)
        })
      }
     getReceiptAccountList({ id: this.id }).then(res => {
        // if (res.data.length > 0) {
        //   // totalAmount
        //   res.data = [...res.data, {
        //     type: 'total',
        //     writeOffAmount: res.data.reduce((total, currentValue) => NP.plus(total, currentValue.writeOffAmount || 0), 0),
        //     collectionAmount: [0, 0, 0]
        //   }]
        // }
        // 收款总计
        // const dollarList = res.data.filter(v => v.collectionCurrencyId == 1)
        // const dollar = dollarList.reduce((total, currentValue) => NP.plus(total, currentValue.collectionAmount || 0), 0)

        // const rmbList = res.data.filter(v => v.collectionCurrencyId == 2)
        // const rmb = rmbList.reduce((total, currentValue) => NP.plus(total, currentValue.collectionAmount || 0), 0)

        // const nairaList = res.data.filter(v => v.collectionCurrencyId == 3)
        // const naira = nairaList.reduce((total, currentValue) => NP.plus(total, currentValue.collectionAmount || 0), 0)

        // res.data[res.data.length -1].collectionAmount = [dollar, rmb, naira]
        // this.$set(this.form, 'receiptAccountList', [...this.form.receiptAccountList])

        const dollarListByList = this.list.filter(v => v.currencyId === 1)
        const discountDollar = dollarListByList.reduce((total, currentValue) => NP.plus(total, currentValue.discountTotal || 0), 0)
        const d = res.data.find(v => v.currencyId == 1)
        d && (d.discountTotal = discountDollar)

        const rmbListByList = this.list.filter(v => v.currencyId === 2)
        const discountRmb = rmbListByList.reduce((total, currentValue) => NP.plus(total, currentValue.discountTotal || 0), 0)
        const r = res.data.find(v => v.currencyId == 2)
        r && (r.discountTotal = discountRmb)

        const nairaListByList = this.list.filter(v => v.currencyId === 3)
        const discountNaira = nairaListByList.reduce((total, currentValue) => NP.plus(total, currentValue.discountTotal || 0), 0)
        const n = res.data.find(v => v.currencyId == 3)
        n && (n.discountTotal = discountNaira)

        console.log(res.data)
        this.$set(this, 'receiptAccountList', [...res.data])
        this.$nextTick(() => {
          // this.form.receiptAccountList.forEach((item, index) => {
          //   this.rateChange(item, index)
          // });
        })
      })

    },
    methods: {
		getCurrencyLabel(id){
		  var label = this.currencyList.filter(item=>item.id == id)
		  if(label.length>0) return this.$i18n.locale=='zh_CN'?label[0].titleZh:label[0].titleEn
		  return ''
		},
    getCurrencyFuhao(id){
      var label = this.currencyList.filter(item=>item.id == id)
      if(label.length>0) return label[0].fuhao
      return ''
    },
      getList() {
        getReceivableItem({ id: this.id }).then(res => {
          this.detailed = res.data
          this.detailed.forEach(item=>{
            if(!this.date){
              this.date = item.amountDate
            }else if(this.date<item.amountDate){
              this.date = item.amountDate
            }
          })
        })
      },
      getCollectionData(){
        let that = this
        getReceiptInfoByIds({id:that.id}).then(res =>{
          that.form = res.data
          that.form.departmentName = that.deptData.find(v => v.id == that.form.departmentId).name
        })
      },
      getRecep(id){
        var total = 0
        if(id){
          var data = this.detailed.filter(item=>item.currencyId==id)
            data.forEach(item => {
            total = NP.plus(total, item.writeOffAmount)
          })
        }
        return total
      },
      handleAddReceiptItem() {
        let recepted = []
        this.detailed.forEach(item => {
            if(!recepted[item.currencyId]){
              recepted[item.currencyId] = item.amount
            }else recepted[item.currencyId] = NP.plus(recepted[item.currencyId], item.amount)
        })
        console.log('rece',recepted)
        let collom = []
        this.receiptAccountList.forEach(item => {
              if(recepted[item.currencyId]){
                item.noReceipt = +parseFloat(item.receivableAmount-recepted[item.currencyId])
              }
        })
      },
      getOrder(orderId){
        getOrder(orderId).then(response => {
          this.orderData = response.data
        });
      },
      print(){
          lodop().then(LODOP => {
              LODOP.PRINT_INIT();
              LODOP.SET_PRINT_STYLE("FontSize",18);
              LODOP.SET_PRINT_STYLE("Bold",1);
              // LODOP.ADD_PRINT_TEXT(50,231,260,39,"打印页面部分内容");
              // var stylePrint = "<style>table th,td{padding:0;margin:0;border:1px solid #000000;border-collapse:collapse;}</style>"
              var htmlContent = "<body>"+document.getElementById("print").innerHTML+"</body>"
              LODOP.ADD_PRINT_HTM("6mm", "6mm", "RightMargin:6mm", "BottomMargin:6mm", htmlContent);
              LODOP.PRINT();
              // this.$alert('已发起打印任务');
              // LODOP.PREVIEW(); // 预览
              /* LODOP.PRINTA(); // 选择打印机
               // 直接打印 */
              console.log('打印哦')
          }).catch(err => {
              console.error('lodop异常', err)
              alert(this.$t('请检查LODOP打印控件是否安装并启动'));
          })
      },
      totalMoney() {
        const t = this.list.map(v => v.actualAmount).reduce((prev, curr) => {
          return prev + curr;
        }, 0)
        return t
      },
      convertCurrency(money) {
        //汉字的数字
        var cnNums = new Array('零', this.$t('壹'), this.$t('贰'), this.$t('叁'), this.$t('肆'), this.$t('伍'), this.$t('陆'), this.$t('柒'), this.$t('捌'), '玖');
        //基本单位
        var cnIntRadice = new Array('', this.$t('拾'), this.$t('佰'), '仟');
        //对应整数部分扩展单位
        var cnIntUnits = new Array('', this.$t('万'), this.$t('亿'), '兆');
        //对应小数部分单位
        var cnDecUnits = new Array('角', this.$t('分'), this.$t('毫'), '厘');
        //整数金额时后面跟的字符
        var cnInteger = this.$t('整');
        //整型完以后的单位
        var cnIntLast = this.$t('元');
        //最大处理的数字
        var maxNum = 999999999999999.9999;
        //金额整数部分
        var integerNum;
        //金额小数部分
        var decimalNum;
        //输出的中文金额字符串
        var chineseStr = '';
        //分离金额后用的数组,预定义
        var parts;
        // 传入的参数为空情况
        if(money === '') {
          return '';
        }
        money = parseFloat(money)
        if(money >= maxNum){
          return ''
        }
        // 传入的参数为0情况
        if (money === 0) {
          chineseStr = cnNums[0] + cnIntLast + cnInteger;
          return chineseStr
        }
        // 转为字符串
        money = money.toString();
        // indexOf 检测某字符在字符串中首次出现的位置 返回索引值(从0 开始) -1 代表无
        if (money.indexOf('.') == -1) {
          integerNum = money;
          decimalNum = ''
        }else{
          parts = money.split('.');
          integerNum = parts[0];
          decimalNum = parts[1].substr(0,4);
        }
        //转换整数部分
        if(parseInt(integerNum,10) > 0){
          let zeroCount  = 0;
          let IntLen = integerNum.length
          for(let i = 0; i < IntLen; i++){
            let n = integerNum.substr(i,1);
            let p = IntLen - i - 1;
            let q = p / 4;
            let m = p % 4;
            if( n == '0'){
              zeroCount ++ ;
            }else{
              if(zeroCount > 0){
                  chineseStr += cnNums[0]
              }
              zeroCount = 0;
              chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
            }
            if(m == 0 && zeroCount < 4){
              chineseStr += cnIntUnits[q];
            }
          }
          // 最后+ 元
          chineseStr += cnIntLast;
        }
        // 转换小数部分
        if(decimalNum != ''){
          let decLen = decimalNum.length;
          for(let i = 0; i <decLen; i++){
            let n = decimalNum.substr(i,1);
            if(n != '0'){
              chineseStr += cnNums[Number(n)] + cnDecUnits[i]
            }
          }
        }
        if(chineseStr == ''){
          chineseStr = cnNums[0] + cnIntLast + cnInteger
        }else if(decimalNum == ''){
          chineseStr += cnInteger;
        }
        return chineseStr
      },
    },

  }
</script>

<style scoped id="printStyle">
  .card{
    margin-top: 20px;
  }
  .dialog-footer{
    padding: 40px;
  }
  .card-title{
      font-size: 18px;
      font-weight: bold;
      text-align: center;
  }
  .header{
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .lastRow{
    border-top:1px solid #dfe6ec;
    display: flex;
    width: 100%;
    height: 44px;
    text-align: center;
    align-items: center;
  }
  .lastRow div{
    height: 44px;
    line-height: 44px;
    border-right:1px solid #dfe6ec;
  }
</style>