<template>
  <div class="registerList">
    <el-card shadow="never"
             class="aui-card--fill">
      <div class="mod-demo__demo}">
        <el-form :inline="true"
                 :model="tableParams"
                 @keyup.enter.native="loadData()">

          <div>
            <el-form-item label="选择客户"
                          :label-width="labelWidth">
              <el-select v-model="tableParams.customerId"
                         placeholder="客户"
                         clearable>
                <el-option v-for="(item,index) in customerList"
                           :key="index"
                           @click.native="handelChangeCustomer(index)"
                           :label="item.customerName"
                           :value="item.customerId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="所属组织"
                          :label-width="labelWidth">
              <el-cascader v-model="agencyIdArray"
                           style="width:480px"
                           :key="iscascaderShow"
                           :options="options"
                           :props="optionProps"
                           clearable></el-cascader>
            </el-form-item>

            <div>
              <el-form-item label="统计类型"
                            :label-width="labelWidth">
                <el-radio v-model="tableParams.type"
                          label="end">截止累计值</el-radio>
                <el-radio v-model="tableParams.type"
                          label="Interval">区间新增值</el-radio>

                <el-date-picker style="margin-left:30px"
                                v-if="tableParams.type==='Interval'"
                                v-model="timeArray"
                                type="daterange"
                                range-separator="至"
                                @change="handleTimeChange"
                                format="yyyy-MM-dd"
                                :picker-options="pickerOptions"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期">
                </el-date-picker>

                <el-date-picker style="margin-left:30px"
                                v-if="tableParams.type==='end'"
                                v-model="endTimeModel"
                                @change="handleEndTimeChange"
                                :picker-options="pickerOptions"
                                type="date"
                                placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item style="margin-left:10px">
                <el-button @click="loadData()"
                           type="primary">查询</el-button>
              </el-form-item>
              <el-form-item style="margin-left:10px">
                <el-button @click="loadOutTableData()"
                           type="primary">导出</el-button>
              </el-form-item>
            </div>

          </div>
        </el-form>

        <c-table ref="table"
                 :url="tableUrl"
                 :params="tableParams"
                 keyword="operStaticList"
                 :operations="operations"
                 :tableHeight="tableHeight">
        </c-table>
      </div>

    </el-card>

  </div>
</template>

<script>
import CTable from '@c/CTable'
import util from '@js/util.js';

import { mapGetters } from 'vuex'
import { Loading } from 'element-ui' // 引入Loading服务
import { requestPost } from '@/js/dai/request'
// import { export_json_to_excel } from '@/vendor/Export2Excel'

