<template>
  <basic-container>
    <el-dialog :modal-append-to-body="false" :visible.sync="editBussinessVisible" title="编辑资料" width="80%">
      <avue-form v-if="editBussinessVisible" :table-loading="loading" v-model="bussiness" :option="bussinessOption"
        @reset-change="emptytChange" @submit="submitBussiness()">

      </avue-form>
    </el-dialog>
    <el-dialog :modal-append-to-body="false" :visible.sync="chongzhiVisible" title="采购页面" width="70%" center top="2vh" modal="true">
      <div v-if="chongzhiVisible">
        <purchase :serviceRate="bussiness.serviceRate" v-if="chongzhiVisible" @finishSubmit="finishSubmit"></purchase>
      </div>
    </el-dialog>

    <el-card v-if="permission.account_static">
      <el-row :gutter="50">
        <el-col :span="24">
          <accountstatic head="采购商财务账本" :statData="bussinessaccountData"></accountstatic>
        </el-col>

      </el-row>

    </el-card>

    <el-card v-if="permission.bussiness_screen" :span="24">
      <el-row>
        <div>
          <el-row :gutter="50">
            <el-col span="12">
              <div style="background: linear-gradient(-125deg, #2f9de2, #4d4dff);border-radius: 30px;">
                <avue-avatar style="margin:20px;" :size="128" :src="bussiness.icon"></avue-avatar>
                <span style="color: white;">{{bussiness.name}}</span>
                <span style="color: white;margin-left: 40px;">API密钥:</span> <span style="color: white;margin-left:10px">******</span>
                <span style="margin-left: 10px;">
                  <el-tooltip content="API密钥用于接口对接,请谨慎保存" placement="bottom" effect="dark">
                    <el-button type="primary" size="mini" @click="doCopy()">
                      复制
                    </el-button>
                  </el-tooltip>
                </span>
                <span style="font-weight: bold; margin-left: 30px;">
                  <el-link target="_blank" type="success" :href="bussiness.apiFilePath">Api文档下载(打开需输入密钥)</el-link>
                </span>
                <div>
                  <el-button style="margin-left:50px;" type="primary" class="button" @click="editBussiness">商户配置（可设置回调地址）</el-button>
                  <span style="color: white;margin-left: 40px;">服务费率(千分比)：{{bussiness.serviceRate}}</span>
                  <span style="color: white;margin-left: 40px;">每日限额(元)：{{bussiness.maxLimit}}</span>
                </div>
                <div style="color: white;margin-left: 20px;margin-top:30px;">
                  <span style="color: white;">商户回调地址：{{bussiness.recallUrl}}</span>
                </div>
                <div style="margin-left: 20px;margin-top:30px;">
                  <span style="color: white;">账户余额</span>
                </div>
                <div style="margin-left: 20px;margin-top:10px;padding-bottom: 20px;">
                  <span>
                    <avue-avatar style="margin-bottom: 30px;" src="/img/bg/rmb.png"></avue-avatar>
                  </span>
                  <span style="font-size:60px;margin-left:20px;margin-bottom: 20px;color:white;">
                    {{bussiness.remain}}
                  </span>
                </div>
                <!--<div style="margin-left: 20px;margin-top:30px;">
                  <span style="color: white;">在途金额</span>
                </div>
                <div style="margin-left: 20px;margin-top:10px;padding-bottom: 20px;">
                  <span>
                    <avue-avatar style="margin-bottom: 30px;" src="/img/bg/rmb.png"></avue-avatar>
                  </span>
                  <span style="font-size:60px;margin-left:20px;margin-bottom: 20px;color:white;">
                    {{bussiness.freeze}}
                  </span>
                </div>-->
              </div>
            </el-col>
            <el-col span="12" height="400px">
              <el-row :gutter="50">
                <!--<el-col span="12">
                  <div style="background-color: #4d4dff;border-radius: 30px;" align="center" @click="chongzhi">
                    <img style="margin:10px;" float="center" :size="30" src="/img/bg/qb.png" />
                    <div style="color: white;padding-bottom: 10px;">
                      商户采购
                    </div>
                  </div>
                </el-col>-->
                <el-col span="12">
                  <div style="background-color: #ff5050;border-radius: 30px;" align="center" @click="toMyOrder">
                    <img style="margin:10px;" float="center" :size="30" src="/img/bg/zd.png" />
                    <div style="color: white;padding-bottom: 10px;">
                      我的账单
                    </div>
                  </div>
                </el-col>
              </el-row>
              <el-row :gutter="50">
                <el-col span="12">
                  <div style="background-color:  #d633ff;border-radius: 30px;" align="center" @click="toMyDebit">
                    <img style="margin:10px;" float="center" :size="30" src="/img/bg/fxfr.png" />
                    <div style="color: white;padding-bottom: 10px;">
                      分销分润
                    </div>
                  </div>
                </el-col>
                <el-col span="12">
                  <div style="background-color: #8080ff;border-radius: 30px;" align="center" @click="toBin">
                    <img style="margin:10px;" float="center" :size="30" src="/img/bg/sm.png" />
                    <div style="color: white;padding-bottom: 10px;">
                      卡bin查询
                    </div>
                  </div>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </div>
      </el-row>

    </el-card>

  </basic-container>
