<template>
  <div class="app-container">
    <div class="app-container-search main-bgcolor main-radius">
      <h1 class="">扫码统计</h1>
      <br />
      <!-- 搜索工作栏 -->
      <StatsForm
        ref="searchForm"
        :searchFormParam="{ queryParams, dataSource }"
        :showSearch.sync="showSearch"
        @handleQuery="handleQuery"
        @selectChage="selectChage"
      ></StatsForm>
    </div>

    <!-- 列表 -->
    <div class="app-container-search main-bgcolor main-radius">
      <h2>扫码详情</h2>
      <el-table v-loading="loading" :data="list">
        <!-- 编号就是序号 -->
        <el-table-column label="商品名称" align="center" prop="goodsName" />
        <el-table-column label="扫码次数" align="center" prop="scanCount" />
        <el-table-column label="操作" Border="100px"  min-width="600" align="center" class-name="small-padding fixed-width" >
          <template slot-scope="scope">
            <div style="display: flex;
                        justify-content: start;
                        align-items: center;width:100%;">
              <div style="width: 48%; border-bottom: 1px solid rgb(51 51 51 / 41%); height: 38px;"></div>
              <el-button
                type="text"
                @click="handlecheck(scope.row)">
                查看趋势
              </el-button>
            </div>
          </template>
        </el-table-column>
        <div slot="empty">
          <StatsTable />
        </div>
    </el-table>
    </div>
  </div>
</template>


