<template>
  <div class="content-main-manage">
    <div class="search-list">
      <div class="search-left">
        <Form class="common-form common-form-list" ref="tableParams" :model="tableParams" inline>
          <!-- <FormItem label="" prop="lineId">
            <Select v-model="tableParams.lineId" placeholder="来源应用">
              <Option v-for="item in lineTypeData" :value="String(item.id)" :key="item.id">{{ item.lineName }}</Option>
            </Select>
          </FormItem> -->
         <FormItem label="" prop="lineId">
            <Select v-model="tableParams.lineId" placeholder="线路" @on-select="selectLine">
              <Option v-for="item in lineTypeData" :value="String(item.id)" :key="item.id">{{ item.lineName }}</Option>
            </Select>
          </FormItem>
          <FormItem label="" prop="stationId">
            <Select v-model="tableParams.stationId" placeholder="站点">
              <Option v-for="item in stationTypeData" :value="String(item.id)" :key="item.id">{{ item.stationName }}</Option>
            </Select>
          </FormItem>
          <FormItem label="" prop="rankId">
            <Select v-model="tableParams.rankId" placeholder="告警等级">
              <Option v-for="item in alarmLevelData" :value="item.id" :key="item.id">{{ item.name }}</Option>
            </Select>
          </FormItem>
          <FormItem label="">
            <DatePicker type="datetimerange" format="yyyy-MM-dd HH:mm:ss" :value="dateRange" :editable="false" placeholder="过滤时间范围" class="common-date-picker date-picker-main" :clearable="false" @on-change="changePicker"></DatePicker>
          </FormItem>
          <!-- <FormItem label="" prop="equipmentType">
             <Select v-model="tableParams.equipmentType" placeholder="设备类型">
              <Option v-for="item in equipTypeData" :value="(item.id)" :key="item.id">{{ item.name }}</Option>
            </Select>
          </FormItem> -->
          <FormItem label="" prop="name">
            <Input placeholder="输入关键字查询" clearable search v-model="tableParams.name" />
          </FormItem>
          <FormItem label="" >
            <Button type="primary" class="common-btn-search" @click="searchClick">
              <Icon type="ios-search" style="margin-right:4px;font-size: 16px"/> 筛选
            </Button> 
            <Button type="primary" class="common-btn-search" style="margin-left:10px" @click="resetClick('tableParams')">
              <Icon type="ios-search" style="margin-right:4px;font-size: 16px"/> 重置
            </Button>   
          </FormItem>
        </Form>
      </div>
    </div>
     <div class="btn-container">
      <Button icon="ios-add" class="common-add-btn" @click="addClick">新增策略</Button>
    </div>
    <div class="manage-main-center">
      <Table :columns="columns" :data="tableData" class="common-table app-table" no-data-text="" :row-class-name="rowClassName" :loading="loading">
        <template slot="loading">
            <Loading-animation></Loading-animation>
        </template>
        <!-- <template slot-scope="{ row }" slot="lineName">
          <span>{{!row.lineName ? '/' : row.lineName}}</span>
        </template> -->
        <!-- <template slot-scope="{ row }" slot="stationName">
          <span>{{!row.stationName ? '/' : row.stationName}}</span>
        </template> -->
         <template slot-scope="{ row }" slot="action">
           <Tooltip content="编辑" placement="top">
              <i class="iconfont icon-bianji" style="cursor:pointer;color:#64ACFE;fontSize:20px;marginRight:6px" @click="editClick(row)"></i>
           </Tooltip>
           <Tooltip content="删除" placement="top">
              <i class="iconfont icon-shanchu" style="cursor:pointer;color:#E92E2E;fontSize:20px;marginRight:6px" @click="delClick(row)"></i>
           </Tooltip>
        </template>
      </Table>
    </div>
    <div class="common-page">
      <div class="common-page-total">
        共<span>{{tablePage}}</span>页 / <span>{{tableTotal}}</span>条数据
      </div>
      <Page :total="tableTotal" :current="tableParams.pageNum" :page-size="tableParams.pageSize" @on-change="changePage" @on-page-size-change="sizeChange" show-elevator />
    </div>
    <Modal
      v-model="showModal"
      :title="title"
      width="34"
      ref="modalGrag"
      draggable
      reset-drag-position
      @on-visible-change="modalChange"
      :mask-closable="false"
      class-name="common-modal">
      <Form class="common-form" ref="formOption" :model="formOption" :rules="ruleValidate" :label-width="130" inline>
        <FormItem label="过滤策略名称：" prop="filterName" style="width:100%">
          <Input v-model.trim="formOption.filterName" maxlength="20" show-word-limit />  
        </FormItem>
        <FormItem label="来源应用：" prop="appId" style="width:100%" :rules="{type:'number'}">
           <Select v-model="formOption.appId" placeholder="来源应用">
             <Option v-for="item in equipAppModalData" :value="item.id" :key="item.id">{{ item.appName }}</Option>
          </Select>
        </FormItem>
        <FormItem label="所属线路：" prop="lineId" style="width:48%" :rules="{type:'number'}">
          <Select v-model="formOption.lineId" placeholder="线路" @on-change="selectModalLine" label-in-value>
              <Option v-for="item in lineTypeModalData" :value="item.id" :key="item.id">{{ item.lineName }}</Option>
          </Select>
				</FormItem>
				<FormItem label="所属站点：" prop="stationId" style="width:48%" :rules="{type:'number'}">
           <Select v-model="formOption.stationId" placeholder="站点" @on-change="selectModalStation" label-in-value>
            <Option v-for="item in stationTypeModalData" :value="item.id" :key="item.id">{{ item.stationName }}</Option>
          </Select>
        </FormItem>
        <FormItem label="告警等级：" prop="rankId" style="width:100%" :rules="{type:'number'}">
          <Select v-model="formOption.rankId" placeholder="告警等级">
             <Option v-for="item in alarmLevelModalData" :value="item.id" :key="item.id">{{ item.name }}</Option>
          </Select>
        </FormItem>
         <FormItem label="过滤时间：" prop="dates" style="width:100%">
          <DatePicker type="datetimerange" :value="formOption.dates" format="yyyy-MM-dd HH:mm:ss" placeholder="过滤时间范围" style="width:100%" class="common-date-picker date-picker-main" :clearable="false" :editable="false" @on-change="changeModalPicker"></DatePicker>
        </FormItem>
			</Form>
      <div slot="footer">
          <Button @click="modalCancel">取消</Button>
          <Button type="primary" @click="modalOk('formOption')">确定</Button>
        </div>
    </Modal>
    <Modal
      v-model="modalStatus"
      :title="commonTitle"
      width="30"
      ref="modalGrag"
      draggable
      reset-drag-position
      :mask-closable="false"
      class-name="common-modal">
      <Icon type="ios-information-circle" :style="{ color: activeColor}" class="modal-icon"></Icon>
      <span class="modal-text">{{modalTitle}}</span>
      <div slot="footer">
          <Button @click="commonCancel">取消</Button>
          <Button type="primary" @click="commonOk">确定</Button>
        </div>
    </Modal>
  </div>