</template>
<script>
  import request from '@/router/axios';
  import echarts from "echarts";
  import accountstatic from "@/components/index/accountstatic.vue"
  import purchase from "./purchase.vue"
  import {
    getByAccount,
    update
  } from "@/api/guosen/bussiness"
  import {
    mapGetters
  } from "vuex";
  export default {
    components: {
      accountstatic,purchase
    },

    data() {
      return {
        agenteraccountData:{},
        useraccountData: {},
        bussinessaccountData: {
          todayIn: null,
          todayOut:null,
          historyIn:null,
          historyOut:null
        },
        loading: true,
        editBussinessVisible: false,
        moneyChina: "壹拾万元整",
        bussiness: {},
        statDatas: [
          {
            key: "技术服务费率",
            value: 0
          },
          {
            key: "技术服务费",
            value: 0
          },
          {
            key: "采购金额",
            value: 0
          },
          {
            key: "可用余额",
            value: 0
          }

        ],
        yibaoOrder: {

        },
        billrecord: {
          payStatus: 0,
          type: 5
        },
        money: 100000,
        serviceRate: 0.005,
        chongzhiVisible: false,
        buttonDay: "primary",
        buttonMonth: "",
        selectDate: [],
        dateType: "daterange",
        dataPlace: "选择日期",
        query: {
          staticType: 1
        },
        tgOption: {
          span: 8,
          data: [{
              count: "66.6万",
              title: '总曝光量',
            },
            {
              count: '88.8万',
              title: '总点击率',

            },
            {
              count: '688万',
              title: '总访问量',

            },
            {
              count: '6666',
              title: '今日曝光量',

            },
            {
              count: '6666',
              title: '今日点击率',

            },
            {
              count: '6666',
              title: '今日访问量',

            }
          ]
        },

        bussiness_option2: {
          span: 12,
          data: [{
            click: function(item) {
              alert(JSON.stringify(item));
            },
            count: '150',
            title: '采购',
            icon: 'el-icon-warning',
            color: 'rgb(49, 180, 141)'
          }, {
            click: function(item) {
              alert(JSON.stringify(item));
            },
            count: '53%',
            title: '跳出率',
            icon: 'el-icon-view',
            color: '#00a65a'
          }, {
            click: function(item) {
              alert(JSON.stringify(item));
            },
            count: '44',
            title: '用户注册数',
            icon: 'el-icon-setting',
            color: '#f39c12'
          }]
        },
        bussinessOption: {
          height: 'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          dialogWidth: "30%",
          column: [{
              label: "采购商名称",
              labelWidth: 130,
              prop: "name",
              span: 24,
              rules: [{
                required: true,
                message: "请输入采购商名称",
                trigger: "blur"
              }]
            },



            {
              label: "api回调地址",
              prop: "recallUrl",
              labelWidth: 130,
              span: 24,
              hide: true,
              placeholder: "请输入回调地址,比如：http://xxx.xxx.xxx.xxx/xxx",
              rules: [{
                required: false,
                message: "请输入回调地址,比如：http://xxx.xxx.xxx.xxx/xxx",
                trigger: "blur"
              }]
            },
            {
              label: "广告图",
              prop: "icon",
              labelWidth: 130,
              span: 12,
              type: "upload",
              listType: "picture-img",
              action: '/api/putObject',
              propsHttp: {
                url: 'data'
              },
              rules: [{
                required: false,
                message: "请输入营业执照",
                trigger: "blur"
              }]
            },
            {
              label: "营业执照",
              prop: "businessLicense",
              labelWidth: 130,
              span: 12,
              type: "upload",
              listType: "picture-img",
              action: '/api/putObject',
              propsHttp: {
                url: 'data'
              },
              rules: [{
                required: false,
                message: "请输入营业执照",
                trigger: "blur"
              }]
            },
            {
              label: "税务登记证",
              prop: "taxAffairsLicense",
              labelWidth: 130,
              type: "upload",
              listType: "picture-img",
              action: '/api/putObject',
              propsHttp: {
                url: 'data'
              },
              span: 12,
              rules: [{
                required: false,
                message: "请输入税务登记证",
                trigger: "blur"
              }]
            },
            {
              label: "组织机构代码证",
              prop: "organizationCodeLicense",
              labelWidth: 130,
              span: 12,
              type: "upload",
              listType: "picture-img",
              action: '/api/putObject',
              propsHttp: {
                url: 'data'
              },
              rules: [{
                required: false,
                message: "请输入关联账号的密码",
                trigger: "blur"
              }]
            },
            {
              label: "关联账号的id",
              prop: "accountId",
              hide: true,
              display: false,
              rules: [{
                required: true,
                message: "请输入关联账号的id",
                trigger: "blur"
              }]
            },
          ]
        },
        bussiness_option1: {
          height: "500px",
          span: 24,
          data: [{
              click: function(item) {
                alert(JSON.stringify(item));
              },

              title: '分类统计',
              subtitle: '实时',
              count: 7993,
              allcount: 10222,
              text: '当前分类总记录数',
              color: 'rgb(27, 201, 142)',
              key: '类'
            },

          ]
        },

      }
    },
    computed: {
      ...mapGetters(["permission", "userInfo"])

    },
    watch: {
      "money"() {

        if (this.money < 0) {
          this.money = 1;
        }
        // this.moneyChina = this.convertCurrency(this.money)
        this.statDatas[0].value = this.bussiness.serviceRate / 1000
        this.statDatas[1].value = this.money * this.bussiness.serviceRate / 1000
        this.statDatas[2].value = parseFloat(this.money)
        this.statDatas[3].value = parseFloat(this.statDatas[2].value) - parseFloat(this.statDatas[1].value)
      },
    },
    mounted() {
      var _that = this;

      // this.type = this.tabsOption.column[0];
      let befDate = new Date();
      let byear = befDate.getFullYear();
      let bmonth = befDate.getMonth() + 1;
      let bday = befDate.getDate();
      let startTime = `${byear}-${bmonth}-${bday}`;
      this.selectDate = [startTime, startTime];

      this.getData();
      this.getOrderCommissionData();
      this.getAccoutStatic()



      getByAccount().then(res => {
        if(res.data.data){
          _that.bussiness = res.data.data
          _that.statDatas[0].value = res.data.data.serviceRate / 1000
          _that.statDatas[1].value = _that.money * _that.statDatas[0].value
          _that.statDatas[2].value = _that.money
          _that.statDatas[3].value = _that.statDatas[2].value - _that.statDatas[1].value
          console.log("buss" + JSON.stringify(_that.bussiness))
        }
      })

    },
    methods: {
      submitBussiness() {
        this.bussiness.userPassword = null;
        this.bussiness.leastPrice = null;
        update(this.bussiness).then(res => {
          this.$message({
            type: "success",
            message: res.data.msg
          });
          this.editBussinessVisible = false;
        })

      },
      /*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 '';
        }
        if (money == 0) {
          chineseStr = cnNums[0] + cnIntLast + cnInteger;
          return chineseStr;
        }
        //转换为字符串
        money = money.toString();
        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) {
          var zeroCount = 0;
          var IntLen = integerNum.length;
          for (let i = 0; i < IntLen; i++) {
            var n = integerNum.substr(i, 1);
            var p = IntLen - i - 1;
            var q = p / 4;
            var 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 != '') {
          var decLen = decimalNum.length;
          for (var i = 0; i < decLen; i++) {
            var 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;
      },*/

      editBussiness() {
        this.editBussinessVisible = true;

      },
      doCopy() {
        this.$copyText(this.bussiness.secret)
        this.$message.success("复制成功")
      },
      toMyDebit() {
        this.$router.push('/guosen/bussinessdebitrequest');
      },
      toBin() {
        this.$router.push('/guosen/bankcode');
      },
      toMyOrder() {
        this.$router.push('/bussiness/order');
      },
      guid() {
        var str = "abcdefghijklmnopqrstuvwxyz0123456789"; // 可以作为常量放到random外面
        var result = "";
        for (var i = 0; i < 32; i++) {
          result += str[parseInt(Math.random() * str.length)];
        }
        return result;

      },
      chongzhi() {
        this.chongzhiVisible = true;
      },

      //按日
      handleDay() {
        this.buttonDay = "primary";
        this.buttonMonth = "";
        this.query.staticType = 1;
        this.dateType = "daterange";
        this.dataPlace = "选择日期";
      },

      //按月
      handleMonth() {
        this.buttonDay = "";
        this.buttonMonth = "primary";
        this.query.staticType = 2;
        this.dateType = "monthrange";
        this.dataPlace = "选择月份";
      },
      getAccoutStatic() {
        let that = this;
        request({
          url: '/api/cyzh-static/adStaticAccountStatic',
          method: "get",
        }).then(res => {
          //今日分润
          let todayOut = res.data.data.todayOut;
          that.useraccountData.todayOut = todayOut.userOut;
          that.agenteraccountData.todayOut = todayOut.proxyOut;
          that.bussinessaccountData.todayOut = todayOut.adsOut;
          //历史提现
          let historyOut = res.data.data.totalOut;
          that.useraccountData.historyOut = historyOut.userOut;
          that.agenteraccountData.historyOut = historyOut.proxyOut;
          that.bussinessaccountData.historyOut = historyOut.adsOut;

          //今日采购
          let todayIn = res.data.data.todayIn;
          that.useraccountData.todayIn = todayIn.userIn;
          that.agenteraccountData.todayIn = todayIn.proxyIn;
          that.bussinessaccountData.todayIn = todayIn.adsIn;

          //历史收入
          let historyIn = res.data.data.totalIn;
          that.useraccountData.historyIn = historyIn.userIn;
          that.agenteraccountData.historyIn = historyIn.proxyIn;
          that.bussinessaccountData.historyIn = historyIn.adsIn;
          that.$forceUpdate()

          that.drawPie();
        })
      },
      getOrderCommissionData() {
        this.query.beginDate = this.selectDate[0];
        this.query.endDate = this.selectDate[1];
        request({
          url: '/api/cyzh-static/staticOrderCommission',
          method: "post",
          data: this.query
        }).then(res => {
          this.drawRealDemandLine(res.data.data.dateList, res.data.data.unClearList, res.data.data.clearedList)
        })
      },
      getData() {

        request({
          url: '/api/cyzh-static/static',
          method: "get"
        }).then(res => {
          const resData = res.data.data;
          if(!resData.userCount){
            this.optionMusic.data[0].count = resData.userCount;
            this.optionMusic.data[1].count = resData.agenterCount;
            this.optionMusic.data[2].count = resData.activityCount;
            this.optionMusic.data[3].count = resData.shopCount;
          }
        })
      },
      finishSubmit(){
        this.chongzhiVisible = false;
      },
      handleStatic() {
        this.getOrderCommissionData();
      },

      drawPie() {
        let $todayOut = document.getElementById('todayOut');
        if(!$todayOut){
          return ;
        }
        let todayOutChart = echarts.init($todayOut);
        todayOutChart.setOption(this.optionTodayOut);

        let histroyOuntChart = echarts.init(document.getElementById('historyOut'));
        histroyOuntChart.setOption(this.optionHistoryOut);

        let todayInChart = echarts.init(document.getElementById('todayIn'));
        todayInChart.setOption(this.optionTodayIn);

        let historyInChart = echarts.init(document.getElementById('historyIn'));
        historyInChart.setOption(this.optionHistoryIn);
      },
      //柱形图
      drawRealDemandLine(dateList, unclearDataList, clearedDataList) {
        // 基于准备好的dom，初始化echarts实例
        let $orderStatistics = document.getElementById('orderStatistics');
        if (!$orderStatistics) return;
        let myChart = echarts.init($orderStatistics)
        // 基于准备好的dom，初始化echarts实例
        // 绘制图表
        myChart.setOption({
          title: {
            text: ''
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: { //直角坐标系内绘图网格
            show: true, //是否显示直角坐标系网格。[ default: false ]
            left: "10%", //grid 组件离容器左侧的距离。
            right: "30px",
            borderColor: "#c45455", //网格的边框颜色
            bottom: "20%" //
          },
          legend: {
            data: ['待结算', '已结算'],
            show: true,
          },
          // x轴拖动
          dataZoom: [{
            type: "slider",
            realtime: true, //拖动滚动条时是否动态的更新图表数据
            height: 25, //滚动条高度
            start: 0, //滚动条开始位置（共100等份）
            end: 100 //结束位置（共100等份）
          }],

          xAxis: {
            data: dateList,
            axisLabel: { //坐标轴刻度标签的相关设置。
              interval: 0,
              rotate: "45"
            }
          },
          yAxis: {},
          series: [{
            name: '待结算',
            type: 'bar',
            stack: '佣金',
            data: unclearDataList
          }, {
            name: '已结算',
            type: 'bar',
            stack: '佣金',
            data: clearedDataList
          }]
        });
      }
    }

  }
</script>

<style>
  .button {
    padding: 10;
    float: center;
  }

  .image {
    width: 35%;
    display: block;
    border-radius: 65px;
  }

  .myTable {
    border-collapse: collapse;
    margin: 0 auto;
    text-align: center;
  }
</style>
