<template>
  <div class="aiCall">
    <div class="radioButton">
      <el-radio-group class="customize" v-model="dimension" @change="radioChange">
        <el-radio-button label="门店维度"></el-radio-button>
        <el-radio-button label="分组维度"></el-radio-button>
      </el-radio-group>
      <div class="tips ml10">
        数据每天更新一次，按营销触发时客户所在服务门店进行统计
      </div>
    </div>
    <div class="searchWarp">
      <div class="pb20 clearfix" v-show="dimension == '门店维度'">
        <el-input placeholder="请输入门店名称/code" class="w260" v-model="form.search" @change="handleSearch" clearable> </el-input>
        <vue-gic-select-tree class="inline" :options="options" v-if="dimension == '门店维度'" @change="onChange" ref="selectTree"></vue-gic-select-tree>
        <el-button icon="iconfont fz14 icon-cp-xiazai" v-if="$getButtonLimit($buttonCode.marketingAiExport)" :limit-code="$buttonCode.marketingAiExport" class="fr" type="primary" @click="handleExport" :disabled="!total"> 查询结果导出</el-button>
      </div>
      <el-form inline="true" class="table-page-search-wrapper" size="small" v-show="dimension == '分组维度'">
        <el-form-item>
          <el-select v-model="selectVal" class="w100" @change="groupSelectChange">
            <el-option label="分组层级" :value="1"></el-option>
            <el-option label="分组名称" :value="2"></el-option>
          </el-select>
          <el-select v-model="form.storeGroupLevel" @change="handleSearch" v-if="selectVal == 1" class="w260">
            <el-option v-for="item in selectOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
          <vue-gic-select-tree :options="options" v-if="selectVal == 2" ref="selectTree" @change="onChange"></vue-gic-select-tree>
        </el-form-item>
        <el-button icon="iconfont icon-cp-xiazai" class="fr" type="primary" @click="handleExport" :disabled="!total"> 查询结果导出</el-button>
      </el-form>
    </div>
    <div class="cardContent">
      <el-row :gutter="20" v-loading="cardLoading">
        <el-col :span="6" v-for="(el, index) in targetList" :key="index">
          <target-group :data-list="el"></target-group>
        </el-col>
      </el-row>
    </div>
    <el-table :data="tableData" style="width:100%" v-loading="loading" @sort-change="handleSortChange" :key="dimension">
      <el-table-column align="center" prop="date" label="排名" width="80px" fixed="left">
        <template slot-scope="scope">
          <div style="line-height:1">
            <!-- 排名变化 上升 +  下降 - 不变0 -->
            <div class="rank-icon" v-show="scope.row.numSort">
              <span :class="`${scope.row.numSort < 4 ? 'rank1' : 'rank2'}`">{{ scope.row.numSort || '-' }}</span>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column v-for="v in tableHeader" :show-overflow-tooltip="v.tooltip" :width="v.width" :min-width="v.minWidth" :align="v.align" :key="v.prop" :prop="v.prop" :label="v.label" :formatter="v.formatter" :sortable="v.sortable" :fixed="v.fixed">
        <template slot-scope="scope">
          <span v-if="v.formatter" v-html="v.formatter(scope.row)"></span>
          <span v-else>{{ scope.row[v.prop] }}</span>
        </template>
      </el-table-column>
    </el-table>
    <dm-pagination v-show="tableData.length" background class="dm-pagination" @size-change="handleSizeChange" @current-change="getListData" :current-page.sync="form.pageNum" :page-sizes="[20, 40, 60, 80]" :page-size.sync="form.pageSize" layout="total, sizes, prev, pager, next" :total="total"></dm-pagination>
    <vue-gic-export-excel :dialogVisible.sync="dialogVisible" :dataArr="tableData" :type="2" :excelUrl="excelUrl" :params="exportParams" projectName="marketing"></vue-gic-export-excel>
  </div>
</template>

<script>
import { aiTransformStoreGroupSplit, getActivityDetail, aiStoreTransfer, aiStoreTransferNoBelong, aiStoreTransferStatistics, exportAiStoreTransfer, aiStoreGroupTransfer, aiStoreGroupTransferStatistics, exportAiStoreGroupTransfer } from '@/service/api/aiApi.js';
import TargetGroup from '@/views/ai/ai-data-report/target-group.vue';
import { numFormat } from '@/utils/index.js';

