<template>
  <section class="recharge">
    <div class="dm-form__wrap" v-loading="loading">
      <div class="pb22" style="overflow:hidden;line-height:40px;" v-if="$route.params.type === 'video'">
        <!-- 视频资费 -->
        <el-date-picker :clearable="false" v-model="dateTimeVideo" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" @change="changeVideoTime"></el-date-picker>
        <span class="fz12 gray">* 此处时间跨度不超过7天</span>
        <el-button type="primary" class="fr" icon="iconfont icon-icon_yunxiazai fz14 mr5" @click="downloadTrafficCostListExcel">导出记录</el-button>
      </div>
      <div v-else class="pb20" style="overflow:hidden;line-height:40px;">
        <div class="flex_between">
          <div>
            <el-date-picker :disabled="loading" :clearable="false" :pickerOptions="pickerOptions" v-model="dateTime" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" @change="onSearch"></el-date-picker>
            <el-input v-model="listParams.searchParam" :style="setInputWidth()" :placeholder="placeholder" clearable @change="onSearch"><i slot="prefix" class="el-input__icon el-icon-search"></i></el-input>
            <el-select v-if="$route.params.type === 'sms'" class="dm-select" v-model="listParams.channelType" clearable placeholder="选择类型" @change="onSearch">
              <el-option label="会员验证码" value="1"></el-option>
              <el-option label="导购验证码" value="2"></el-option>
            </el-select>
            <select-depart v-if="isMoreAccount && config.showAllDepartment" :data="deparment" @load="load" @getDepartId="getDepartId" @remote-search="remoteSearch" :loading="deparment.loading" />
            <span class="fz12 gray">* 此处仅支持筛选近半年的统计数据</span>
          </div>
          <el-button v-if="getCodeAuth" :limit-code="getCode($route.params.type)" type="primary" class="btn h32" @click="exportDialog.dialogVisible = true"><i class="iconfont icon-xiazai" style="marginRight:6px;fontSize:14px" />导出</el-button>
        </div>
        <p class="tips" v-if="$route.params.type === 'video'">共消耗流量{{ sumCount }}MB 累计支出{{ sumFee }}元</p>
        <p class="tips" v-if="['record', 'call'].includes($route.params.type)">
          通话时长：{{ sumCount || 0 }} 秒
          <span class="ml10 blod">总计消费：{{ (sumFee / 100).toFixed(2) }} 元</span>
        </p>
        <p class="tips" v-else>
          成功发送：国内短信{{ localCount || 0 }}条，国外短信{{ sumInternational || 0 }}条
          <span class="ml10 blod">总计消费：{{ (sumFee / 1000).toFixed(2) }} 元</span>
        </p>
      </div>
      <!-- 短信营销 -->
      <el-table tooltipEffect="light" :data="tableList" style="width:100%" v-if="$route.params.type === 'marketing'">
        <el-table-column align="left" width="170" prop="sendTime" label="发送时间">
          <template slot-scope="scope">
            <p class="cell-time">
              {{ formatDateTimeByType(scope.row.sendTime, 'yyyy-MM-dd-HH-mm-ss', true).y }}<br />
              <span>{{ formatDateTimeByType(scope.row.sendTime, 'yyyy-MM-dd-HH-mm-ss', true).h }}</span>
            </p>
          </template>
        </el-table-column>
        <el-table-column align="left" min-width="120" prop="telephone" label="接收号码"></el-table-column>
        <el-table-column align="left" min-width="100" prop="countNum" label="计费条数">
          <template slot-scope="scope">{{ scope.row.countNum }}条 </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" align="left" min-width="150" prop="storeName" label="门店">
          <template slot-scope="scope">
            <p>{{ scope.row.storeName }}</p>
            <p class="gray">{{ scope.row.storeGroupName }}</p>
          </template>
        </el-table-column>
        <el-table-column label="触发计划名称" :show-overflow-tooltip="true" align="left" min-width="110" prop="sourceName"></el-table-column>
        <el-table-column label="活动创建人" align="left" min-width="100" prop="sourceCreatorName"></el-table-column>
        <el-table-column v-if="isMoreAccount" label="扣费规则" align="left" min-width="100" prop="accountRule">
          <template slot-scope="{ row }">{{ accountRule(row.accountRule) }}</template>
        </el-table-column>
        <el-table-column v-if="isMoreAccount" label="费用归属部门" align="left" min-width="120" prop="accountDepartName">
          <template slot-scope="{ row }">{{ row.accountDepartName || '总部' }}</template>
        </el-table-column>
        <!-- <el-table-column label="模板ID" align="left" width="100" prop="chartsDate"></el-table-column> -->
        <el-table-column label="短信内容" align="left" min-width="200" prop="remark">
          <template slot-scope="scope">
            <el-popover class="item" trigger="hover" width="200" v-if="scope.row.remark && scope.row.remark.length > 10" :content="scope.row.remark" placement="top-start">
              <span class="ellipsis" slot="reference">{{ scope.row.remark }}</span>
            </el-popover>
            <span v-else>{{ scope.row.remark }}</span>
          </template>
        </el-table-column>
      </el-table>
      <!-- 短信验证码 -->
      <el-table tooltipEffect="light" :data="tableList" style="width:100%" v-if="$route.params.type === 'sms'">
        <el-table-column align="left" width="170" prop="createTime" label="发送时间">
          <template slot-scope="scope">
            <p class="cell-time">
              {{ formatDateTimeByType(scope.row.createTime, 'yyyy-MM-dd-HH-mm-ss', true).y }}<br />
              <span>{{ formatDateTimeByType(scope.row.createTime, 'yyyy-MM-dd-HH-mm-ss', true).h }}</span>
            </p>
          </template>
        </el-table-column>
        <el-table-column align="left" width="150" prop="receivePhone" label="接收号码"></el-table-column>
        <el-table-column :show-overflow-tooltip="true" align="left" width="320" prop="storeName" label="门店">
          <template slot-scope="scope">
            <p>{{ scope.row.storeName }}</p>
            <p class="fz13 gray">{{ scope.row.storeGroupName }}</p>
            <p v-if="!scope.row.storeName && !scope.row.storeGroupName">--</p>
          </template>
        </el-table-column>
        <el-table-column v-if="isMoreAccount" label="扣费规则" align="left" min-width="100" prop="accountRule">
          <template slot-scope="{ row }">{{ accountRule(row.accountRule) }}</template>
        </el-table-column>
        <el-table-column v-if="isMoreAccount" label="费用归属部门" align="left" min-width="120" prop="accountDepartName">
          <template slot-scope="{ row }">{{ row.accountDepartName || '总部' }}</template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" label="短信内容" align="left" min-width="200" prop="paramInfo">
          <template slot-scope="scope">您的验证码是：{{ scope.row.paramInfo }} </template>
        </el-table-column>
        <el-table-column label="类型" align="left" min-width="100" prop="status">
          <template slot-scope="scope">
            {{ scope.row.channelType ? (scope.row.channelType == 2100 ? '导购验证码' : '会员验证码') : '' }}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="left" width="100" prop="status">
          <template slot-scope="scope">
            {{ scope.row.status === 1 ? '成功' : '失败' }}
          </template>
        </el-table-column>
      </el-table>
      <!-- 语音验证码 -->
      <!-- <el-table tooltipEffect="light" :data="tableList" style="width:100%" v-if="$route.params.type === 'voice'">
        <el-table-column align="left" prop="createTime" label="发送时间" width="170px">
          <template slot-scope="scope">
            <p class="cell-time">
              {{ formatDateTimeByType(scope.row.createTime, 'yyyy-MM-dd-HH-mm-ss', true).y }}<br />
              <span>{{ formatDateTimeByType(scope.row.createTime, 'yyyy-MM-dd-HH-mm-ss', true).h }}</span>
            </p>
          </template>
        </el-table-column>
        <el-table-column align="left" prop="receivePhone" label="接收号码"></el-table-column>
        <el-table-column :show-overflow-tooltip="true" align="left" width="320" prop="storeName" label="门店">
          <template slot-scope="scope">
            <p>{{ scope.row.storeName }}</p>
            <p class="fz13 gray">{{ scope.row.storeGroupName }}</p>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="left" prop="status">
          <template slot-scope="scope">
            {{ scope.row.status === 1 ? '成功' : '失败' }}
          </template>
        </el-table-column>
      </el-table> -->
      <!-- 双向呼叫 -->
      <el-table tooltipEffect="light" :data="tableList" style="width:100%" v-if="$route.params.type === 'call'">
        <el-table-column align="left" width="200" prop="createTime" label="呼叫时间">
          <template slot-scope="scope">
            <p class="cell-time">
              {{ formatDateTimeByType(scope.row.createTime, 'yyyy-MM-dd-HH-mm-ss', true).y }}<br />
              <span>{{ formatDateTimeByType(scope.row.createTime, 'yyyy-MM-dd-HH-mm-ss', true).h }}</span>
            </p>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" align="left" min-width="320" prop="storeName" label="门店">
          <template slot-scope="scope">
            <p>{{ scope.row.storeName }}</p>
            <p class="fz13 gray">{{ scope.row.storeGroupName }}</p>
          </template>
        </el-table-column>
        <el-table-column label="触发计划名称" align="left" :show-overflow-tooltip="true" min-width="320" prop="sourceName"></el-table-column>
        <el-table-column label="活动创建人" align="left" width="150" prop="sourceCreatorName"></el-table-column>
        <el-table-column v-if="isMoreAccount" label="扣费规则" align="left" min-width="100" prop="accountRule">
          <template slot-scope="{ row }">{{ accountRule(row.accountRule) }}</template>
        </el-table-column>
        <el-table-column v-if="isMoreAccount" label="费用归属部门" align="left" min-width="120" prop="accountDepartName">
          <template slot-scope="{ row }">{{ row.accountDepartName || '总部' }}</template>
        </el-table-column>
        <el-table-column align="left" width="150" prop="clerkName" label="主叫">
          <template slot-scope="scope">
            <p>{{ scope.row.clerkName || '--' }}</p>
            <p class="gray">{{ scope.row.sendPhone }}</p>
          </template>
        </el-table-column>
        <el-table-column align="left" width="160" prop="memberId" label="被叫(会员)">
          <template slot-scope="scope">
            <img :src="scope.row.memberPic || defaultAvatar" width="32" height="32" alt="" />
            <div class="inline-block">
              <p>{{ scope.row.memberName || '--' }}</p>
              <p class="fz13 gray">{{ scope.row.receivePhone || '--' }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="left" width="150" prop="status" label="通话状态">
          <template slot-scope="scope">
            {{ scope.row.callStatus === 1 ? '未接通' : scope.row.callStatus === 2 ? '接通' : '成功' }}
          </template>
        </el-table-column>
        <el-table-column align="left" width="150" prop="callTime" label="时间（秒）">
          <template slot-scope="scope">{{ scope.row.callTime }}秒</template>
        </el-table-column>
        <el-table-column align="left" width="150" prop="callFee" label="消费金额（元）">
          <template slot-scope="scope">{{ Number(scope.row.callFee / 1000).toFixed(2) }}元</template>
        </el-table-column>
      </el-table>
      <!--通话记录-->
      <el-table tooltipEffect="light" :data="tableList" style="width:100%" v-if="$route.params.type === 'record'">
        <el-table-column align="left" width="160" prop="createTime" label="呼叫时间">
          <template slot-scope="scope">
            <p class="cell-time">
              {{ formatDateTimeByType(scope.row.callBeginTime, 'yyyy-MM-dd-HH-mm-ss', true).y }}<br />
              <span>{{ formatDateTimeByType(scope.row.callBeginTime, 'yyyy-MM-dd-HH-mm-ss', true).h }}</span>
            </p>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" align="left" prop="storeName" width="350" label="门店">
          <template slot-scope="scope">
            <p>{{ scope.row.storeName }}</p>
            <p class="fz13 gray">{{ scope.row.storeGroupName }}</p>
          </template>
        </el-table-column>
        <el-table-column label="触发计划名称" align="left" width="350" prop="sourceName" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="活动创建人" align="left" width="100" prop="sourceCreatorName"></el-table-column>
        <el-table-column v-if="isMoreAccount" label="扣费规则" align="left" min-width="100" prop="accountRule">
          <template slot-scope="{ row }">{{ accountRule(row.accountRule) }}</template>
        </el-table-column>
        <el-table-column v-if="isMoreAccount" label="费用归属部门" align="left" min-width="120" prop="accountDepartName">
          <template slot-scope="{ row }">{{ row.accountDepartName || '总部' }}</template>
        </el-table-column>
        <el-table-column align="left" width="150" prop="clerkName" label="主叫">
          <template slot-scope="scope">
            <p>{{ scope.row.clerkName || '--' }}</p>
            <p class="gray">{{ scope.row.clerkPhoneNumber }}</p>
          </template>
        </el-table-column>
        <el-table-column align="left" width="150" prop="memberId" label="被叫(会员)">
          <template slot-scope="scope">
            <img :src="scope.row.memberImgUrl || defaultAvatar" width="32" height="32" alt="" />
            <div class="inline-block">
              <p>{{ scope.row.memberName || '--' }}</p>
              <p class="fz13 gray">{{ scope.row.memberPhoneNumber || '--' }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="left" width="150" prop="status" label="类型">
          <template slot-scope="scope">
            {{ scope.row.telTaskTitle }}
          </template>
        </el-table-column>
        <el-table-column align="left" width="150" prop="status" label="录音保存时长">
          <template slot-scope="scope">
            {{ scope.row.storageTypeRemark }}
          </template>
        </el-table-column>
        <el-table-column align="left" width="150" prop="callTime" label="时间（分钟）">
          <template slot-scope="scope"> {{ scope.row.callTime }}分钟 </template>
        </el-table-column>
        <el-table-column align="left" width="150" prop="callFee" label="消费金额（元）">
          <template slot-scope="scope"> {{ Number(scope.row.storageFee / 100).toFixed(2) }}元 </template>
        </el-table-column>
      </el-table>
      <!-- 视频资费 -->
      <!-- <el-table tooltipEffect="light" :data="tableList" style="width:100%" v-if="$route.params.type === 'video'">
        <el-table-column align="left" prop="createTime" label="时间">
          <template slot-scope="scope">
            <p class="cell-time">
              {{ formatDateTimeByType(scope.row.time, 'yyyy-MM-dd-HH-mm-ss') }}
            </p>
          </template>
        </el-table-column>
        <el-table-column align="left" prop="traffic" label="流量消耗统计">
          <template slot-scope="scope"> {{ scope.row.traffic }}GB </template>
        </el-table-column>
        <el-table-column align="left" prop="trafficCost" label="流量费用支出">
          <template slot-scope="scope"> ¥ {{ scope.row.trafficCost }} </template>
        </el-table-column>
      </el-table> -->
      <dm-pagination v-show="tableList.length" background class="dm-pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listParams.currentPage" :page-sizes="[20, 40, 60, 80]" :page-size="listParams.pageSize" layout="total, sizes, prev, pager, next" :total="total" hide-on-single-page></dm-pagination>
    </div>
    <!--导出数据-->
    <el-dialog title="导出数据" :visible.sync="exportDialog.dialogVisible" width="500">
      <div class="export-time text-center">
        <h2>选择导出日期范围</h2>
        <p class="tip mb10">日期最大可选择范围为3个月，不支持导出当天的数据</p>
        <el-date-picker :clearable="false" :pickerOptions="exportDialog.pickerOptions" v-model="exportDialog.time" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
        <div class="mt40 mb40">
          <el-button type="primary" @click="createRepoert">去生成报告</el-button>
        </div>
      </div>
    </el-dialog>
    <vue-gic-export-excel :dialogVisible.sync="exportData.dialogVisible" :dataArr="tableList" :type="2" :excelUrl="exportData.excelUrl" :params="exportData.params" :projectName="projectName"></vue-gic-export-excel>
  </section>
</template>
<script>
import { messageMarketingChart, messageMarketingPage, smsData, voiceData, callData, recordData, videoPage, videoChartData, downloadTrafficCostListExcel, getDepartList } from '@/service/api/rechargeApi.js';
import { formatDateTimeByType } from '@/utils/index.js';
import SelectDepart from './components/select-depart.vue';
import intel from './recharge_mixin';

export default {
  name: 'recharge-consume',
  components: { SelectDepart },
  mixins: [intel],
  data() {
    return {
      // eslint-disable-next-line
      defaultAvatar: require('../../assets/img/head_default.png'),
      formatDateTimeByType,
      dateTime: [Date.now() - 30 * 24 * 60 * 60 * 1000, Date.now()],
      dateTimeVideo: [Date.now() - 7 * 24 * 60 * 60 * 1000, Date.now()],
      dateTimeVideoCopy: [Date.now() - 7 * 24 * 60 * 60 * 1000, Date.now()],
      loading: false,
      tableList: [],
      listParams: {
        currentPage: 1,
        pageSize: 20,
        beginTime: '',
        endTime: '',
        searchParam: '',
        channelType: ''
      },
      total: 0,
      taskType: '',
      taskTypeOptions: [],
      sumFee: 0,
      sumCount: 0,
      sumInternational: 0,
      localCount: 0,
      placeholder: '',
      pickerOptions: {
        disabledDate: val => {
          // 只能筛选半年之内得数据,并且最大跨度为一个月
          const halfYearBefore = Date.now() - 6 * 30 * 24 * 60 * 60 * 1000;
          const oneMothods = 30 * 24 * 60 * 60 * 1000;
          const curTime = this.minDate.getTime();
          const min = curTime - oneMothods > halfYearBefore ? curTime - oneMothods : halfYearBefore;
          return val.getTime() > curTime + oneMothods || val.getTime() < min;
        },
        onPick: ({ maxDate, minDate }) => {
          this.minDate = minDate;
        }
      },
      minDate: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
      videoListParams: {
        currentPage: 1,
        pageSize: 20,
        requestProject: 'marketing',
        startTime: '',
        endTime: ''
      },
      projectName: 'marketing', // 当前项目名
      dialogVisible: false,
      excelUrl: '', // 下载数据的地址
      params: {}, // 传递的参数
      deparment: {
        list: [],
        searchParams: '',
        status: -1,
        pageSize: 20,
        currentPage: 1,
        loading: false,
        isLimit: false, // 是否最后一页
        departId: '', // 选中时得id
        zbFlag: 1
      },
      exportDialog: {
        dialogVisible: false,
        pickerOptions: {
          disabledDate: val => {
            const isSms = this.$route.params.type == 'marketing'; // 是否为营销类型
            const beforeDay = Date.now() - 24 * 60 * 60 * 1000; // 营销类型最大选择时间为当天的前一天
            // 只能筛选一年之内得数据,并且最大跨度为三个月
            const oneYearBefore = Date.now() - 12 * 30 * 24 * 60 * 60 * 1000;
            const threeMothods = 3 * 30 * 24 * 60 * 60 * 1000;
            const curTime = this.exportDialog.minDate.getTime();
            const min = curTime - threeMothods > oneYearBefore ? curTime - threeMothods : oneYearBefore;
            const max = isSms ? beforeDay : curTime + threeMothods;
            return val.getTime() > max || val.getTime() < min;
          },
          onPick: ({ maxDate, minDate }) => {
            this.exportDialog.minDate = minDate;
          }
        },
        time: [],
        minDate: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)
      },
      exportData: {
        dialogVisible: false,
        execUrl: '',
        params: {}
      }
    };
  },
  async created() {
    this.getDepartmentList();
    const config = await this.getAuth(); // rechartge_mixin
    this.deparment.departId = config.accountDepartId;
    await this.getRule(); // 该接口调取完后select-depart组件挂载所以在之前一步初始化departId
    this.loadAll();
    this.$store.commit('mutations_breadcrumb', [{ name: '企业管理', path: '' }, { name: '计费中心', path: '/recharge' }, { name: '消费详情', path: '' }]); // eslint-disable-line
  },
  methods: {
    setInputWidth() {
      let width = 250;
      switch (this.$route.params.type) {
        case 'marketing':
          width = 400;
          break;
        case 'call':
        case 'record':
          width = 320;
          break;
        default:
          width = 250;
      }
      return { width: `${width}px` };
    },
    handleSizeChange(val) {
      this.listParams.currentPage = 1;
      this.listParams.pageSize = val;
      this.loadAll();
    },
    handleCurrentChange(val) {
      this.listParams.currentPage = val;
      this.loadAll();
    },
    loadAll(onlyList = false) {
      if (this.dateTime) {
        this.listParams.beginTime = formatDateTimeByType(this.dateTime[0], 'yyyy-MM-dd');
        this.listParams.endTime = formatDateTimeByType(this.dateTime[1], 'yyyy-MM-dd');
      } else {
        this.listParams.beginTime = '';
        this.listParams.endTime = '';
      }
      const id = this.setAccountDepartId(this.deparment.departId, this.config);
      if (id) this.$set(this.listParams, 'accountDepartId', id);
      else {
        delete this.listParams.accountDepartId;
      }
      if (this.$route.params.type === 'marketing') {
        this.placeholder = '输入手机号/模板ID/内容/触发计划名称/活动创建人';
        if (!onlyList) {
          this.marketingCharts();
        }
        this.marketingList();
      }
      if (this.$route.params.type === 'sms') {
        this.placeholder = '输入手机号';
        if (!onlyList) {
          this.smsData('charts');
        }
        this.smsData('list');
      }
      if (this.$route.params.type === 'voice') {
        this.placeholder = '输入手机号';
        if (!onlyList) {
          this.voiceData('charts');
        }
        this.voiceData('list');
      }
      if (this.$route.params.type === 'call') {
        this.placeholder = '输入手机号/触发计划名称/活动创建人';
        if (!onlyList) {
          this.callData('charts');
        }
        this.callData('list');
      }
      if (this.$route.params.type === 'record') {
        this.placeholder = '输入手机号/触发计划名称/活动创建人';
        if (!onlyList) {
          this.recordData('charts');
        }
        this.recordData('list');
      }
      if (this.$route.params.type === 'video') {
        if (!onlyList) {
          this.videoPage('charts');
        }
        this.videoPage('list');
      }
    },
    onSearch() {
      this.listParams.currentPage = 1;
      this.loadAll();
    },
    async marketingList() {
      this.loading = true;
      try {
        let resList = await messageMarketingPage(this.listParams);
        if (resList.errorCode === 0 && resList.result.result) {
          this.tableList = resList.result.result || [];
          this.total = resList.result.totalCount;
        } else {
          this.tableList = [];
        }
      } catch (err) {}
      this.loading = false;
    },
    async marketingCharts() {
      try {
        let res = await messageMarketingChart(this.listParams);
        this.sumCount = res.result.sumCount;
        this.sumFee = res.result.sumFee;
        this.sumInternational = res.result.sumInternational;
        this.localCount = this.sumCount - this.sumInternational;
      } catch (err) {}
    },
    async smsData(type = 'list') {
      this.loading = true;
      try {
        let res = await smsData(Object.assign({ ajaxType: type }, this.listParams));
        if (type === 'list') {
          if (res.errorCode === 0 && res.result.page.result) {
            this.tableList = res.result.page.result || [];
            this.total = res.result.page.totalCount;
          } else {
            this.tableList = [];
          }
        } else if (type === 'charts') {
          this.sumCount = res.result.sumCount;
          this.sumFee = res.result.sumFee;
          this.sumInternational = res.result.sumInternational;
          this.localCount = this.sumCount - this.sumInternational;
        }
      } catch (err) {}
      this.loading = false;
    },
    async voiceData(type = 'list') {
      this.loading = true;
      try {
        let res = await voiceData(Object.assign({ ajaxType: type }, this.listParams));
        if (type === 'list') {
          if (res.errorCode === 0 && res.result.page.result) {
            this.tableList = res.result.page.result || [];
            this.total = res.result.page.totalCount;
          } else {
            this.tableList = [];
          }
        } else if (type === 'charts') {
          this.sumCount = res.result.sumCount;
          this.sumFee = res.result.sumFee;
        }
      } catch (err) {}
      this.loading = false;
    },
    async callData(type = 'list') {
      this.loading = true;
      try {
        let res = await callData(Object.assign({ ajaxType: type, taskType: type === 'list' ? this.taskType : '' }, this.listParams));
        if (type === 'list') {
          if (res.errorCode === 0 && res.result.page.result) {
            this.tableList = res.result.page.result || [];
            this.total = res.result.page.totalCount;
            this.taskTypeOptions = [{ taskType: '', ecmName: '全部' }, { taskType: 1, ecmName: '不良评价回访' }]; // eslint-disable-line
          } else {
            this.tableList = [];
          }
        } else if (type === 'charts') {
          this.sumCount = res.result.times || 0;
          this.sumFee = res.result.sumFee;
        }
      } catch (err) {}
      this.loading = false;
    },
    // 视频资费相关接口
    async videoPage(type = 'list') {
      this.loading = true;
      try {
        this.videoListParams.startTime = formatDateTimeByType(this.dateTimeVideo[0], 'yyyy-MM-dd');
        this.videoListParams.endTime = formatDateTimeByType(this.dateTimeVideo[1], 'yyyy-MM-dd');
        if (type === 'list') {
          let res = await videoPage(this.videoListParams);
          if (res.errorCode === 0 && res.result.result) {
            this.tableList = res.result.result || [];
            this.total = res.result.totalCount;
          } else {
            this.tableList = [];
          }
        } else if (type === 'charts') {
          const params = { ...this.listParams, startTime: this.listParams.beginTime };
          let res = await videoChartData(params);
          this.sumCount = res.result.sumCount;
          this.sumFee = res.result.sumFee;
        }
      } catch (err) {}
      this.loading = false;
    },
    // 修改视频时间 范围不能超过7天
    changeVideoTime(date) {
      // 单张卡券可以设置领取n久
      if (new Date(this.dateTimeVideo[1]).getTime() - new Date(this.dateTimeVideo[0]).getTime() > 7 * 24 * 60 * 60 * 1000) {
        this.$tips({ message: '领取时间段范围不能超过7天', type: 'warning' });
        this.dateTimeVideo = [...this.dateTimeVideoCopy];
        return;
      }
      this.dateTimeVideoCopy = [...this.dateTimeVideo];
      this.videoPage('list');
    },
    // 导出
    downloadTrafficCostListExcel() {
      this.dialogVisible = true;
      this.excelUrl = downloadTrafficCostListExcel;
      this.params = {
        startTime: formatDateTimeByType(this.dateTimeVideo[0], 'yyyy-MM-dd'),
        endTime: formatDateTimeByType(this.dateTimeVideo[1], 'yyyy-MM-dd'),
        requestProject: 'marketing'
      };
    },
    async recordData(type = 'list') {
      this.loading = true;
      try {
        let res = await recordData(Object.assign({ ajaxType: type, taskType: type === 'list' ? this.taskType : '' }, this.listParams));
        if (type === 'list') {
          if (res.errorCode === 0 && res.result.page.result) {
            this.tableList = res.result.page.result || [];
            this.total = res.result.page.totalCount;
            this.taskTypeOptions = [{ taskType: '', ecmName: '全部' }, { taskType: 1, ecmName: '不良评价回访' }]; // eslint-disable-line
          } else {
            this.tableList = [];
          }
        } else if (type === 'charts') {
          this.sumCount = res.result.sumCallTime * 60 || 0;
          this.sumFee = res.result.sumFee;
        }
      } catch (err) {}
      this.loading = false;
    },
    // 获取计费部门
    async getDepartmentList() {
      const depart = this.deparment;
      depart['loading'] = true;
      const para = Object.assign({}, depart);
      const typeArr = ['list', 'loading', 'isLimit', 'departId'];
      this.deleteAttribute(para, typeArr);
      let { result } = await getDepartList(para);
      this.setDepartData(depart, 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() {
      const depart = this.deparment;
      if (depart['isLimit'] || depart['loading']) return;
      depart['currentPage']++;
      this.getDepartmentList();
    },
    getDepartId(id) {
      // 选中不同下拉得id时，调用对应得表格方法
      const depart = this.deparment;
      depart['departId'] = id;
      this.listParams['currentPage'] = 1;
      this.loadAll();
    },
    // 下拉远程搜索
    remoteSearch(val) {
      const depart = this.deparment;
      depart['searchParams'] = val.trim();
      depart['currentPage'] = 1;
      depart['isLimit'] = false;
      depart['list'] = [];
      this.getDepartmentList();
    },
    // 导出表格数据
    cdkeyExport() {
      const exportData = this.exportData;
      exportData.dialogVisible = true;
      const type = this.$route.params.type;
      let meth;
      switch (type) {
        case 'sms':
          meth = '/api-marketing/excel/recharge-sms-valid-excel';
      }
      const params = {
        requestProject: 'marketing',
        beginTime: formatDateTimeByType(this.exportDialog.time[0], 'yyyy-MM-dd'),
        endTime: formatDateTimeByType(this.exportDialog.time[1], 'yyyy-MM-dd'),
        dataType: 2,
        searchParam: this.listParams.searchParam,
        accountDepartId: this.deparment.departId
      };
      if (type == 'sms') params.channelType = this.listParams.channelType;
      exportData.excelUrl = meth;
      exportData.params = params;
    },
    // 生成报告
    createRepoert() {
      this.exportDialog.dialogVisible = false;
      this.exportData.dialogVisible = true;
      this.cdkeyExport();
    }
  },
  computed: {
    accountRule() {
      const map = {
        1: '总部',
        2: '会员所属服务门店 ',
        3: '活动创建人',
        4: '导购所属服务门店'
      };
      return id => map[id] || '--';
    },
    accountDepartName() {
      return row => (row.accountDepartName ? row.accountDepartName : row.accountDepartId == 1 ? '总部' : '--');
    },
    getCodeAuth() {
      return this.$getButtonLimit(this.getCode(this.$route.params.type));
    },
    getCode() {
      return type => {
        let code;
        switch (type) {
          case 'marketing':
            code = 'marketingExportMarketing';
            break;
          case 'sms':
            code = 'marketingExportSms';
            break;
          case 'call':
            code = 'marketingExportCall';
            break;
          case 'record':
            code = 'marketingExportRecord';
            break;
        }
        return this.$buttonCode[code];
      };
    }
  },
  watch: {
    'exportDialog.dialogVisible': {
      handler: function(newVal) {
        if (newVal) {
          const isSms = this.$route.params.type == 'marketing'; // 是否为短信营销
          const beforeDay = Date.now() - 24 * 60 * 60 * 1000;
          const begenTime = isSms && this.dateTime[0] > beforeDay ? beforeDay : this.dateTime[0];
          const endTime = isSms && this.dateTime[1] > beforeDay ? beforeDay : this.dateTime[1];
          this.exportDialog.time = [begenTime, endTime];
          this.exportDialog.minDate = new Date(begenTime);
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.recharge-today {
  &-item {
    padding: 20px;
    margin: 10px 20px;
    .fl {
      line-height: 24px;
    }
    .fr {
      line-height: 34px;
    }
  }
}
.tips {
  height: 22px;
  font-size: 14px;
  font-weight: 400;
  color: #303133;
  line-height: 22px;
  margin-top: 16px;
}
.blod {
  font-weight: bold;
}
.flex_between {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.export-time {
  box-sizing: border-box;
  h2 {
    padding: 25px 0;
    font-weight: 600;
    line-height: 22px;
    font-size: 16px;
    color: #303133;
  }
  .tip {
    font-size: 12px;
    font-weight: 400;
    color: #909399;
  }
}
</style>
