<template>
  <div class="app-container">
    <div slot="header" class="card-title">{{ $t('开票') }}</div>
    <!-- 搜索工作栏 -->
    <el-form
      :model="invoiceData"
      ref="queryForm"
      size="small"
      :inline="true"
      label-width="120px"
      class="card"
    >
      <el-card class="card">
        <el-form-item :label="$t('发票号码')" prop="invoiceNumber" :rules="{ required: true, trigger: ['blur'], message: $t('发票号码不能为空') }">
          <el-input v-model="invoiceData.invoiceNumber"></el-input>
        </el-form-item>
        <el-form-item :label="$t('开票类型')" prop="invoicingTypeId" :rules="{ required: true, trigger: ['blur', 'change'], message: $t('开票类型不能为空') }">
          <dict-selector
            :type="DICT_TYPE.ECW_INVOICING_TYPE"
            v-model="invoiceData.invoicingTypeId"
          />
        </el-form-item>
      </el-card>
      <el-card class="card">
        <div slot="header" class="card-title">{{ $t('开票资料') }}</div>
        <el-descriptions title="" direction="vertical" :column="6" border>
          <el-descriptions-item :label="$t('发票抬头')">{{ invoiceData.invoice }}</el-descriptions-item>
          <el-descriptions-item :label="$t('纳税人识别号')">{{ invoiceData.taxpayer }}</el-descriptions-item>
          <el-descriptions-item :label="$t('地址')">{{ invoiceData.addressPhone }}</el-descriptions-item>
          <el-descriptions-item :label="$t('开户行')">{{ invoiceData.accountBank }}</el-descriptions-item>
          <el-descriptions-item :label="$t('税率%')">
            <el-form-item label="">
              <el-input v-model="invoiceData.taxRate"></el-input>  
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('项目')">
            <el-form-item label="">
              <el-input v-model="invoiceData.projectName"></el-input>  
            </el-form-item>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
      <el-card class="card">
        <el-table
          v-loading="loading"
          :data="list"
          border
          class="card"
          show-summary
          :summary-method="getSummaries"
        >
          <el-table-column :label="$t('订单号')" align="center" prop="orderNo" />
          <el-table-column :label="$t('品名')" align="center" prop="titleZh">
            <template slot-scope="scope">
              {{ scope.row.titleZh || scope.row.titleEn ? scope.row.titleZh + "(" + scope.row.titleEn + ")" : '' }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('箱数')" align="center" prop="num" />
          <el-table-column :label="$t('体积/重量')" align="center" prop="weight"></el-table-column>
          <el-table-column :label="$t('收入类型')" align="center" prop="feeType">
            <template slot-scope="scope">
              <dict-tag
                :type="DICT_TYPE.FEE_TYPE"
                :value="scope.row.feeType"
              ></dict-tag>
            </template>
          </el-table-column>
          <el-table-column :label="$t('单价金额')" align="center" prop="unitPrice">
          <template slot-scope="scope">
            <span>{{ scope.row.unitPrice }}{{getCurrencyLabel(scope.row.currencyId)}}</span>
            <!-- <dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="scope.row.currencyId" /> -->
          </template>
        </el-table-column>
        <el-table-column :label="$t('总金额')" align="center" prop="totalAmount">
          <template slot-scope="scope">
            <span>{{ scope.row.totalAmount }}{{getCurrencyLabel(scope.row.currencyId)}}</span>
            <!-- <dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="scope.row.currencyId" /> -->
          </template>
        </el-table-column>
          <el-table-column :label="$t('税额')" align="center" prop="tax">
            <template slot-scope="scope">
              <span>{{ scope.row.tax }}{{getCurrencyLabel(scope.row.currencyId)}}</span>
              <!-- <dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="scope.row.currencyId" /> -->
            </template>
          </el-table-column>
          <el-table-column :label="$t('价税合计')" align="center" prop="taxAndTotalAmount">
            <template slot-scope="scope">
              <span>{{ scope.row.taxAndTotalAmount }}{{getCurrencyLabel(scope.row.currencyId)}}</span>
              <!-- <dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="scope.row.currencyId" /> -->
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-descriptions class="card" style="width: 50%">
        <el-descriptions-item :label="$t('备注')">
          <el-input
            v-model="invoiceData.invoicingRemark"
            type="text"
            placeholder=""
            clearable
          ></el-input>
        </el-descriptions-item>
      </el-descriptions>
    </el-form>
    <div slot="footer" class="card">
      <el-button type="primary" @click="submitForm">{{ $t('确定') }}</el-button>
    </div>
  </div>
</template>

<script>
import { DICT_TYPE } from "@/utils/dict";
import { getReceiptInvoicing, getInvoicingItem, updateReceiptInvoicing } from "@/api/ecw/financial";
import NP from 'number-precision'


export default {
  name: "OpenInvoice",
  components: {},
  data() {
    return {
      loading: false,
      invoiceData: {},
      id: 0,
      list: [],
	  params:{
	       page:1,
	       rows:20,
	   },
	  currencyList:[]
    };
  },
  created() {
    if (this.$route.query.id) {
      this.id = this.$route.query.id;
      this.getData();
    }
	 getCurrencyPage(this.params).then(res => this.currencyList = res.data.list)
  },
  methods: {
	  getCurrencyLabel(id){
	    var label = this.currencyList.filter(item=>item.id == id)
	    if(label.length>0) return label[0].titleZh
	    return ''
	  },
    async getData() {
      this.loading = true;
      await getReceiptInvoicing(this.id).then((res) => {
        this.invoiceData = res.data;
        this.invoiceData.invoicingTypeId = this.invoiceData.invoicingTypeId || ''
        // if (!this.invoiceData.info || this.invoiceData.info.length == 0) {
        //   this.$modal.msgError("客户开票资料不能为空，请完善客户开票信息");
        // }
        this.loading = false;
      });
      getInvoicingItem({ id: this.id }).then(res => {
        res.data.map(v => {
          v.tax = NP.times(v.totalAmount, this.invoiceData.taxRate/100)
          v.taxAndTotalAmount = NP.plus(v.totalAmount, NP.times(v.totalAmount, this.invoiceData.taxRate/100))
        })
        const t = {
          orderNo: this.$t('合计'),
          totalAmount: res.data.reduce((total, curr) => NP.plus(total, curr.totalAmount), 0),
          tax: res.data.reduce((total, curr) => NP.plus(total, curr.tax), 0),
          taxAndTotalAmount: res.data.reduce((total, curr) => NP.plus(total, curr.taxAndTotalAmount), 0)
        }
        this.list = [...res.data, t]
      })
    },
    submitForm() {
      this.$refs.queryForm.validate(valid => {
        if (valid) {
          updateReceiptInvoicing(this.invoiceData).then(res => {
            this.open = false;
            this.$modal.msgSuccess(this.$t('操作成功'));
            this.$router.back();
          })
        }
      })
    },
    getSummaries(param) {
      const t = this.list[this.list.length - 1].taxAndTotalAmount
      return [this.$t('收款人'), this.invoiceData.payeeName, this.$t('核销人'), this.invoiceData.writeOffName, this.$t('开票人'), this.invoiceData.issuerName, '', this.$t('价税合计大写'), this.convertCurrency(t)];
    },
    convertCurrency(money) {
      //汉字的数字
      var cnNums = new Array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
      //基本单位
      var cnIntRadice = new Array('', '拾', '佰', '仟');
      //对应整数部分扩展单位
      var cnIntUnits = new Array('', '万', '亿', '兆');
      //对应小数部分单位
      var cnDecUnits = new Array('角', '分', '毫', '厘');
      //整数金额时后面跟的字符
      var cnInteger = '整';
      //整型完以后的单位
      var cnIntLast = '元';
      //最大处理的数字
      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 lang="scss">
.card {
  margin-top: 20px;
}
.dialog-footer {
  padding: 30px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  height: 160px;
}
.card-title {
  font-size: 18px;
  font-weight: bold;
}
.lastRow {
  border-top: 1px solid #dfe6ec;
  display: flex;
  width: 100%;
  height: 44px;
  text-align: center;
  align-items: center;
}
.lastRow div {
  flex: 1;
  height: 44px;
  line-height: 44px;
  border-right: 1px solid #dfe6ec;
}
::v-deep .el-form-item--small.el-form-item {
  margin-bottom: 0;
}
</style>