const tableHead = [
  {
    label: '上级分组',
    minWidth: '150',
    prop: 'storeGroupName',
    formatter: function(row) {
      return `<span class="ellipsis-l2">${row.storeGroupName ? row.storeGroupName : '- -'}</span>`;
    }
  },
  {
    label: '营销人数',
    prop: 'marketingNumber',
    width: '100',
    sortable: 'custom',
    formatter: function(row) {
      return `<span>${!isNaN(row.marketingNumber) ? row.marketingNumber.toLocaleString() : '- -'}</span>`;
    }
  },
  {
    label: '触达人数',
    prop: 'reachNumber',
    width: '120',
    sortable: 'custom',
    formatter: function(row) {
      return `<span>${!isNaN(row.reachNumber) ? row.reachNumber.toLocaleString() : '- -'}</span>`;
    }
  },
  {
    label: '触达率',
    prop: 'reachRate',
    width: '120',
    sortable: 'custom',
    formatter: function(row) {
      return `<span>${!isNaN(row.reachRate) ? row.reachRate + '%' : '- -'}</span>`;
    }
  },
  {
    label: '转化人数',
    prop: 'conversionNumber',
    width: '120',
    sortable: 'custom',
    formatter: function(row) {
      return `<span>${!isNaN(row.conversionNumber) ? row.conversionNumber.toLocaleString() : '- -'}</span>`;
    }
  },
  {
    label: '转化率',
    prop: 'conversionRate',
    width: '120',
    sortable: 'custom',
    formatter: function(row) {
      return `<span>${!isNaN(row.conversionRate) ? row.conversionRate + '%' : '- -'}</span>`;
    }
  },
  {
    label: '活动转化金额(实付)',
    prop: 'actualSale',
    width: '180',
    sortable: 'custom',
    formatter: function(row) {
      return `<span>${!isNaN(row.actualSale) ? row.actualSale.toLocaleString() : '- -'}</span>`;
    }
  },
  {
    label: '客单价(元)',
    prop: 'perCustomerTransaction',
    width: '160',
    sortable: 'custom',
    formatter: function(row) {
      return `<span>${!isNaN(row.perCustomerTransaction) ? row.perCustomerTransaction.toLocaleString() : '- -'}</span>`;
    }
  },
  {
    label: '连带率',
    prop: 'associatedPurchaseRate',
    width: '120',
    sortable: 'custom',
    fixed: 'right'
  }
];
export default {
  data() {
    return {
      numFormat,
      form: {
        search: '',
        storeGroupId: '',
        storeGroupLevel: '',
        orderBy: '',
        activityId: this.$route.params.id,
        pageNum: 1,
        pageSize: 20
      },
      dimension: '门店维度',
      selectVal: 1,
      tableData: [],
      selectOptions: [
        {
          label: '第一层级',
          value: 1
        },
        {
          label: '第二层级',
          value: 2
        },
        {
          label: '第三层级',
          value: 3
        },
        {
          label: '第四层级',
          value: 4
        },
        {
          label: '第五层级',
          value: 5
        }
      ],
      options: {
        selectOptions: {
          allCheckText: '全部选中111',
          width: 260,
          placeholder: '请选择',
          clearable: true,
          data: []
        },
        treeOptions: {
          data: [],
          isDefalutExpandAll: true,
          nodeClickRule: {
            leafOnly: true,
            includeHalfChecked: false
          },
          props: {
            label: 'storeGroupName',
            value: 'storeGroupId',
            children: 'children'
          },
          filter(value, data, node) {
            return node.label.indexOf(value) > -1;
          }
        },
        searchAble: true
      },
      fixedTableData: [],
      total: 0,
      cardLoading: false,
      loading: false,
      dialogVisible: false,
      excelUrl: '',
      originTargetList: [
        [
          {
            label: '营销人数',
            tips: '根据每天外呼人数累加',
            value: '',
            key: 'marketingNumber',
            type: 'number'
          },
          {
            label: '触达人数',
            value: '',
            key: 'reachNumber',
            type: 'number'
          },
          {
            label: '触达率',
            value: '',
            key: 'reachRate',
            type: 'rate'
          }
        ],
        [
          {
            label: '转化人数',
            value: '',
            key: 'conversionNumber',
            type: 'number'
          },
          {
            label: '转化率',
            tips: '',
            value: '',
            key: 'conversionRate',
            type: 'rate'
          }
        ],
        [
          {
            label: '活动转化金额(实付)',
            value: '',
            unit: '元',
            key: 'actualSale',
            type: 'moneyNum'
          }
        ],
        [
          {
            label: '客单价',
            value: '',
            key: 'perCustomerTransaction',
            type: 'moneyNum',
            unit: '元'
          },
          {
            label: '连带率',
            value: '',
            key: 'associatedPurchaseRate',
            type: 'number'
          }
        ]
      ],
      activityData: {},
      targetData: {},
      tableHeader: []
    };
  },
  components: {
    TargetGroup
  },
  mounted() {
    this.getActivityDetail();
    this.aiStoreTransfer();
    this.aiStoreTransferStatistics();
  },
  computed: {
    targetList() {
      return this.originTargetList
        .map(el => {
          return el.filter(item => {
            const value = this.targetData[item.key];
            switch (item.type) {
              case 'number':
                item.value = numFormat(value);
                break;
              case 'time':
                item.value = '--';
                if (typeof value == 'number') {
                  const h = Math.floor(value / 3600);
                  const m = Math.floor((value % 3600) / 60);
                  const s = value % 60;
                  item.value = `${h}:${m}:${s}`;
                }
                break;
              case 'moneyNum':
                item.value = numFormat(value);
                break;
              case 'rate':
                item.value = !isNaN(value) ? value + '%' : '- -';
                break;
            }
            return true;
          });
        })
        .filter(el => el.length > 0);
    },
    exportParams() {
      const { search, storeGroupId, storeGroupLevel, orderBy } = this.form;
      let params = {};
      if (this.dimension == '分组维度') {
        if (this.selectVal == 1) {
          params = { ...this.activityData, storeGroupLevel, orderBy };
        } else {
          params = { ...this.activityData, storeGroupId, orderBy };
        }
      } else {
        params = { ...this.activityData, search, storeGroupId, orderBy };
      }
      return { ...this.activityData, ...params };
    }
  },
  methods: {
    async aiStoreTransfer() {
      // 门店维度列表
      const head = {
        label: '门店名称',
        width: '250',
        prop: 'storeName',
        tooltip: true,
        fixed: 'left',
        formatter: function(row) {
          return `<span>${row.storeName ? row.storeName : '- -'}</span>`;
        }
      };
      this.tableHeader = [head, ...tableHead];
      this.loading = true;
      const { activityId, search, storeGroupId, pageNum, pageSize, orderBy } = this.form;
      try {
        const { result } = await aiStoreTransfer({ activityId, search, storeGroupId, orderBy }, `&pageNum=${pageNum}&pageSize=${pageSize}`);
        if (!result) return;
        this.tableData = result.result || [];
        this.total = result.totalCount;
        if (!storeGroupId && !search) {
          this.aiStoreTransferNoBelong();
        }
      } finally {
        this.loading = false;
      }
    },
    async aiStoreTransferNoBelong() {
      // 门店维度列表-无归属客户
      try {
        const { result } = await aiStoreTransferNoBelong({ activityId: this.$route.params.id });
        if (!result) return;
        result.numSort = 0;
        this.tableData.unshift(result);
        // this.fixedTableData = [result];
      } finally {
        this.loading = false;
      }
    },
    async aiStoreTransferStatistics() {
      // 门店维度列表-统计数据
      try {
        this.cardLoading = true;
        const { activityId, search, storeGroupId } = this.form;
        const { result } = await aiStoreTransferStatistics({ activityId, search, storeGroupId });
        if (!result) return;
        this.targetData = result;
      } finally {
        this.cardLoading = false;
      }
    },
    async aiStoreGroupTransfer() {
      // 分组维度列表
      const head = {
        label: '分组名称',
        prop: 'name',
        width: '150',
        tooltip: true,
        fixed: 'left',
        formatter: function(row) {
          return `<span>${row.name ? row.name : '- -'}</span>`;
        }
      };
      this.tableHeader = [head, ...tableHead];
      this.loading = true;
      const { activityId, storeGroupLevel, storeGroupId, pageNum, pageSize, orderBy } = this.form;
      let params = {};
      if (this.selectVal == 1) {
        params = { activityId, storeGroupLevel, orderBy };
      } else {
        params = { activityId, storeGroupId, orderBy };
      }
      try {
        const { result } = await aiStoreGroupTransfer(params, `&pageNum=${pageNum}&pageSize=${pageSize}`);
        if (!result) return;
        this.tableData = result.result || [];
        this.total = result.totalCount;
      } finally {
        this.loading = false;
      }
    },
    async aiStoreGroupTransferStatistics() {
      // 分组维度列表-统计数据
      try {
        this.cardLoading = true;
        const { activityId, storeGroupLevel, storeGroupId } = this.form;
        let params = {};
        if (this.selectVal == 1) {
          params = { activityId, storeGroupLevel };
        } else {
          params = { activityId, storeGroupId };
        }
        const { result } = await aiStoreGroupTransferStatistics(params);
        if (!result) return;
        this.targetData = result;
      } finally {
        this.cardLoading = false;
      }
    },
    async aiTransformStoreGroupSplit() {
      const { activityId, planId } = this.activityData;
      let res = await aiTransformStoreGroupSplit({ activityId, planId });
      this.options.treeOptions.data = res.result || [];
    },
    async getActivityDetail() {
      try {
        const { result } = await getActivityDetail({ activityId: this.$route.params.id });
        if (!result) return;
        const { startDate, endDate, activityName, activityId } = result;
        const smsFlag = result.activityPlanList[0].activityEventList[0].smsFlag;
        const planId = result.activityPlanList[0].planId;
        this.activityData = { startTime: startDate, endTime: endDate, smsFlag, activityName, activityId, planId };
        this.aiTransformStoreGroupSplit();
      } catch (err) {}
    },
    radioChange(data) {
      this.form = {
        search: '',
        storeGroupId: '',
        storeGroupLevel: '',
        activityId: this.$route.params.id,
        pageNum: 1,
        pageSize: 20,
        orderBy: ''
      };
      if (data == '分组维度') {
        this.form.storeGroupLevel = 1;
        this.selectVal = 1;
        // 分组维度列表+统计数据
      }
      try {
        this.$refs.selectTree.onClearSelect();
      } catch (err) {
        console.log(err);
      }
    },

    handleSizeChange(val) {
      this.form.pageSize = val;
      this.form.pageNum = 1;
      this.getListData();
    },
    groupSelectChange(data) {
      // 分组维度列表+统计数据
      this.aiStoreGroupTransfer();
      this.aiStoreGroupTransferStatistics();
    },
    handleSearch() {
      this.form.pageNum = 1;
      this.getStaticListData();
    },
    getListData() {
      if (this.dimension == '门店维度') {
        this.aiStoreTransfer();
      } else if (this.dimension == '分组维度') {
        this.aiStoreGroupTransfer();
      }
    },
    getStaticListData() {
      if (this.dimension == '门店维度') {
        // 门店维度列表+统计数据
        this.aiStoreTransfer();
        this.aiStoreTransferStatistics();
      } else if (this.dimension == '分组维度') {
        // 分组维度列表+统计数据
        this.aiStoreGroupTransfer();
        this.aiStoreGroupTransferStatistics();
      }
    },
    onChange(data) {
      console.log(data);
      this.form.storeGroupId = data ? data.storeGroupId : undefined;
      this.getStaticListData();
    },
    handleExport() {
      this.dialogVisible = true;
      if (this.dimension == '门店维度') {
        this.excelUrl = exportAiStoreTransfer;
      } else if (this.dimension == '分组维度') {
        this.excelUrl = exportAiStoreGroupTransfer;
      }
    },
    handleSortChange(data) {
      const { prop, order } = data;
      console.log(order);
      if (order == 'descending') {
        this.form.orderBy = prop + ' desc';
      } else if (order === 'ascending') {
        this.form.orderBy = prop + ' asc';
      } else {
        this.form.orderBy = undefined;
      }
      this.form.pageNum = 1;
      this.getListData();
    }
  }
};
</script>

<style lang="scss" scoped>
.aiCall {
  padding: 5px 20px;
  .radioButton {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
  }
  .cardContent {
    margin: -14px 0 20px 0;
  }
  .table-page-search-wrapper {
    /deep/ .el-form-item__content {
      display: flex;
    }
  }
}
</style>
