<template>
  <!--
      所有账户余额： 仅开启多账户模式时，显示此字段       部门权限为可见所有的用户或者超管登录时可显示【所有账户余额】字段；
      账户明细按钮： 仅开启多账户模式时，显示此字段       开启多账户模式下的超管可见 || 开启多账户模式下的子账号部门权限为所有并且赋予了【
      】操作按钮权限时可见
      首次开启多账户计费规则时，点击保存按钮则弹框二次提示，保存成功后显示保存成功弹框，点击保存成功
      计费部门筛选框规则：开启多账户计费模式时显示计费部门筛选框； && 超管和部门权限为可见所有的子账号显示计费部门筛选框；
  -->
  <section class="recharge">
    <div class="dm-wrap" style="margin-bottom: 4px">
      <dm-sub-title title-align="space-between">
        账户概览
        <el-button v-if="$getButtonLimit($buttonCode.marketingAccountRule)" :limit-code="$buttonCode.marketingAccountRule" class="h32 ghost-btn" type="primary" @click="setRuleVisible = true">计费规则配置</el-button>
      </dm-sub-title>
      <div class="money_wrap">
        <div class="current">
          <div class="sub_title">
            账户余额（元）
            <span v-if="config.isMoreAccount">(当前所在计费部门：{{ config.departmentName }})</span>
          </div>
          <p class="fz22 vertical-middle money">
            <span v-if="$getButtonLimit($buttonCode.marketingRechargeBoardRecord)" class="active" @click="$router.push('/recharge/record')">{{ (config.balance / 100) | amount }}<i class="el-icon-arrow-right arrow"/></span>
            <span v-else>{{ (config.balance / 100) | amount }}<i class="el-icon-arrow-right arrow"/></span>
          </p>
          <el-button v-if="$getButtonLimit($buttonCode.marketingRechargeBoardRecharge)" :limit-code="$buttonCode.marketingRechargeBoardRecharge" class="vertical-middle pl20 pr20" type="primary" @click="$router.push('/recharge/do')">充值</el-button>
          <el-button v-if="$getButtonLimit($buttonCode.marketingRechargeBoardRecord)" :limit-code="$buttonCode.marketingRechargeBoardRecord" class="vertical-middle pl20 pr20" @click="$router.push('/recharge/record')">记录</el-button>
        </div>
        <div class="all" v-if="config.isMoreAccount && config.showAllBlance">
          <div class="sub_title">
            所有账户余额（元）<span class="tip"><i class="iconfont icon-anquanbaozhang" />已开启多账户计费模式</span>
          </div>
          <p class="fz22 vertical-middle money">
            <span v-if="$getButtonLimit($buttonCode.marketingAccountDetail)" class="active" @click="$router.push('/recharge/accountDetail')">{{ (config.allDepartmentTotal / 100) | amount }}<i class="el-icon-arrow-right arrow"/></span>
            <span v-else>{{ (config.allDepartmentTotal / 100) | amount }}<i class="el-icon-arrow-right arrow"/></span>
          </p>
          <!--该按钮待埋点-->
          <el-button v-if="$getButtonLimit($buttonCode.marketingAccountDetail)" :limit-code="$buttonCode.marketingAccountDetail" class="vertical-middle" @click="$router.push('/recharge/accountDetail')">账户明细</el-button>
        </div>
      </div>
    </div>
    <div class="dm-wrap" style="border-top:1px solid #E4E7ED">
      <dm-sub-title class="mb10">今日消费</dm-sub-title>
      <select-depart v-if="config.isMoreAccount && config.showAllDepartment" :data="deparment1" class="mb20" @load="() => load('one')" @getDepartId="id => getDepartId(id, 'one')" @remote-search="val => remoteSearch(val, 'one')" :loading="deparment1.loading" />
      <el-row class="recharge-today" :gutter="20" v-loading="loading1">
        <el-col :span="6" style="padding: 0 2px">
          <div class="recharge-today-item border2">
            <div class="text-center">
              <div class="icon-box">
                <i class="iconfont icon-wenbenmsg fz36"></i>
              </div>
            </div>
            <div class="consume-info">
              <div class="consume-item">
                <p class="consume-item-label">短信营销</p>
                <p class="consume-item-value">
                  <span class="value-content">{{ recharge.messageCount || 0 }}</span> 条
                </p>
              </div>
              <div class="consume-item">
                <p class="consume-item-label">合计费用</p>
                <p class="consume-item-value">
                  <span class="value-content">{{ (recharge.messageFee / 1000) | amount }}</span> 元
                </p>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="6" style="padding: 0 2px">
          <div class="recharge-today-item border2">
            <div class="text-center">
              <div class="icon-box color2">
                <i class="iconfont icon-duanxinyzm fz28"></i>
              </div>
            </div>
            <div class="consume-info">
              <div class="consume-item">
                <p class="consume-item-label">短信验证码</p>
                <p class="consume-item-value">
                  <span class="value-content">{{ recharge.smsCount || 0 }}</span> 条
                </p>
              </div>
              <div class="consume-item">
                <p class="consume-item-label">合计费用</p>
                <p class="consume-item-value">
                  <span class="value-content">{{ (recharge.smsFee / 1000) | amount }}</span> 元
                </p>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="6" style="padding: 0 2px">
          <div class="recharge-today-item border2">
            <div class="text-center">
              <div class="icon-box color3">
                <i class="iconfont icon-shuangxianghujiao1 fz36"></i>
              </div>
            </div>
            <div class="consume-info">
              <div class="consume-item">
                <p class="consume-item-label">双向呼叫</p>
                <p class="consume-item-value">
                  <span class="value-content">{{ recharge.callTime || 0 }}</span> 分钟
                </p>
              </div>
              <div class="consume-item">
                <p class="consume-item-label">合计费用</p>
                <p class="consume-item-value">
                  <span class="value-content">{{ (recharge.callFee / 1000) | amount }}</span> 元
                </p>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="6" style="padding: 0 2px">
          <div class="recharge-today-item border2">
            <div class="text-center">
              <div class="icon-box color4">
                <i class="iconfont icon-AIdianhua  fz36"></i>
              </div>
            </div>
            <div class="consume-info">
              <div class="consume-item">
                <p class="consume-item-label">AI电话</p>
                <p class="consume-item-value">
                  <span class="value-content">{{ recharge.aiCount || 0 }}</span> 分钟
                </p>
              </div>
              <div class="consume-item">
                <p class="consume-item-label">合计费用</p>
                <p class="consume-item-value">
                  <span class="value-content">{{ (recharge.aiFee / 1000) | amount }}</span> 元
                </p>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="dm-wrap" style="padding-top: 0">
      <div class="pb22">
        <div slot="header" class="clearfix">
          <el-date-picker :pickerOptions="pickerOptions" v-model="dateTime" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" @change="consumeRecord('two')" @click.native="minDate = null"></el-date-picker>
          <select-depart v-if="config.isMoreAccount && config.showAllDepartment" :data="deparment2" @load="() => load('two')" @getDepartId="id => getDepartId(id, 'two')" @remote-search="val => remoteSearch(val, 'two')" :loading="deparment2.loading" />
          <span class="fz12 gray">* 此处仅支持筛选近半年的统计数据，最大查询区间为1个月</span>
        </div>
      </div>
      <el-table tooltipEffect="light" :data="tableList" style="width: 100%" v-loading="loading2">
        <el-table-column align="left" prop="name" label="计费项目"></el-table-column>
        <el-table-column align="left" prop="count" label="时长/条数">
          <template slot-scope="scope">
            <template v-if="scope.row.type === 'video'">{{ scope.row.count || 0 }} G</template>
            <template v-else>
              <span>{{ scope.row.count }}</span>
              {{ scope.row.type === 'call' || scope.row.type === 'record' || scope.row.type == 'ai-call' ? '分钟' : '条' }}
            </template>
          </template>
        </el-table-column>
        <el-table-column align="left" prop="fee" label="费用(元)">
          <template slot="header" slot-scope="scope">
            费用(元)
            <el-tooltip :open-delay="200" class="item" effect="dark" placement="top">
              <div slot="content" style="width:300px;line-height:1.5;" :key="scope.$index">由于运营商的计费单价会有调整以及海外短信是按不同地区进行费用扣除。但此处是用统一用当下的单价乘以计费条数进行合计，所以可能导致此处的费用和详情不一致，最终以详情的合计金额为准。</div>
              <i class="iconfont icon-QuestionCircleOutlined minor-font-color cursor-pointer ml5"></i>
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <span->{{ (scope.row.fee / (scope.row.type === 'record' ? 100 : 1000)).toFixed(2) }}</span->
          </template>
        </el-table-column>
        <el-table-column label="操作" align="left" width="220px" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" v-if="$getButtonLimit($buttonCode.marketingCounsumeDetail)" :limit-code="$buttonCode.marketingCounsumeDetail" @click="$router.push('/recharge/consume/' + scope.row.type)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <set-rule-drawer :visible.sync="setRuleVisible" :data="accountRule" @getNewData="callBackSave" />
  </section>
