<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               v-model="form"
               ref="crud"
               @on-load="onLoad">
      <template slot="purchaseNum" slot-scope="{row}" >
        <el-input v-model="row.purchaseNum" type="number" min="0" @change="calAmount(row)" @keydown.native="channelInputLimit"></el-input>
      </template>
    </avue-crud>
    <el-divider></el-divider>
    <div align="left" style="margin: 10px;">采购金额(大写)：{{moneyChina}}</div>
    <template>
      <div align="center" style="font-size: 20px;color: #0099FF;margin-bottom: 20px;">采购金额</div>
      <div align="center">
        <div>说明：采购后账户余额 = 本次采购金额 - 技术服务费 - 手续费
          <div>
            <table style="width: 100%;" border="1" class="myTable">
              <tr v-for="(item,i) in statDatas" :key="i">
                <td class="column">{{ item.key }}</td>
                <td class="column">{{ item.value }}</td>
              </tr>
            </table>
          </div>
        </div>
        <div align="center" style="margin: 20px;">
          <el-span style="font-weight: bold">银行卡：</el-span>
          <el-select v-model="billrecord.bankCode" placeholder="请选择银行" clearable="true" filterable="true">
            <el-option v-for="item in bankCodeList" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey">
            </el-option>
          </el-select>
        </div>
        <div align="center" style="margin: 20px;">
          <el-button type="success" size="mini" @click="purchaseConfirm" :loading="isLoading">确认采购</el-button>
        </div>
      </div>
    </template>
  </basic-container>
</template>

<script>
  import {getList} from "@/api/bussiness/bussinessgoods";
  import {getDictionary} from "@/api/system/dictbiz";
  import {mapGetters} from "vuex";
  import {
    detail as getParamDetail
  } from "@/api/system/param";
  import {
    add as addBillrecord
  } from "@/api/billrecord/billrecord";

  export default {
    props:{
      serviceRate: ""
    },
    data() {
      return {
        form: {},
        query: {},
        bankCodeList: [],
        loading: true,
        chongzhiVisible:true,
        money: 0.00,
        purchaseList:[],
        moneyChina: "",
        isLoading: false,
        billrecord: {
          payStatus: 0,
          type: 5,
          bankCode: null
        },
        yibaoOrder: {

        },
        purchaseMap: new Map(),
        statDatas: [
          {
            key: "技术服务费率",
            value: this.serviceRate / 1000
          },
          {
            key: "技术服务费",
            value: 0
          },
          {
            key: "采购金额",
            value: 0
          },
          {
            key: "可用余额",
            value: 0
          }

        ],
        page: {
          pageSize: 100,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'300',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: false,
          viewBtn: true,
          selection: false,
          dialogClickModal: false,
          refreshBtn: false,
          columnBtn: false,
          menu:false,
          addBtn: false,
          column: [
            {
              label: "商品编号",
              prop: "goodsNo",
            },
            {
              label: "商品名称",
              prop: "goodsName",
            },
            {
              label: "商品图片",
              prop: "goodsPic",
              type: 'img'
            },
            {
              label: "商品单价",
              prop: "goodsPrice",
            },
            {
              label: "商品数量",
              prop: "purchaseNum",
            },
            {
              label: "小计",
              prop: "amount",
              type: "number"
            },
          ],
        },
        data: []
      };
    },
    created(){
      this.loadBizDict("b2b_bank_code");
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.bussinessgoods_add, false),
          viewBtn: this.vaildData(this.permission.bussinessgoods_view, false),
          delBtn: this.vaildData(this.permission.bussinessgoods_delete, false),
          editBtn: this.vaildData(this.permission.bussinessgoods_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      loadBizDict(code){
        let that = this;
        getDictionary({"code":code}).then(res =>{
          that.bankCodeList = res.data.data;
        })
      },
      channelInputLimit (e) {
        let key = e.key
        // 不允许输入'e'和'.'
        if (key === 'e' || key === '.') {
          e.returnValue = false
          return false
        }
        return true
      },
      calAmount(row){
        row.amount = (row.purchaseNum * row.goodsPrice).toFixed(2);
        this.$set(row);
        let list = this.data;
        let that = this;
        let newMoney = 0.00;
        list.forEach(item => {
          newMoney = newMoney + parseFloat(item['amount']).toFixed(2);
        });
        that.money = newMoney;
        that.moneyChina = that.digitUppercase(that.money);
        this.statDatas[1].value = (that.money * that.statDatas[0].value).toFixed(2)
        this.statDatas[2].value = parseFloat(that.money).toFixed(2)
        this.statDatas[3].value = (parseFloat(that.statDatas[2].value) - parseFloat(that.statDatas[1].value)).toFixed(2)
        if(row.purchaseNum == 0){
          that.purchaseMap.delete(row.id);
        }else if(row.purchaseNum > 0){
          that.purchaseMap.set(row.id, row);
        }
      },
      purchaseConfirm() {
        this.isLoading = true;
        this.billrecord.price = this.money;
        this.billrecord.bussinessFee = this.statDatas[1].value;
        this.billrecord.purchaseList = Array.from(this.purchaseMap.values());
        this.billrecord.returnUrl = "https://music.nanyue6688.com/cyzhtest/#/";
        if(this.billrecord.bankCode == null){
          this.$message({
            type: "error",
            message: "请选择银行卡"
          })
          return;
        }
        getParamDetail({"paramKey":"maintain"}).then(res => {
          let systemParam = res.data.data;
          let paramValue = systemParam.paramValue;
          if(paramValue == "0"){
            this.isLoading = false;
            this.$message({
              type: "fail",
              message: "系统维护时间为每天晚上22:00-凌晨07:00"
            });
            this.$emit('finishSubmit', null);
          }else{
            addBillrecord(this.billrecord).then((res) => {
              this.isLoading = false;
              this.chongzhiVisible = false;
              this.$emit('finishSubmit', null);
              location.href = res.data.data
            }).catch(err => {
              this.isLoading = false;
            })
          }
        })
    },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          data.records.forEach(item => {item.amount = 0.00; item.purchaseNum = 0})
          this.data = data.records;
          this.loading = false;
        });
      },
      //金额大写
      digitUppercase(money){
        let fraction = ['角', '分'];
        let digit = [
          '零', '壹', '贰', '叁', '肆',
          '伍', '陆', '柒', '捌', '玖'
        ];
        let unit = [
          ['元', '万', '亿'],
          ['', '拾', '佰', '仟']
        ];
        let head = money < 0 ? '欠' : '';
        money = Math.abs(money);
        let s = '';
        for (let i = 0; i < fraction.length; i++) {
          s += (digit[Math.floor(money * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
        }
        s = s || '整';
        money = Math.floor(money);
        for (let i = 0; i < unit[0].length && money > 0; i++) {
          let p = '';
          for (let j = 0; j < unit[1].length && money > 0; j++) {
            p = digit[money % 10] + unit[1][j] + p;
            money = Math.floor(money / 10);
          }
          s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
        }
        return head + s.replace(/(零.)*零元/, '元')
                .replace(/(零.)+/g, '零')
                .replace(/^整$/, '零元整');
      }
    }
  };
</script>

<style>
</style>
