<template>
  <div class="height100 flexbox">
    <div class="flex">
      <div :class="{ 'bi-mod__item': item.elmType != 'area' }" v-for="(item, index) in screenArr" :key="index">
        <ts-radio
          v-model="areaVal"
          :title="item.title"
          :title-width="item.width"
          :data="areaType"
          width="auto"
          @change="item.event"
          v-if="item.elmType == 'area'"
        ></ts-radio>
        <ts-input
          v-model="dateVal"
          placeholder=""
          :title="item.title"
          :title-width="item.width"
          :type="item.type"
          @change="item.event"
          v-if="item.elmType == 'date' && (item.type == 'month' || item.type == 'year') && israng === false"
        ></ts-input>
        <ts-input
          v-model="postData[item.name]"
          placeholder=""
          :title="item.title"
          :title-width="item.width"
          :type="item.type"
          @change="item.event"
          v-if="item.elmType == 'date' && (item.type == 'month' || item.type == 'year') && israng === true"
        ></ts-input>
        <ts-date
          v-model="dateVal"
          :title="item.title"
          :title-width="item.width"
          :type="item.type"
          placeholder=""
          @done="item.event"
          v-if="item.elmType == 'date' && item.type != 'month' && item.type != 'year' && israng === true"
        ></ts-date>
        <ts-date
          v-model="postData[item.name]"
          :title="item.title"
          :title-width="item.width"
          :type="item.type"
          placeholder=""
          @done="item.event"
          v-if="item.elmType == 'date' && item.type != 'month' && item.type != 'year' && israng === false"
        ></ts-date>
        <ts-input
          v-model="postData[item.name]"
          :title="item.title"
          :title-width="item.width"
          :type="item.type"
          placeholder=""
          @keyEnter="search"
          v-if="item.elmType == 'text'"
        ></ts-input>
        <ts-select
          :source="item.source"
          v-model="postData[item.name]"
          :title="item.title"
          :title-width="item.width"
          placeholder=""
          @selected="item.event"
          v-if="item.elmType == 'select'"
        ></ts-select>
      </div>
    </div>
    <div class="bi-mod__btn">
      <ts-button style="margin-left:5px;" type="button" icon="iconfont icon-Group-14" status="primary" @click="search">查询</ts-button>
      <ts-button style="margin-left:5px;" type="button" icon="iconfont icon-jiaohu" status="primary" @click="reset">重置</ts-button>
      <ts-button style="margin-left:5px;" type="button" icon="iconfont icon-daochu" status="primary" @click="exportFn">导出</ts-button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'screen',
  props: {
    value: {
      type: [String, Number, Object],
      default: function () {
        return {}
      }
    },
    type: String
  },
  data () {
    return {
      obj: this.value,
      params: this.value.params || {},
      dateVal: '',
      screenArr: [],
      postData: {},
      areaType: [
      ],
      areaVal: '',
      israng: false
    }
  },
  created () {
  },
  mounted () {
    this.screen(this.obj.data, this.obj.dates)
  },
  methods: {
    // 布局渲染
    screen (data, timevalue) {
      let h = ''
      let timetype = 0
      let ndate = this.$utils.timestampToTime() // 限制日期
      let dateRange = 0
      let _dateRange = 0
      let dateName = []
      let dateVal = []
      let type = 'text'
      let titleElm = {}
      let areaLoad = false
      let pages = {}
      let israng = false
      let txt = ''
      let datenamestr = ''
      let screenArr = []
      let yesterday = this.$utils.intervalDate(new Date(), 1)
      let isVal = false
      if (this.params.begin) {
        this.postData.begin = this.params.begin || ''
        this.postData.end = this.params.end || ''
      }
      if (this.params.begin && this.params.end) {
        this.dateVal = this.postData.begin + ' ~ ' + this.postData.end
      }
      for (let i in data) {
        if (data[i].columnType == 'DATE') {
          // 时间是筛选
          let ndarr = timevalue
          let _tit = data[i].title.split(':');
          dateRange++
          dateName.push(data[i].name)
          this.postData[data[i].name] = ''
          datenamestr += data[i].name
          for (let j in ndarr) {
            if (ndarr[j].name == data[i].name) {
              let val = ndarr[j].value.split(' ~ ')[0]
              this.postData[data[i].name] = val
              isVal = true
            }
          }
          if (data[i].range === true) {
            israng = true
          }
        }
      }
      if (datenamestr == 'beginend') {
        israng = true
      }
      this.israng = israng
      for (let i in data) {
        let v = data[i]
        let _d = {}
        if (v.columnType == 'DATE') {
          // 时间
          _dateRange++
          if (_dateRange == 1 && dateRange == 2) {
            txt = v.title
          }
          if (dateRange == _dateRange && israng === true) {
            if (v.dateFormat == 1 && v.dateTime == false) {
              _d.type = 'range'
              if (this.dateVal === '') {
                this.postData.begin = yesterday
                this.postData.end = yesterday
                this.dateVal = this.postData.begin + ' ~ ' + this.postData.end
              }
            } else if(v.dateTime == true) {
              _d.type = 'rangetime'
              if (this.dateVal === '') {
                this.postData.begin = yesterday + ' 00:00:00'
                this.postData.end = yesterday + ' 23:59:59'
                this.dateVal = this.postData.begin + ' ~ ' + this.postData.end
              }
            }
            v.title = txt
            _d.elmType = 'date'
            _d.event = (o) => {
              this.postData.begin = o.s
              this.postData.end = o.e
              this.search()
            }
          } else if (israng === false) {
            let _tit = data[i].title.split(':')
            // if (_tit.length > 1) {
            //   let _btn = _tit[1].split(',')
            //   let _btnarr = data[i].dateButtonValue.split(':')
            //   let _btncodes = _btnarr[0].split(',')
            //   let _btncoder = false
            //   if(_btnarr[1]) {
            //     _btncoder = _btnarr[1].split(',')
            //   }
            //   for(let l in _btn) {
            //   }
            // }
            let ndarr = timevalue
            let nd = ''
            for (let j in ndarr) {
              if (ndarr[j].name == data[i].name) {
                nd = ndarr[j].value;
              }
            }
            let _type = 'date'
            let mon = []
            if (data[i].dateTime == true) {
              ndate = ndate + ' 23:59:59'
              _d.type = 'datetime'
            } else {
              if (data[i].dateFormat == 1) {
                _d.type = 'date'
              } else if(data[i].dateFormat == 2) {
                _d.type = 'month'
                mon = ndate.split('-')
                ndate = mon[0] + '-' + mon[1]
              } else if(data[i].dateFormat == 3) {
                _d.type = 'year'
                mon = ndate.split('-')
                ndate = mon[0]
              }
            }
            if (isVal === true) {
              ndate = this.postData[v.name] || ndate
            }
            this.postData[v.name] = ndate
            this.dateVal = ndate
            if (v.range && (data[i].dateTime == true || data[i].dateFormat == 1)) {
              this.dateVal = this.dateVal + ' ~ ' + this.dateVal
              if (data[i].dateFormat == 1 && data[i].dateTime == false) {
                _d.type = 'range'
              } else if(data[i].dateTime == true) {
                _d.type = 'rangetime'
              }
            }
            _d.elmType = 'date'
            if (_d.type == 'month' && _d.type == 'year' && dateRange == 1) {
              _d.event = (o) => {
                this.postData.begin = o.value
                this.postData.end = o.value
                this.search()
              }
            } else if (dateRange == 1) {
              _d.event = (o) => {
                if (_d.type == 'date' || _d.type == 'datetime') {
                  this.postData.begin = o
                  this.postData.end = o
                } else {
                  this.postData.begin = o.s
                  this.postData.end = o.e
                }
                this.search()
              }
            } else if (_d.type == 'month' && _d.type == 'year' && dateRange == 2) {
              _d.event = (o) => {
                this.postData[v.name] = o.value
                this.search()
              }
            } else if (dateRange == 2) {
              _d.event = (o) => {
                if (_d.type == 'date' || _d.type == 'datetime') {
                  this.postData[v.name] = o
                } else {
                  this.postData[v.name] = o.s
                }
                this.search()
              }
            }
          }
        } else if (v.columnType == 'DATEUNIT') {
          _d.type = 'rangetime'
          _d.elmType = 'date'
          if (this.dateVal === '') {
            this.postData.begin = this.postData.begin || yesterday + ' 00:00:00'
            this.postData.end = this.postData.end || yesterday + ' 23:59:59'
            this.dateVal = this.postData.begin + ' ~ ' + this.postData.end
          }
          _d.event = (o) => {
            this.postData.begin = o.s
            this.postData.end = o.e
            this.search()
          }
        }else if (v.columnType == 'PAGE') {
          pages = {
            str: v.defaultValue,
            name: v.name
          }
        }else if (v.columnType == 'SELECT') {
          _d.elmType = 'select'
          _d.source = {
            url: '/ts-query/api/user/select/config/cfgLoad?configId=' + v.cfgid,
            method: 'get',
            data: {
            },
            page: 'pageNo',
            code: 'value',
            text: 'name',
            value: {
              name: '',
              code: ''
            }
          }
          _d.event = (o) => {
            this.search()
          }
        } else {
          _d.type = 'text'
          if (v.columnType == 'NUMBER') {
            _d.type = 'number'
          }
          if(data[i].name == 'area') {
            areaLoad = true
            _d.elmType = 'area'
            _d.event = (o) => {
              this.postData.area = o.label
              this.search()
            }
          } else {
            _d.elmType = 'text'
          }
        }
        _d.title = v.title
        _d.name = v.name
        titleElm = this.getTitleWidth(v.title)
        _d.width = titleElm.width
        if (v.columnType&&v.columnType !== 'DATE' && v.columnType !== 'DATEUNIT'&&v.name!="DEPT_TYPE" ) {
          this.postData[v.name] = ''
        }
        if (v.name != 'hj') {
          screenArr.push(_d)
        }
      }
      this.screenArr = screenArr
      if (areaLoad === true) {
        this.getArea(pages)
      } else {
        this.$emit('loadSuccess', this.postData, pages)
      }
    },
    // 院区获取
    getArea (pages) {
      const _this = this
      this.$api({
        url: '/ts-query/api/config/hospital/area',
        method: 'get'
      }).then(function (res) {
        // 请求成功
        if (res.success === true) {
          let arr = []
          res.object.forEach((v, i) => {
            let d = {
              name: 'area',
              value: v.scode,
              text: v.shortDesc
            }
            arr.push(d)
            if (Number(i) === 0) {
              _this.areaVal = v.scode
            }
          })
          _this.areaType = arr
          _this.postData.area = _this.areaVal
          _this.$emit('loadSuccess', _this.postData, pages)
        }
      }).catch(function (error) {
          // 请求失败
      })
    },
    // 获取标题长度
    getTitleWidth (text) {
      let elm = null
      let dom = document.createElement('div')
      dom.style.display = 'inline-block'
      dom.style.position = 'fixed'
      dom.style.left = '0px'
      dom.style.top = '0px'
      dom.style.opacity = '0'
      dom.innerHTML = text
      document.getElementsByTagName('body')[0].appendChild(dom)
      elm = dom.getBoundingClientRect()
      dom.remove()
      return elm
    },
    // 日期
    dateBack () {},
    // 查询
    search () {
      setTimeout(() => {
        this.$parent.refresh(this.postData)
      })
    },
    // 重置
    reset () {
      Object.keys(this.postData).forEach((v, i) => {
        this.postData[v] = ''
      })
      setTimeout(() => {
        this.$parent.refresh(this.postData)
      })
    },
    // 导出
    exportFn () {
      const _this = this
      let html = this.$parent.$refs.biModTable.$el.getElementsByClassName('vxe-table--main-wrapper')[0].innerHTML
      let data = JSON.parse(JSON.stringify(this.$parent.postData))
      this.$api({
        url: '/ts-query/api/user/query/table/export/excel',
        method: 'post',
        data: data,
        responseType: 'blob'
      }).then(function (res) {
        // 请求成功
        let blob = res.data
        if(blob.size > 0) {
          let reader = new FileReader()
          reader.readAsDataURL(blob) // 转换为base64，可以直接放入a标签href
          reader.onload = function (e) {
            // 转换完成，创建一个a标签用于下载
            let a = document.createElement('a')
            a.download = new Date().getTime() + '.' + 'xls'
            a.href = e.target.result;
            document.body.appendChild(a)
            a.click()
            a.remove()
          }
        }
      }).catch(function (error) {
          // 请求失败
      })
    }
  },
  watch: {
    value: {
      handler (n, o) {
        this.obj = n
        this.params = n.params
        this.screen(n.data, n.dates)
      },
      deep: true
    }
  }
}
</script>

<style>
  .bi-mod__item{
    width: 25%;
    float: left;
  }
</style>