</template>

<script>
import { rechargeCenter, consumeRecord, todayVideoTraffic, getDepartList, getAccountRule } from '@/service/api/rechargeApi.js';
import { formatDateTimeByType } from '@/utils/index.js';
import SelectDepart from './components/select-depart.vue';
import setRuleDrawer from './components/set-rule-dialog.vue';
export default {
  name: 'recharge',
  components: {
    SelectDepart,
    setRuleDrawer
  },
  data() {
    return {
      dateTime: [Date.now(), Date.now()],
      minDate: new Date(),
      maxDate: new Date(),
      loading1: false,
      loading2: false,
      tableList: [],
      recharge: {},
      listParams: {
        beginTime: '',
        endTime: '',
        accountDepartId: ''
      },
      videoTraffic: {},
      pickerOptions: {
        disabledDate: val => {
          // 只能筛选半年之内得数据,并且最大跨度为一个月
          const halfYearBefore = Date.now() - 6 * 30 * 24 * 60 * 60 * 1000;
          const oneMothods = 30 * 24 * 60 * 60 * 1000;
          if (this.minDate) {
            const curTime = this.minDate.getTime();
            const min = curTime - oneMothods > halfYearBefore ? curTime - oneMothods : halfYearBefore;
            return val.getTime() > curTime + oneMothods || val.getTime() < min || val.getTime() > this.maxDate.getTime();
          }
          return val.getTime() <= halfYearBefore || val.getTime() > this.maxDate.getTime();
        },
        onPick: ({ maxDate, minDate }) => {
          this.minDate = minDate;
        }
      },
      deparment1: {
        list: [],
        searchParams: '',
        status: -1,
        pageSize: 20,
        currentPage: 1,
        loading: false,
        isLimit: false, // 是否最后一页
        departId: '', // 选中时得id
        zbFlag: 1
      },
      deparment2: {
        list: [],
        searchParams: '',
        status: -1,
        pageSize: 20,
        currentPage: 1,
        loading: false,
        isLimit: false,
        departId: '', // 选中时得id
        zbFlag: 1
      },
      accountRule: {},
      setRuleVisible: false,
      config: {
        isMoreAccount: false, // 是否多账户
        showAllDepartment: false, // 是否超管或部门权限为可见所有的用户
        departmentName: '', // 当前账户名称
        accountDepartId: '', // 普通商户(不是超管也不是部门权限为可见所有)进来时自身得账号部门Id
        allDepartmentTotal: '', // 多商户时所有账账户余额
        balance: '', // 当前账户余额
        showAllBlance: false // 是否展示账户余额
      }
    };
  },
  async created() {
    this.$store.commit('aside_handler', false);
    // this.getTodayVideoTraffic();
    this.getDepartmentList();
    this.$store.commit('mutations_breadcrumb', [{ name: '企业管理', path: '' }, { name: '计费中心', path: '' }]); // eslint-disable-line
    await this.rechargeCenter(); // 该接口返回权限字段需要控制下面接口内容
    await this.getRule();
    this.consumeRecord('one');
    this.consumeRecord('two');
  },
  filters: {
    // 金额处理 保留2位小数
    amount: function(value) {
      if (!value) return '0.00';
      if (isNaN(value)) return value;
      return value.toFixed(2);
    }
  },
  methods: {
    // 视频流量资费
    async getTodayVideoTraffic() {
      try {
        let res = await todayVideoTraffic();
        this.videoTraffic = res.result || {};
      } catch (err) {
        console.log(err);
      }
    },
    async rechargeCenter() {
      try {
        let res = await rechargeCenter();
        this.extend(this.config, res.result.account);
        this.deparment1.departId = this.config.accountDepartId;
        this.deparment2.departId = this.config.accountDepartId;
        return true;
      } catch (err) {
        console.log(err);
      }
    },
    async consumeRecord(type) {
      const depart = type == 'one' ? this.deparment1 : this.deparment2;
      const para = this.listParams;
      const loading = type == 'one' ? 'loading1' : 'loading2';
      console.log(loading);
      this[loading] = true;
      if (this.dateTime) {
        para.beginTime = formatDateTimeByType(this.dateTime[0], 'yyyy-MM-dd');
        para.endTime = formatDateTimeByType(this.dateTime[1], 'yyyy-MM-dd');
      } else {
        para.beginTime = '';
        para.endTime = '';
      }
      if (type == 'one') {
        delete para.beginTime;
        delete para.endTime;
      }
      const id = this.setAccountDepartId(depart.departId);
      if (id) para.accountDepartId = id;
      else {
        delete para.accountDepartId;
      }
      try {
        let res = await consumeRecord(para);
        const result = res.result;
        // , { name: '视频流量', type: 'video', fee: result.allTraffic, count: result.allTrafficCost }
        if (type != 'one') {
          this.tableList = [
            { name: '短信营销', type: 'marketing', fee: result.messageFee, count: result.messageCount },
            { name: '短信验证码', type: 'sms', fee: result.smsFee, count: result.smsCount },
            { name: '双向呼叫', type: 'call', fee: result.callFee, count: result.callTime },
            { name: 'AI电话', type: 'ai-call', fee: result.aiFee, count: result.aiCount }
          ];
        } else {
          this.recharge = res.result;
        }
      } catch (err) {
        console.log(err);
      }
      this[loading] = false;
    },
    // 获取计费部门
    async getDepartmentList(type) {
      // 该方法对不同得计费部门下拉做处理, 默认初始加载取deparment1 || deparment2均可，因为参数相同
      const depart = type == 'one' ? this.deparment1 : this.deparment2;
      depart['loading'] = true;
      const para = Object.assign({}, depart);
      const typeArr = ['list', 'loading', 'isLimit', 'departId'];
      this.deleteAttribute(para, typeArr);
      let { result } = await getDepartList(para);
      if (type) {
        this.setDepartData(depart, result);
      } else {
        this.setDepartData(this.deparment1, result);
        this.setDepartData(this.deparment2, result);
      }
    },
    // 清除接口无用属性
    deleteAttribute(obj, typeArr) {
      for (const key in obj) {
        if (typeArr.includes(key)) delete obj[key];
      }
    },
    // 设置departmentData
    setDepartData(obj, result) {
      const data = result.result || [];
      const total = result.totalCount;
      obj['list'].push(...data);
      obj['isLimit'] = obj['list'].length >= total; // list得数据量>=数据总数时做出限制
      obj['loading'] = false;
    },
    // 下拉滚动加载
    load(type) {
      const depart = type == 'one' ? this.deparment1 : this.deparment2;
      if (depart['isLimit'] || depart['loading']) return;
      depart['currentPage']++;
      this.getDepartmentList(type);
    },
    getDepartId(id, type) {
      // 选中不同下拉得id时，调用对应得表格方法
      const depart = type == 'one' ? this.deparment1 : this.deparment2;
      depart['departId'] = id;
      this.consumeRecord(type);
    },
    // 下拉远程搜索
    remoteSearch(val, type) {
      const depart = type == 'one' ? this.deparment1 : this.deparment2;
      depart['searchParams'] = val.trim();
      depart['currentPage'] = 1;
      depart['isLimit'] = false;
      depart['list'] = [];
      this.getDepartmentList(type);
    },
    // 获取计费规则
    async getRule() {
      const result = await getAccountRule();
      this.accountRule = result.result || {};
      this.config.isMoreAccount = !!this.accountRule.status;
      return true;
    },
    // 保存了计费规则
    async callBackSave(cbOther) {
      if (cbOther) {
        // 多商户改变配置就重新调接口
        await this.getRule();
        this.consumeRecord('one');
        this.consumeRecord('two');
      } else {
        this.getRule();
      }
    },
    extend(to, from) {
      for (let key in to) {
        if (!from.hasOwnProperty(key)) continue;
        to[key] = from[key];
      }
    }
  },
  computed: {
    setAccountDepartId() {
      const { isMoreAccount, showAllDepartment, accountDepartId: defaultAccountId } = this.config;
      return id => (isMoreAccount ? (showAllDepartment ? id : defaultAccountId) : defaultAccountId);
    }
  }
};
</script>