<script>
import { getBusinessNameList } from '@/api/basic/businessInfo'
import StatsForm from '@/components/Customer/SearchForm'
import StatsTable from '@/components/EmptyTable'
import { getGoodsListByBelongBusinessId } from '@/api/basic/goodsInfo'
import { getScanRecordTimeList } from '@/api/identity/scanRecord'
export default {
  name: 'DiversionStats',
  components: {
    StatsForm,
    StatsTable,
  },
  data() {
    return {
      //展示层
      foldBoole: false,
      // 遮罩层
      loading: false,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 窜货统计列表
      list: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        dealerId: null,
        dealerName: null,
        batchId: null,
        goodsId: null,
        goodsName: null,
        num: null,
        belongBusinessId: null,
        belongBusinessName: null,
        businessName: null,
        timeHorizon: null,
        scanCount: null,
        createTime: [],
      },
      //表对象
      dataSource: [
        {
          key: 'belongBusinessId', //商户名称
          itemType: 'select',
          label: '商户名称',
          placeholder: '请选择品牌',
          onEnterKeyUp: this.handleQuery,
          options: [],
          isNet: true,
        },
        {
          key: 'goodsName', //商品名称
          itemType: 'select',
          label: '商品',
          placeholder: '请输入',
          onEnterKeyUp: this.handleQuery,
          options: [],
        },
        {
          key: 'timeHorizon', //时间范围
          itemType: 'datePicker',
          label: '时间范围',
          placeholder: '请选择',
          onEnterKeyUp: this.handleQuery,
        },
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        businessName: [
          { required: true, message: '商户名称不能为空', trigger: 'blur' },
        ],
        goodsName: [
          { required: true, message: '商品名称不能为空', trigger: 'blur' },
        ],
          timeHorizon: [
          { required: true, message: '时间范围不能为空', trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    // this.getList()
    this.getBusinessNameList()
  },
  methods: {
    handlecheck(row){
      let { timeHorizon, goodsName , belongBusinessName , goodsId , belongBusinessId } = this.queryParams;
      this.$router.push({
        'path':'/clientGroup/clientGroup-trend',
        'query':{
          id:row.list[0].goodsId,
          params: JSON.stringify({ timeHorizon, goodsName , belongBusinessName , goodsId , belongBusinessId }),
        },
      })
    },
    selectChage({ value, type, book }) {
      console.log('搜索改变',value, type, book);
      if (type == 'belongBusinessId') {
        let info = this.dataSource[0].options.find(item=>item.value == value);
        console.log('find值',info);
        this.queryParams.belongBusinessName = info.label;
      }
      if (!book) {
        return
      }
      getGoodsListByBelongBusinessId({
        belongBusinessId: value,
      }).then((res) => {
        console.log(res, 'res')
        this.$nextTick(() => {
          this.dataSource[1].options = res.data.map((el) => {
            let obj = {
              label: el.goodsName,
              value: el.goodsName,
              key: el.id,
            }
            return obj
          });
        })
      })
    },
    /** 查询列表 */
    getList() {
      // 执行查询
      this.loading = true;
      getScanRecordTimeList({
      ...this.queryParams,
      ids:''}).then((response) => {
        let list = response.data;
        // var newList = getListGroupBy(list, 'goodsName');
        // if(newList.length){
        //   newList.map((item) => {
        //     item.scanCount = item.list ? item.list.length : 0;
        //   })
        // }else{
        //   let businessName;
        //   this.dataSource[0].options.map(item=>{
        //     if(item.key == this.queryParams.businessName){
        //       businessName = item.label;
        //     }
        //   });
        //   let goodsName;
        //   this.dataSource[1].options.map(item=>{
        //     if(item.key == this.queryParams.goodsName){
        //       goodsName = item.label;
        //     }
        //   });
        //   newList.push({
        //     businessName,
        //     goodsName,
        //     timeHorizon: this.queryParams.timeHorizon,
        //     scanCount: 0,
        //     list: [
        //       {
        //         businessName,
        //         businessId: this.queryParams.businessName,
        //         goodsName,
        //         goodsId: this.queryParams.goodsName,
        //         timeHorizon: this.queryParams.timeHorizon,
        //       },
        //     ],
        //   });
        // }

        let newList = [];
        let businessInfo = this.dataSource[0].options.find(item=>item.key == this.queryParams.belongBusinessId);
        let businessName = businessInfo.label;
        let goodsInfo = this.dataSource[1].options.find(item=>item.label == this.queryParams.goodsName);
        let goodsName = goodsInfo.label;
        let goodsId = goodsInfo.key;
        this.queryParams.goodsId = goodsId;
        newList.push({
          businessName,
          goodsName,
          timeHorizon: this.queryParams.timeHorizon,
          scanCount: list?list:0,
          list: [
            {
              businessName,
              businessId: this.queryParams.belongBusinessId,
              goodsName,
              goodsId,
              timeHorizon: this.queryParams.timeHorizon,
            },
          ],
        });
        console.log('列表',newList);
        this.list = newList;
        this.loading = false;
      }).catch(()=>{
        this.loading = false;
      })
    },
    //获取商户名称
    async getBusinessNameList() {
      const res = await getBusinessNameList()
      console.log('res', res)
      this.$nextTick(() => {
        this.dataSource[0].options = res.data.map((el) => {
          let obj = {
            label: el.businessName,
            value: el.id,
            key: el.id,
          }
          return obj
        })
      })
    },
    /** 取消按钮 */
    cancel() {
      this.open = false
      this.reset()
    },
    /** 表单重置 */
    reset() {
      this.form = {
        businessName: undefined,
        goodsName: undefined,
        timeHorizon: undefined,
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      if( !this.queryParams.belongBusinessId || !this.queryParams.goodsName || !this.queryParams.timeHorizon || this.queryParams.timeHorizon.length == 0 ){
        this.$message.error("搜索栏所有参数不能为空");
        return false;
      }
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
  },
}

/**根据相同字段组成新的对象数组 */
// function getListGroupBy(list, key) {
//   var keysArr = list.map(item=>item[key])
//   var keys = [...new Set(keysArr)]
//   var newList = keys.map(item=> {
//     return {
//       [key]: item,
//       list: list.filter(i=>i[key] == item)
//     }
//   })
//   return newList
// }

</script>
<style>
element.style {
    position: relative;
    width: 400px;
    height: 40px;
    display: inline-block;
    vertical-align: middle;
    cursor: default;
}
</style>