</template>
<script>
import moment from "moment"
const defaultFrom = {filterName: '',lineId: '',stationId: '',appId:'',rankId: '',filterBeginTime: '',filterEndTime: '',dates:[],enabled: 0}
export default {
  name: "AlarmFilterConfig",
  components:{
  },
  data() {
    return {
       alarmParams: {
        keywords: '',
        enabled: 1,
        beginDate: '',
        endDate: '',
        pageNum: 1,
        pageSize: 10
      },
      applicationParams: {
        level: '',
        lineId: '',
        stationId: '',
        equipmentCheck: '',
        instrumentCheck: '',
        pageNum: 1,
        pageSize: 9999
      },
      appParams: {
        applicationId: '',
        equipmentTypeId: '',
        keywords: '',
        pageNum: 1,
        pageSize: 9999
      },
      loading: true,
      dateRange: [],
      tableParams: {
        lineId: '',
        stationId: '',
        keywords: '',
        applicationId:'',
        equipmentTypeId: '',
        rankId: '',
        filterBeginTime: '',
        filterEndTime: '',
        name: '',
        pageNum: 1,
        pageSize: 10
      },
      tableData: [],
      tableTotal: 0,
      tablePage: 0,
      rowObj: {},
      lineTypeData: [],
      stationTypeData: [],
      lineTypeModalData: [],
      stationTypeModalData: [],
      alarmLevelData: [],
      alarmLevelModalData: [],
      lineTypeData: [],
      stationTypeData: [],
      equipTypeData: [],
      equipTypeModalData: [],
      equipAppModalData: [],
      columns: [
          {
            title: '过滤策略名称',
            key: 'filterName',
            align: 'center',
            ellipsis: true,
            tooltip: true
          },
          {
            title: '来源应用',
            key: 'appName',
            align: 'center',
            ellipsis: true,
            tooltip: true
          }, 
          {
            title: '线路',
            key: 'lineName',
            // width: 160,
            ellipsis: true,
            tooltip: true,
            align: 'center',
            // render: (h, params) => {
            //     let lineName = ''
            //     if (params.row.lineName && params.row.lineName.length > 10) {
            //       lineName = params.row.lineName.substring(0, 10) + "...";
            //     } else {
            //       lineName = params.row.lineName
            //     }
            //     return h('div', [
            //   　　　　h('Tooltip', {
            //   　　　　props: { placement: 'bottom', transfer: true,disabled:params.row.lineName.length<=10,}
            //   　　　　}, [
            //   　　　　h('span', {
            //   　　　　　　style: {
            //   　　　　　　　　overflow: 'hidden',
            //   　　　　　　　　textOverflow: 'ellipsis',
            //   　　　　　　　　whiteSpace: 'nowrap',
            //   　　　　　　},
            //   　　　　　　}, lineName),
            //   　　　　　　h('span', {
            //   　　　　　　　　slot: 'content',
            //   　　　　　　　　style: { whiteSpace: 'normal', wordBreak: 'break-all' }
            //   　　　　　　},params.row.lineName)
            //   　　　　])
            //   　　])
            //   }
           },
           {
            title: '站点',
            ellipsis: true,
            tooltip: true,
            key: 'stationName',
            align: 'center',
            // render: (h, params) => {
            //   this.$set(this.columns[3], 'tooltip', true)
            //   return h('span', params.row.stationName)
            // },
            // tooltip: true,
          },
          {
            title: '告警等级',
            key: 'rankName',
            align: 'center',
            ellipsis: true,
            tooltip: true
          },
          {
            title: '开始时间',
            key: 'filterBeginTime',
            align: 'center',
            ellipsis: true,
            tooltip: true
          },
          {
            title: '结束时间',
            key: 'filterEndTime',
            align: 'center',
            ellipsis: true,
            tooltip: true
          },
          {
          title: '是否启用',
          key: 'enabled',
          align: 'center',
          width: 100,
          render: (h, params) => {
            return h('div', [                             
              h('i-switch', {
                props: { value: params.row.enabled,'true-color': '#57C44F', trueValue:1,falseValue: 0
                },
                nativeOn:{
                    "mousedown":(event)=>{ // 监听组件原生事件mousedown,此事件在click之前触发
                      this.rowObj =  params.row
                      if (params.row.enabled == 1) {this.commonTitle = '确认关闭'
                        this.activeColor = '#E92E2E'
                        this.activeClass = 'icon-guanbi'
                        this.modalTitle = '可能影响新数据判断结果。'
                        this.modalStatus = true
                      } else {
                        this.commonTitle = '确认启用'
                        this.activeColor = '#57C44F'
                        this.activeClass = 'icon-qiyong'
                        this.modalTitle = '当前时间点后所有告警信息，将使用策略自动判定。'
                        this.modalStatus = true
                      }
                    },
                  }
                }),
              ])
            }
          },
          {
          title: '操作',
          align: 'center',
          slot: 'action',
          width: 80,
        }
      ],
      showModal: false,
      modalStatus: false,
      title: '新增策略',
      commonTitle: "确认删除",
      activeColor: '#E92E2E',
      activeClass: '',
      modalTitle: '',
      dateModalRange: [],
      formOption: {filterName: '',lineId: '',stationId: '',appId:'',rankId: '',filterBeginTime: '',filterEndTime: '',dates:[],enabled: 0},
      ruleValidate: {
        filterName: [{
          required: true,
          message: '请输入过滤策略名称',
          trigger: 'blur'
        }],
        dates: [{
            type: "array", required: true, message: '请选择过滤时间',
            // fields: {
            //   0: {type: 'string', required: true, message: '过滤时间'},
            //   1: {type: 'string', required: true, message: '过滤时间'}
            // }
        }]
      },
    };
  },
  mounted() {
    this.getType()
  },
  methods: {
    go (){
      // this.$router.push({path:'//ApplicationManage'})
      // this.$router.push({path:'/MainPage/ApplicationManage/2'})
      this.$router.push({ name: 'ApplicationManage', params: { type:2 }}) // -> /home/123
    },
    changePicker (date) {
      this.tableParams.filterBeginTime = date[0]
      this.tableParams.filterEndTime = date[1]
    },
    changeModalPicker (date) {
      this.formOption.dates = date
      this.formOption.filterBeginTime = date[0]
      this.formOption.filterEndTime = date[1]
    },
    rowClassName(row, index) {
      if (index % 2 == 0) {
        return "ivu-table-stripe-even";
      } else {
        return "ivu-table-stripe-odd";
      }
    },
    // 分页
    changePage (val) {
      this.tableParams.pageNum = val
      this.getTableData()
    },
    //跳转
    sizeChange (val) {
      this.tableParams.pageSize = val
      this.getTableData()
    },
    getType  () {
      //获取所属线路
      this.$get('metroapi/lineStation/queryLine', {lineName:''}).then(res=>{
        if (res.httpCode == 1 ){
          this.lineTypeModalData = JSON.parse(JSON.stringify(res.data))
          this.lineTypeData = res.data
          this.lineTypeData.unshift({ id: '-1', lineName: '线路' })
          this.getStationData ('-1')
        } else {
          this.lineTypeData = []
          this.lineTypeModalData = []
        }
      })
      // 获取归属应用
      this.$get('metroapi/application/info/list', this.applicationParams).then(res=>{
        if (res.httpCode == 1 ){
          this.equipAppModalData = res.data.data
        } else {
          this.equipAppModalData = []
        }
      })
      // 告警等级
      this.$get('metroapi/alert/rank/list', this.alarmParams).then(res=>{
        if (res.httpCode == 1 ){
          this.alarmLevelModalData = JSON.parse(JSON.stringify(res.data.data))
          this.alarmLevelData = res.data.data
          this.alarmLevelData.unshift({ id: '-1', name: '告警等级' })
        } else {
          this.alarmLevelData = []
          this.alarmLevelModalData = []
        }
      })
    },
    selectLine (val) {
      // 获取站点类型
      this.tableParams.stationId = ''
      this.tableParams.lineId = val.value
      if (this.tableParams.lineId) {
        this.getStationData(val.value)
      }
    },
    // 获取所属站点
    getStationData (lineId) {
      if(lineId == -1) {
        this.stationTypeData = [{ id: '-1', stationName: '站点' }]
      } else {
        this.$get('metroapi/lineStation/queryStationByLineId', {lineId:lineId}).then(res=>{
          if (res.httpCode == 1 ){
            this.stationTypeModalData = JSON.parse(JSON.stringify(res.data))
            this.stationTypeData = res.data
            this.stationTypeData.unshift({ id: '-1', stationName: '站点' })
          }
        })
      }
    },
    // 获取表格数据
    getTableData () {
      let params = JSON.parse(JSON.stringify(this.tableParams))
      params.lineId = params.lineId == -1 ? '':params.lineId
      params.stationId = params.stationId == -1 ?'':params.stationId
      params.rankId = params.rankId == '-1' ?'':params.rankId
      this.loading = true
      this.$get('metroapi/alertfilter/queryStrategyFilterPage', params).then(res=>{
        this.loading = false
          if (res.httpCode == 1 ){
            this.tableData = res.data.data
            this.tableTotal = res.data.count
            if (res.data.data.length==0) {
              this.tablePage = 0
            } else {
              this.tablePage = res.data.count<= 10 ? 1: Math.ceil(res.data.count/this.tableParams.pageSize)
            }
            if (res.data.data.length==0 && this.tableParams.pageNum>1) {
              this.tableParams.pageNum--
              return this.getTableData()
            }
          } else {
            this.tableData = []
            this.tableTotal = 0
          }
        })
    },
    selectModalLine (val) {
      this.formOption.stationId = ''
      if (val) {
        this.getStationData(val.value)
      }
    },
    selectModalStation (val) {
      if (val) {
       this.formOption.stationId =val.value
      }
    },
    // selectModalApp (val) {
    //   this.appParams.applicationId = val
    //   if (val) {
    //     this.getAddEquipType( this.appParams)
    //   }
    // },
    // 获取设备类型 
    getAddEquipType (params) {
      this.$get('metroapi/application/equipmentTypeInfo', params).then(res=>{
        if (res.httpCode == 1 ){
          this.equipTypeModalData = res.data.data
        } else {
          this.equipTypeModalData = []
        }
      })
    },
    searchClick () {
      this.tableParams.pageNum = 1
      this.getTableData()
      // this.$router.push({ path: '/MainPage/ApplicationManage',  query: {deptName: "2"}})
    },
    resetClick (name) {
     this.dateRange = []
     this.tableParams.filterBeginTime = ''
     this.tableParams.filterEndTime = ''
     this.stationTypeData = [{ id: -1, stationName: '站点' }]
     this.$refs[name].resetFields()
     this.tableParams.pageNum = 1
     this.getTableData()
    },   
    changeMoldaPicker (val) {
     this.formOption.useDate = val
    },
    addClick () {
      this.formOption = JSON.parse(JSON.stringify(defaultFrom))
      this.title = '新增策略'
      this.showModal = true
    },
    editClick (row) {
      this.rowObj = row
      this.formOption = JSON.parse(JSON.stringify(row));
      this.formOption.dates = [row.filterBeginTime,row.filterEndTime]
      this.getStationData(this.formOption.lineId)
      this.appParams.applicationId = this.formOption.appId
      this.getAddEquipType(this.appParams)
      this.title = '编辑策略'
      this.showModal = true
    },
    delClick (row) {
      this.rowObj = row
      this.commonTitle = '确认删除'
      this.activeColor = '#E92E2E'
      this.activeClass = ''
      this.modalTitle = '删除的同时将解绑所有运营数据，且数据不可恢复，请慎重操作。'
      this.modalStatus = true
    },
    modalChange (modalStatus) {
     if (!modalStatus) {
      this.$refs.formOption.resetFields();
      this.stationTypeModalData = []
     }
    },
    modalOk (formName) {
      let params = JSON.parse(JSON.stringify(this.formOption)) //把对象中的数据给了某个变量，改变一个对象的值，另一个对象也变化的解决方法
      // params.lineId = params.lineId == '-1' ? '':params.lineId
      // params.stationId = params.stationId == '-1' ? '':params.stationId
      let url = ''
      if (this.title == '新增策略') {
        url = 'metroapi/alertfilter/addStrategyFilter'
      } else {
        url = 'metroapi/alertfilter/editStrategyFilter'
      }
      this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$post(url, params).then(res=>{
              if (res.httpCode == 1 ){
                this.showModal = false
                this.$Message.info(res.msg)
                this.getTableData()
              } else {
                this.$Message.info(res.msg)
              }
            })
          } else {
            this.showModal = true
          }
       })
    },
    modalCancel () {
      this.showModal = false
    },
    commonOk () {
       if (this.commonTitle == '确认启用') {
        let params = {
          strategyFilterId: this.rowObj.id,
          enabled: 1
        }
        this.getSwitchStatus(params)
      } else if (this.commonTitle == '确认关闭') {
        let params = {
          strategyFilterId: this.rowObj.id,
          enabled:0
        }
        this.getSwitchStatus(params)
      } else {
        let params = {
          strategyFilterId: this.rowObj.id
        }
        this.delData(params)
      }
    },
    commonCancel () {
      this.modalStatus = false
    },
    // 启用 关闭/接口
    getSwitchStatus (params) {
      this.$get('metroapi/alertfilter/enableStrategyFilter',params).then(res=>{
        if (res.httpCode == 1 ){
          if (params.enabled == 0) {
            this.rowObj.enabled = 0
          } else {
            this.rowObj.enabled = 1
          }
          this.modalStatus = false
        } else {
          this.rowObj.enabled = 0
          this.$Message.info(res.msg)
        }
      })
    },    
    // 删除接口
    delData (params) {
      this.$get('metroapi/alertfilter/delStrategyFilter',params).then(res=>{
        if (res.httpCode == 1 ){
          this.modalStatus = false
          this.$Message.info(res.msg)
          this.getTableData()
        } else {
          this.$Message.info(res.msg)
        }
      })
    },
  }
};
</script>
<style scoped lang="stylus">
.content-main-manage {
  position: relative;
  height: 100%;
}
.search-list {
  display: flex;
  padding: 10px 0;
}
.search-left {
  display: flex;
  align-items: center;
   .ivu-select {
     width: 155px;
     height: 32px;
   }
   .ivu-select-single .ivu-select-selection {
     height: 100%;
   }
   >>> .ivu-input {
     width: 160px;
     height: 32px;
   }
    >>> .common-date-picker .ivu-input {
    width: 332px;
   }
   >>> .ivu-input-prefix, >>> .ivu-input-suffix {
     height: 32px;
     line-height: 32px;
   }
   >>> .ivu-input-icon {
     height: 32px;
     line-height: 32px;
   }
   >>> .date-picker-main .ivu-date-picker-header {
    border-bottom: 0.0052083333rem solid #204384;
 }
}
.btn-container {
  display: flex;
  justify-content: flex-end;
  padding-bottom: 10px;
}
.common-form {
  display: flex;
  flex-wrap: wrap;
}
>>> .common-form-list .ivu-form-item {
  margin-bottom: 10px;
}
.manage-main-center {
  width: 100%;
  height: calc(100% - 150px);
}
.common-table {
  height: 100%;
  // max-height: 100%;
}
>>> .common-table .ivu-table-body{
  height: calc(100% - 49px);
  overflow: hidden;
  overflow-y: auto;
}
>>> .common-table .ivu-table th {
  height: 49px;
 }
 >>> .common-table .ivu-table td {
  height: 48.5px;
 }
  >>> .common-table .ivu-spin-fix {
   top: 49px;
 }
  >>> .app-table .ivu-spin-fix {
   height: calc(100vh - 375px);
 }
 >>> .ivu-table-tip {
  background: url('../../../assets/images/noData.png') no-repeat center;
}
>>> .app-table .ivu-table-tip {
  height: calc(100vh - 375px);
 }
 >>> .common-table .ivu-table-tip table {
 display: none;
}
 >>> .modal-table {
   overflow: auto !important;
 }
 >>> .modal-table .ivu-spin-fix {
   height: 200px;
 }
  >>> .modal-table .ivu-table-tip {
   height: 200px;
 }
.common-page {
  margin-top: 15px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  position: absolute;
  bottom: 0;
  right: 0;
}
.common-page-total {
  color: #fff;
  padding-right: 10px;
  font-size: 14px;
  span {
    color #409EFF;
  }
}
/deep/ .ivu-input::-webkit-input-placeholder{
  color: #718EBD;
}
/deep/ .ivu-input::-moz-placeholder{   /* Mozilla Firefox 19+ */
  color: #718EBD;
}
/deep/ .ivu-input::-moz-placeholder{    /* Mozilla Firefox 4 to 18 */
  color: #718EBD;
}
/deep/ .ivu-input::-ms-input-placeholder{  /* Internet Explorer 10-11 */
  color: #718EBD;
}
</style>