<style lang="scss" scoped>
.recharge {
  font-family: PingFangSC-Regular, PingFang SC;
}
.recharge .box-card {
  margin: 24px;
}
.recharge-today {
  .el-col-5 {
    width: 20% !important;
  }
  &-item {
    display: flex;
    justify-content: space-between;
    align-items: stretch;
    // padding: 15px;
    padding: 5.4%;
    margin: 4px;
    .consume-info {
      display: flex;
      justify-content: space-between;
      align-items: stretch;
      margin-left: 12px;
      width: calc(100% - 72px);
      .consume-item {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        align-items: flex-start;
        width: 50%;
        + .consume-item {
          align-items: flex-end;
          .consume-item-value {
            justify-content: flex-end;
          }
        }
        .consume-item-label {
          font-size: 14px;
          font-weight: 400;
          color: #303133;
          line-height: 20px;
        }
        .consume-item-value {
          display: flex;
          justify-content: flex-start;
          align-items: flex-end;
          width: 100%;
          font-size: 14px;
          font-weight: 400;
          color: #303133;
          line-height: 20px;
          .value-content {
            margin-right: 5px;
            transform: translateY(3px);
            font-size: 22px;
            font-weight: 600;
            color: #303133;
            line-height: 30px;
            display: inline-block;
            max-width: 100%;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
      }
    }
    .icon-box {
      width: 60px;
      height: 60px;
      background: rgba(253, 107, 56, 0.15);
      border-radius: 4px;
      i {
        line-height: 60px;
        color: #fd6b38;
      }
      &.color2 {
        background: rgba(38, 218, 208, 0.15);
        i {
          color: #26dad0;
        }
      }
      &.color3 {
        background: rgba(92, 137, 255, 0.15);
        i {
          color: #5c89ff;
        }
      }
      &.color4 {
        background: rgba(250, 140, 22, 0.15);
        i {
          color: #fa8c16;
        }
      }
    }
    .fl {
      line-height: 24px;
      p {
        color: #353944;
        margin-top: 5px;
      }
    }
    .fr {
      line-height: 40px;
      position: relative;
      top: 10px;
    }
    .iconfont {
      color: #fff;
    }
  }
}
.money_wrap {
  display: flex;
  margin-top: 10px;
  .current,
  .all {
    flex: 1;
  }
  .sub_title {
    color: #606266;
    line-height: 20px;
  }
  .money {
    margin: 6px 0 40px;
    font-size: 26px;
    font-family: PingFangSC-Semibold, PingFang SC;
    color: #303133;
    line-height: 37px;
    & span {
      font-weight: 600;
      i {
        position: relative;
        top: -4px;
      }
      &.active {
        cursor: pointer;
        &:hover {
          color: #2f54eb;
          .arrow {
            color: #2f54eb;
          }
        }
      }
    }
    .arrow {
      margin-left: 4px;
      color: #909399;
    }
  }
  .tip {
    color: #606266;
    line-height: 20px;
    font-size: 12px;
    i {
      color: #2f54eb;
      margin-right: 5px;
    }
  }
}
.flex_between {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  width: 100%;
}
.flex_column {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.flex1 {
  flex: 1;
}
.fz22 {
  font-size: 22px;
  font-weight: 600;
}
.regular-font-color {
  align-self: flex-end;
  text-align: right;
}
</style>
