<template>
  <div>
    <Row :gutter="32">
      <i-col span="32">
        <row>
          <!--搜索、状态行-->
          <row style="height: 73px;line-height: 73px;background: #F7F8FA">
            <row>
              <span class="left-15">选择日期</span>
              <DatePicker v-model="dateRange" separator="至" class="left-10" type="daterange" placement="bottom-start" split-panels placeholder="请选择日期区间" style="width: 200px" size="small"></DatePicker>
              <span style="margin: 0 10px">大区</span>
              <Select filterable placeholder="请选择大区" v-model="regionId" @on-change="regionSelect" style="width:190px" size="small">
                <Option v-for="item in regionList" :value="item.id" :key="item.id">{{ item.name }}</Option>
              </Select>
              <span style="margin: 0 10px">零售公司</span>
              <Select filterable placeholder="请选择零售公司" v-model="orgId" @on-change="orgSelect" style="width:190px" size="small">
                <Option v-for="item in orgList" :value="item.id" :key="item.id">{{ item.name }}</Option>
              </Select>
              <span style="margin: 0 10px">客户</span>
              <Select filterable placeholder="请选择客户" v-model="customerId" style="width:190px" size="small">
                <Option v-for="item in customerList" :value="item.id" :key="item.id">{{ item.name }}</Option>
              </Select>
              <Button type="primary" style="width: 70px;margin-left: 20px" @click="searchBtnClick" size="small">查询</Button>
              <Button type="primary" style="width: 80px;margin-left: 20px;" @click="exportZeroExtend" size="small">导出数据</Button>
            </row>
          </row>
          <!--表格数据-->
          <row style="margin-top: 30px">
            <Table :columns="columns1" :data="data1"></Table>
            <Spin style="top: 40px;height: 200px" size="large" fix v-if="spinShow"></Spin>
            <Page :total="totalSize" :current="pageNum" :page-size="pageSize" show-elevator show-total
                  placement="top" @on-change="handlePage" style="margin-top: 20px;float: right"></Page>
          </row>
        </row>
      </i-col>
    </Row>
  </div>