let loading // 加载动画
const customerId = localStorage.getItem('customerId')
export default {
  data () {
    return {

      tableData1: [
        { 'name': 'lgk', 'sex': '男', 'username': 'liqing' },
        { 'name': 'll', 'sex': '女', 'username': 'yaoyao' }
      ],

      tableData: [],

      downloadLoading: false,

      //查询条件标题宽度
      labelWidth: '70px',

      options: [],
      agencyIdArray: [],
      customerList: [],
      iscascaderShow: 0,

      optionProps: {
        value: 'agencyId',
        label: 'agencyName',
        children: 'subAgencyList',
        checkStrictly: true
      },


      pickerOptions: { //控制时间范围
        disabledDate (time) {
          return time.getTime() > (Date.now() - (24 * 60 * 60 * 1000))
        }
      },

      // 列表相关
      tableUrl: '/data/aggregator/datastats/operatedata',
      // tableUrl: 'http://yapi.elinkservice.cn/mock/102/data/aggregator/datastats/operatedata',
      tableParams: {
        customerId: '', //客户Id	
        agencyId: '', //所选组织Id 	
        type: 'end', //区间:Interval  截止:end	
        startTime: '', //开始时间【yyyymmdd】	
        endTime: '', //结束时间【yyyymmdd】	
        isPage: true
      },
      timeArray: ['', ''],
      customerName: '',
      agencyName: '',
      startTimeShow: '',//导出表格标题处显示的内容 	
      endTimeShow: '', //导出表格标题处显示的内容 	
      endTimeModel: new Date() - 60 * 60 * 24 * 2,

      operations: [
      ],

    }
  },
  components: {
    CTable
  },
  activated () {
    this.$nextTick(() => {
      this.$refs.table.doLayout() // 解决表格错位
    })
  },
  mounted () {
    this.initData()
  },
  computed: {
    tableHeight () {
      return this.clientHeight - 60 - 80 - 80 - 100
    },

    ...mapGetters(['clientHeight', 'env'])
  },
  methods: {
    async initData () {
      this.startLoading()
      this.initDate()
      await this.loadCustomer()//获取客户列表

      this.endLoading()
    },

    initDate () {
      //设置默认结束日期为前一天
      const date = new Date()
      const month = date.getMonth() + 1 > 9 ? (date.getMonth() + 1) : '0' + (date.getMonth() + 1)
      const day = date.getDate() - 1 > 9 ? (date.getDate() - 1) : '0' + (date.getDate() - 1)
      const yesterday = date.getFullYear() + '-' + month + '-' + day
      this.timeArray = ['', yesterday]
      this.endTimeModel = yesterday

      let yesterdayArray = yesterday.split('-')

      this.tableParams.endTime = yesterdayArray[0] + yesterdayArray[1] + yesterdayArray[2]

      this.endTimeShow = yesterdayArray[0] + '年' + yesterdayArray[1] + '月' + yesterdayArray[2] + '日'
    },

    loadData () {
      if (this.validate()) {
        this.tableParams.isPage = true
        this.$refs.table.loadData()
      }
    },

    //获取客户列表
    async loadCustomer (row) {
      const url = ' https://epmet-cloud.elinkservice.cn/api/third/pacustomer/registerbyauth'
      const params = {
        //  workAuth: 1,
        // resiAuth: 1,
        source: this.env,
        initState: 1
      }

      const { data, code, msg } = await requestPost(url, params)
      if (code === 0) {
        this.customerList = data

      } else {
        this.$message.error(msg)
      }
    },

    handelChangeCustomer (index) {
      this.customerName = this.customerList[index].customerName
      this.getAgencylist()//获取组织级别

    },

    handleEndTimeChange (item) {
      if (item) {
        const endTimeArray = util.dateFormatter(item, 'date').split('-')
        this.tableParams.endTime = endTimeArray[0] + endTimeArray[1] + endTimeArray[2]
        this.endTime = endTimeArray[0] + '年' + endTimeArray[1] + '月' + endTimeArray[2] + '日'
      } else {
        this.tableParams.endTime = ''
        this.endTimeShow = ''
      }
    },

    handleTimeChange (time) {
      if (time) {
        const startTimeArray = util.dateFormatter(time[0], 'date').split('-')
        const endTimeArray = util.dateFormatter(time[1], 'date').split('-')

        this.tableParams.startTime = startTimeArray[0] + startTimeArray[1] + startTimeArray[2]
        this.tableParams.endTime = endTimeArray[0] + endTimeArray[1] + endTimeArray[2]

        this.startTimeShow = startTimeArray[0] + '年' + startTimeArray[1] + '月' + startTimeArray[2] + '日'
        this.endTimeShow = endTimeArray[0] + '年' + endTimeArray[1] + '月' + endTimeArray[2] + '日'
      } else {
        this.tableParams.startTime = ''
        this.tableParams.endTime = ''
        this.startTimeShow = ''
        this.endTimeShow = ''
      }

    },

    async getAgencylist () {
      const url = '/gov/org/customeragency/agencylist'
      // const url = 'http://yapi.elinkservice.cn/mock/102/gov/org/agency/agencylist'

      const params = {
        customerId: this.tableParams.customerId
      }
      const { data, code, msg } = await requestPost(url, params)
      if (code === 0) {
        ++this.iscascaderShow
        this.options = []
        this.agencyIdArray.length = []
        this.tableParams.agencyId = ''
        if (data) {
          this.options.push(data)
        }

      } else {
        this.$message.error(msg)
      }
    },
    validate () {

      if (!this.tableParams.customerId || this.agencyIdArray.length == 0) {
        this.$message.info("请选择客户和组织")
        return false
      }

      if (this.tableParams.type === 'Interval' && (!this.tableParams.endTime || !this.tableParams.startTime)) {
        this.$message.info("请选择起止日期")
        return false
      }

      if (this.tableParams.type === 'end' && !this.tableParams.endTime) {
        this.$message.info("请选择结束日期")
        return false
      }

      this.tableParams.agencyId = this.agencyIdArray[this.agencyIdArray.length - 1]

      return true
    },

    //导出表格
    async loadOutTableData () {
      if (!this.validate()) {
        return false
      }
      let title = this.agencyName

      if (this.tableParams.type === 'Interval') {
        title = title + + this.startTimeShow + '-' + this.endTimeShow + '区间增长值'
      } else {
        title = title + '截止至' + this.endTimeShow + '累计值'
      }
      console.log(title)

      const url = "/data/aggregator/datastats/operateexport"
      // const url = "http://yapi.elinkservice.cn/mock/102/data/aggregator/datastats/operateexport"
      this.tableParams.isPage = false
      // this.tableParams.agencyId = '30705f91f1295ae77d372b868596a5e7'
      // this.tableParams = {
      //   "customerId": "613cc61a6b8ce4c70d21bd413dac72cc",
      //   "agencyId": "30705f91f1295ae77d372b868596a5e7",
      //   "type": "Interval",
      //   "isPage": true,
      //   "endTime": "20210909",
      //   "startTime": "20210901"
      // }

      console.log(this.tableParams)
      app.ajax.exportFilePost(
        url,
        this.tableParams,
        (data, rspMsg) => {

          this.download(data, title + '.xls')
        },
        (rspMsg, data) => {
          this.$message.error(rspMsg);
        }
      );

    },


    // 下载文件
    download (data, fileName) {
      if (!data) {
        return
      }

      var csvData = new Blob([data])

      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(csvData, fileName);
      }
      // for Non-IE (chrome, firefox etc.)
      else {
        var a = document.createElement('a');
        document.body.appendChild(a);
        a.style = 'display: none';
        var url = window.URL.createObjectURL(csvData);
        a.href = url;
        a.download = fileName;
        a.click();
        a.remove();
        window.URL.revokeObjectURL(url);
      }

    },

    handleDownload () {

      this.downloadLoading = true
      require.ensure([], () => {

        const multiHeader = [title, '', '', '', '', '', '', '', '', '', '']
        const tHeader = ['组织', '用户数', '居民数', '党员数', '小组数', '话题数', '议题数', '项目数', '结案项目数', '巡查人数', '巡查次数', '巡查时长']
        const filterVal = ['orgName', 'userCount', 'residentCount', 'partyMemberCount', 'groupCount', 'topicCount', 'issueCount', 'projectCount', 'closedProjectCount', 'patrolPeopleCount', 'patrolCount', 'patrolDuration']
        const list = this.tableData
        const data = this.formatJson(filterVal, list)
        export_json_to_excel(multiHeader, tHeader, data, title)
        this.downloadLoading = false
      })
    },

    formatJson (filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },

    // 截取value值
    cutValue (target, name) {
      let arr = []
      for (let i = 0; i < target.length; i++) {
        arr.push(target[i][name])
      }
      return arr
    },

    // 开启加载动画
    startLoading () {
      loading = Loading.service({
        lock: true, // 是否锁定
        text: '正在加载……', // 加载中需要显示的文字
        background: 'rgba(0,0,0,.7)' // 背景颜色
      })
    },
    // 结束加载动画
    endLoading () {
      // clearTimeout(timer);
      if (loading) {
        loading.close()
      }
    }
  }
}
</script>
<style lang="css" scoped>
.myNote {
  display: -webkit-box;
  text-overflow: ellipsis;
  overflow: hidden;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}
/* .register .el-table .el-table__header-wrapper {
  position: absolute;
  top: 0;
  left: 0;
}*/
/*
.register .el-table .el-table__fixed-body-wrapper {
  height: calc(100% - 44px);
  margin-top: 44px;
  overflow-y: auto !important;
} */
</style>

