<template>

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

          <div>
            <el-form-item v-if="source==='project'"
                          style="margin-left:10px">
              <el-button @click="handleBack()"
                         size="mini"
                         icon="el-icon-back"
                         type="warning"
                         plain>返回</el-button>
            </el-form-item>

            <el-form-item label="所属组织"
                          :label-width="labelWidth">
              <el-cascader ref="myCascader"
                           v-model="agencyIdArray"
                           style="width:480px"
                           :key="iscascaderShow"
                           :options="casOptions"
                           :props="optionProps"
                           @change="handleChange"></el-cascader>
            </el-form-item>

            <div>
              <el-form-item label="统计类型"
                            :label-width="labelWidth">
                <el-radio-group v-model="staticType"
                                @change="handleTypeChange">
                  <el-radio label="end">截止累计值</el-radio>
                  <el-radio label="Interval">区间新增值</el-radio>
                </el-radio-group>

                <el-date-picker style="margin-left:30px"
                                v-if="staticType==='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="staticType==='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="loadTable()"
                           type="primary">查询</el-button>
              </el-form-item>
              <el-form-item style="margin-left:10px">
                <el-button @click="handelExport()"
                           type="primary">导出</el-button>
              </el-form-item>
            </div>

          </div>
        </el-form>

        <classify-list v-if="source==='classify'"
                       ref="ref_classify"
                       @changeSource="changeSource"></classify-list>
        <project-list v-if="source==='project'"
                      ref="ref_project"></project-list>
      </div>
    </el-card>
  </div>

</template>

<script>
import util from '@js/util.js';
import { mapGetters } from 'vuex'
import { Loading } from 'element-ui' // 引入Loading服务
import { requestPost } from '@/js/dai/request'
import ClassifyList from "./classifyList"
import ProjectList from "./projectList"

let loading // 加载动画

export default {
  data () {
    return {
      source: "classify",//父组件来源 classify 分类列表 project 项目列表
      downloadLoading: false,

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

      casOptions: [],
      agencyIdArray: [],
      selAgencyObj: {},
      iscascaderShow: 0,

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

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

      staticType: 'end',
      tableParams: {
        orgId: '', //组织ID	
        orgType: '', //组织类型 组织：agency，网格：grid
        startTime: '', //开始时间【yyyymmdd】	,截止累计值
        endTime: '', //结束时间【yyyymmdd】,
      },
      timeArray: ['', ''],
      endTimeModel: new Date() - 60 * 60 * 24 * 2,

      //导出表格部分
      startTimeShow: '',//导出表格标题处显示的内容 	
      endTimeShow: '', //导出表格标题处显示的内容 

      oldParams: {}//当进入项目时，记录原查询条件，返回时充值为原条件

    }
  },
  props: {
  },

  mounted () {
    this.customerId = localStorage.getItem('customerId')
    this.initData()
  },

  methods: {
    async initData () {
      this.startLoading()
      this.initDate()
      await this.getAgencylist()//获取组织级联列表
      this.loadTable()
      this.endLoading()
    },

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

      const params = {
        // customerId: this.customerId
      }
      const { data, code, msg } = await requestPost(url, params)
      if (code === 0) {
        ++this.iscascaderShow
        this.casOptions = []
        this.agencyIdArray = []
        this.tableParams.orgId = ''
        if (data) {
          //默认级联选中父级
          this.selAgencyObj = {
            agencyId: data.agencyId,
            agencyName: data.agencyName,
            level: data.level,
            pid: data.pid,
          }

          this.casOptions.push(data)
          this.agencyIdArray.push(data.agencyId)

        }

      } else {
        this.$message.error(msg)
      }
    },
    async loadTable () {
      if (this.validate()) {
        this.tableParams.orgId = this.selAgencyObj.agencyId
        this.tableParams.orgType = this.selAgencyObj.level

        if (this.staticType === 'end') {
          this.tableParams.startTime = ''
        }
        console.log(this.tableParams)
        if (this.source === 'classify') {
          this.$nextTick(() => {
            this.$refs.ref_classify.loadTable(this.tableParams)
          })
        } else {
          this.$nextTick(() => {
            this.$refs.ref_project.loadTable(this.tableParams)
          })
        }
      }

    },

    //切换来源
    changeSource (source) {
      this.source = source
      if (source === 'project') {//进入项目
        this.oldParams = {
          staticType: this.staticType,
          tableParams: this.tableParams,
          timeArray: ['', ''],
          endTimeModel: new Date() - 60 * 60 * 24 * 2,

          //导出表格部分
          startTimeShow: '',//导出表格标题处显示的内容 	
          endTimeShow: '', //导出表格标题处显示的内容 
        }



      } else {

      }
    },

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

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

      if (this.source === 'classify') {
        this.$nextTick(() => {
          this.exportClassify()
        })
      } else {
        this.$nextTick(() => {
          this.exportProject()
        })
      }
    },

    async exportProject () {
      const params = {
        status: this.tableParams.status,
        categoryCode: this.tableParams.categoryCode,
        categoryName: this.categoryName,
        orgId: this.tableParams.orgId,
        startTime: this.tableParams.startTime,
        endTime: this.tableParams.endTime,
        parentCategoryName: this.parentCategoryName,
      }

      const url = "/data/report/screen/project/selectcategoryprojectlist/export"

      app.ajax.exportFilePost(
        url,
        params,
        (data, rspMsg) => {

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

    async exportClassify () {
      const url = "/data/report/screen/project/selectprojectcategory/export"

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

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

    handleBack () {
      this.$emit('back')
      this.changeSource('classify')
    },

    handleChange (value) {
      if (value && value.length > 0) {
        this.selAgencyObj = this.$refs["myCascader"].getCheckedNodes()[0].data

      } else {
        this.selAgencyObj = {}

      }
    },

    initDate () {
      //设置默认结束日期为前一天
      let date = new Date()
      date.setTime(date.getTime() - 24 * 60 * 60 * 1000);
      const month = date.getMonth() + 1 > 9 ? (date.getMonth() + 1) : '0' + (date.getMonth() + 1)
      const day = date.getDate() > 9 ? (date.getDate()) : '0' + (date.getDate())

      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] + '日'
    },
    handleTypeChange (value) {
      if (value === 'end') {

        const endTimeArray = util.dateFormatter(this.endTimeModel, 'date').split('-')
        this.tableParams.startTime = ''
        this.tableParams.endTime = endTimeArray[0] + endTimeArray[1] + endTimeArray[2]

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

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

    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 = ''
      }

    },


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

      return true
    },




    // 下载文件
    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);
      }

    },

    // 开启加载动画
    startLoading () {
      loading = Loading.service({
        lock: true, // 是否锁定
        text: '正在加载……', // 加载中需要显示的文字
        background: 'rgba(0,0,0,.7)' // 背景颜色
      })
    },
    // 结束加载动画
    endLoading () {
      // clearTimeout(timer);
      if (loading) {
        loading.close()
      }
    }
  },
  computed: {


    ...mapGetters(['clientHeight', 'env'])
  },
  components: {
    ClassifyList, ProjectList
  },
  activated () {

  },
}
</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>