</template>
<script>

  import zeroExtend from "../services/customer/zeroExtend";
    export default {
        inject:['checkParamBlank'],
        data() {
            return {
              columns1: [
                {
                  title: '序号',
                  width:'80px',
                  key: 'number',
                  align: 'center',
                },
                {
                  title: '店铺名称',
                  key: 'shopName',
                  align: 'left',
                  width:'300px',
                },
                {
                  title: '店铺编码',
                  key: 'shopCode',
                  align: 'left',
                  width:'150px',
                },
                {
                  title: '大区',
                  key: 'region',
                  align: 'left',
                  width:'200px',
                },
                {
                  title: '零售公司',
                  key: 'company',
                  width:'150px',
                  align: 'left',
                },
                {
                  title: '客户',
                  key: 'customer',
                  align: 'left',
                },
              ],

              userId: JSON.parse(sessionStorage.getItem("loginInfo")).userId,
              //加载遮罩
              spinShow: false,
              //mainData
              data1: [],
              orginAllData: [],

              //开始时间，结束时间
              dateRange: [this.$route.query.startDate, this.$route.query.endDate],
              //所有组织list
              organizationalList: [],
              //区域list
              regionList: [],
              regionId: 0,
              //零售公司list
              orgList: [],
              orgId: 0,
              //客户list
              customerList: [],
              customerId: 0,

              totalSize: 0,
              pageNum: 1,
              pageSize: 10,

            }
        },
        mounted: function () {
          this.getSelectList();
          this.getMainList();
        },
        methods: {
          //格式化日期
          formartDate: function(date, format, endFlag){
            if(!date){
              return null;
            }
            if(endFlag == null){
              return this.$moment(date).format(format) + " 00:00:00";
            }else{
              return this.$moment(date).format(format) + " 23:59:59";
            }
          },
          //区域选择
          regionSelect: function(){
            let regionId = this.regionId;
            if(regionId === 0){
              this.orgList = this.organizationalList.filter(item => item.level === 2);
              this.customerList = this.organizationalList.filter(item => item.level === 3);
            }else{
              this.orgList = this.organizationalList.filter(item => item.parentId === regionId && item.level === 2);
              let orgIds = this.orgList.map(item => item.id);
              this.customerList = this.organizationalList.filter(item => orgIds.indexOf(item.parentId) !== -1 && item.level === 3);
            }
            this.insertAllOption();
            this.orgId = 0;
            this.customerId = 0;
          },
          //零售公司选择
          orgSelect: function(){
            let orgId = this.orgId;
            if(orgId === 0){
              let orgIds = this.orgList.map(item => item.id);
              this.customerList = this.organizationalList.filter(item => orgIds.indexOf(item.parentId) !== -1 && item.level === 3);
            }else{
              this.customerList = this.organizationalList.filter(item => item.parentId === orgId && item.level === 3);
            }
            this.insertAllOption();
            this.customerId = 0;
          },
          //插入全部选项
          insertAllOption: function(){
            if(this.regionList.length === 0 || this.regionList[0].id !== 0){
              this.regionList.splice(0,0, {"id":0, "name":"全部"});
            }
            if(this.orgList.length === 0 || this.orgList[0].id !== 0){
              this.orgList.splice(0, 0, {"id":0, "name":"全部"});
            }
            if(this.customerList.length === 0 || this.customerList[0].id !== 0){
              this.customerList.splice(0, 0, {"id":0, "name":"全部"});
            }
          },
          //查询按钮
          searchBtnClick: function(){
            this.pageNum = 1;
            this.getMainList();
          },
          //零推广导出
          exportZeroExtend: function(){
            let title = "0推广店铺";
            if(this.dateRange[0]){
              let start = this.$moment(this.dateRange[0]).format("YYYY-MM-DD");
              let end = this.$moment(this.dateRange[1]).format("YYYY-MM-DD");
              title += "（" + start + "至" + end + "）";
            }
            this.originAllData = [];
            let that = this;
            let request = {
              userId: that.userId,
              pageNum : 1,
              pageSize : that.totalSize,
              regionId : that.regionId === 0 ? null : that.regionId,
              companyId : that.orgId === 0 ? null : that.orgId,
              customerId : that.customerId === 0 ? null : that.customerId,
              startTime : this.formartDate(that.dateRange[0], "YYYY-MM-DD"),
              endTime : this.formartDate(that.dateRange[1], "YYYY-MM-DD", true),
            };
            zeroExtend.getMainRequest(request,function (data) {
              if(data.data.code !== "0000"){
                that.$Message.error("系统异常");
              }
              data = data.data.results;
              if(data && data.length > 0){
                that.totalSize = data[0].totalSize;
                for(let i=0;i<data.length;i++){
                  let entity = data[i];
                  that.originAllData.push(entity);
                }
                require.ensure([], () => {
                  const { export_json_to_excel } = require('../excel/Export2Excel');
                  const tHeader = ['序号', '店铺名称', '店铺编码', '大区', '零售公司', '客户', '推广数'];
                  // 属性名
                  const filterVal = ['number', 'shopName', 'shopCode', 'region', 'company', 'customer', 'numb'];
                  // 数据
                  const list = that.originAllData;  //把data里的tableData存到list
                  const data = that.formatJson(filterVal, list);
                  export_json_to_excel(tHeader, data, title);
                });
              }
              if(data && data.length === 0){
                that.$Message.info("暂无数据");
              }
            });
          },
          formatJson(filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => v[j]))
          },
          /**mainList数据*/
          getMainList: function () {
              this.data1 = [];
              let that = this;
              let request = {
                  userId: that.userId,
                  pageNum : that.pageNum,
                  pageSize : that.pageSize,
                  regionId : that.regionId === 0 ? null : that.regionId,
                  companyId : that.orgId === 0 ? null : that.orgId,
                  customerId : that.customerId === 0 ? null : that.customerId,
                  startTime : this.formartDate(that.dateRange[0], "YYYY-MM-DD"),
                  endTime : this.formartDate(that.dateRange[1], "YYYY-MM-DD", true),
              };
              //加载遮罩
              this.spinShow = true;
              zeroExtend.getMainRequest(request,function (data) {
                  that.spinShow = false;
                  if(data.data.code !== "0000"){
                    that.$Message.error("系统异常");
                  }
                  data = data.data.results;
                  if(data && data.length > 0){
                      that.totalSize = data[0].totalSize;
                      for(let i=0;i<data.length;i++){
                          let entity = data[i];
                          that.data1.push(entity);
                          //null改--
                          that.checkParamBlank(entity);
                      }
                  }
                  if(data == null || data.length === 0){
                      that.totalSize = 0;
                  }
              });

          },
          /**基础数据：区域list、零售公司list、客户list*/
          getSelectList:function(){
            let that = this;
            let request = {
              userId: this.userId,
            };
            zeroExtend.getSelectListRequest(request,function (data) {
              if(data.data.code !== "0000"){
                that.$Message.error("系统异常");
              }
              data = data.data.results;
              if(data){
                that.organizationalList = data;
                that.regionList = that.organizationalList.filter(item => item.level === 1);
                that.orgList = that.organizationalList.filter(item => item.level === 2);
                that.customerList = that.organizationalList.filter(item => item.level === 3);
              }
              //插入全部选项
              that.insertAllOption();
            });
          },
          //切页处理
          handlePage: function (value) {
            this.pageNum = value;
            this.getMainList();
            sessionStorage.setItem("hisOrderPageNum", this.pageNum)
          },



        }
    }
</script>

<style scoped>

  .top-10{
    margin-top: 10px;
  }
  .left-10{
    margin-left: 10px;
  }
  .left-15{
    margin-left: 15px;
  }
</style>
