<template>
  <div class="content-main common-scroll">
    <div class="content-body">
      <Row :gutter="8" style="width:100%;height:100%">
        <i-col span="24" style="height:100%">
          <div class="right-main">
            <div class="manage-main-top">
              <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" no-data-text="" :row-class-name="rowClassName" :loading="loading">
                <template slot="loading">
                    <Loading-animation></Loading-animation>
                </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>
                </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" show-elevator />
            </div>
          </div>
        </i-col>
      </Row>
    </div>
     <Modal
      v-model="showModal"
      :title="title"
      width="40"
      ref="modalGrag"
      draggable
      reset-drag-position
      :mask-closable="false"
      @on-visible-change="modalChange"
      class-name="common-modal">
       <Form class="common-form" ref="formOption" :model="formOption" :rules="ruleValidate" :label-width="130" label-position="left">
        <FormItem label="归属设备类型：" prop="equipmentTypeId">
           <Select v-model="formOption.equipmentTypeId" placeholder="设备类型">
              <Option v-for="item in equipTypeData" :value="item.id" :key="item.id">{{ item.name }}</Option>
          </Select>
        </FormItem>
			</Form>
      <div class="sub-add" v-show="title == '新增监测模型'">
          <span>点击"+"添加新指标</span>
          <i class="iconfont icon-tianjia" style="cursor:pointer;color:#43B843;padding-left:10px" @click="handleAdd('formDynamic')"></i>
        </div>
      <Form ref="formDynamic" :model="formCustom" :label-width="0" class="common-modal-bot">
        <Row class="strategy-form-header">
          <Col span="3" class="row-first">序号</Col>
          <Col span="12">设备指标名称</Col>
          <Col span="8">对应字段</Col>
          <Col span="1" class="row-last"></Col>
        </Row>
        <div class="strategy-form-scroll common-scroll" v-if="showModal">
          <div class="strategy-form">
              <Row v-for="(item, index) in formCustom.targetInfoList" :key="index">
              <Col span="3" :class="{'row-first': index == 0}" class="row-first-es">{{index + 1}}</Col>
              <Col span="12" :class="{'row-first': index == 0}" class="row-input">
                <FormItem
                  :prop="'targetInfoList.'+index+'.targetName'" :rules="{required: true,message: '请输入设备指标名称',trigger: 'blur'}">
                 <Input v-model.trim="item.targetName" placeholder="设备指标名称" maxlength="20" show-word-limit />
                </FormItem>
              </Col>
              <Col span="8" :class="{'row-first': index == 0}" class="row-input">
                 <FormItem
                  :prop="'targetInfoList.'+index+'.targetCode'" :rules="{required: true,message: '请输入字段名称',trigger: 'blur'}">
                 <Input v-model.trim="item.targetCode" placeholder="字段名称"></Input>
                </FormItem>
              </Col>
              <Col span="1" class="ivu-col-btn">
               <i class="iconfont icon-shanchu ivu-col-del" style="cursor:pointer; color:#BC2020;padding-left:10px" @click="handleRemove(index,item.id)"></i>
              </Col>
            </Row>
          </div>
        </div>
      </Form>
      <div slot="footer">
          <Button @click="modalCancel">取消</Button>
          <Button type="primary" @click="modalOk('formOption')">确定</Button>
        </div>
    </Modal>
</div>
</template>
<script>
const defaultFrom = {equipmentTypeId: ''}
import _ from 'lodash'
export default {
  name: "ModelConfig",
  components:{
  },
  data() {
    return {
      tableTotal: 0,
      tablePage: 0,
      tableParams: {
        equipmentTypeId: '',
        applicationId: '',
        keywords: '',
        pageNum: 1,
        pageSize: 10
      },
      loading: true,
      tableData: [],
      columns: [
        {
          title: '设备类型名称',
          key: 'equipmentTypeName',
          align: 'center',
          ellipsis: true,
          tooltip: true
        },
        {
          title: '模型监测指标',
          key: 'targetCount',
          align: 'center',
          ellipsis: true,
          tooltip: true
        },
        {
          title: '操作',
          align: 'center',
          slot: 'action',
          width: 120
        }
      ],
      rowObj: {},
      formOption: {equipmentTypeId: ''},
      ruleValidate: {
        equipmentTypeId: [{
          required: true,
          type: 'number',
          message: '请选择归属设备类型',
          trigger: 'change'
        }],
      },
    equipTypeData: [],
    showModal: false,
    title: '新增监测模型',
    equipTypeData: [],
    formCustom: {
        targetInfoList: [
          {
            targetName: '',
            targetCode: '',
            id: null,
          },
        ],
      },
    };
  },
  mounted() {
    this.getType() 
  },
  methods: {
    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()
    },
    getTableData () {
      this.loading = true
      this.$get('metroapi/target/queryTargetPage', this.tableParams).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
          }
        })
    },
    getType  () {
      // 获取设备类型
      this.$get('metroapi/equipment/queryEquipmentType', {name:''}).then(res=>{
        if (res.httpCode == 1 ){
          this.equipTypeData = res.data
        } else {
          this.equipTypeData = []
        }
      })
    },
    addClick () {
      this.formCustom.targetInfoList= [
        {
          targetName: '',
          targetCode: '',
          id: null
        },
      ],      
      this.title = '新增监测模型'
      this.formOption = JSON.parse(JSON.stringify(defaultFrom))
      this.showModal = true
    },
    editClick (row) {
      this.getstrategyData(row.equipmentTypeId)
      this.rowObj = row
      this.formOption = JSON.parse(JSON.stringify(row))
      this.title = '编辑监测模型'
      this.$nextTick(()=> {
        this.showModal = true
      })
    },
    getstrategyData (equipmentTypeId) {
      this.$get('metroapi/target/queryTargetByEquipmentType', {equipmentTypeId:equipmentTypeId}).then(res=>{
        if (res.httpCode == 1 ){
          this.formCustom.targetInfoList = res.data
        } else {
          this.$Message.info(res.msg)
        }
      })
    },
    modalChange (modalStatus) {
     if (!modalStatus) {
      this.$refs.formOption.resetFields();
      this.$refs.formDynamic.resetFields();
     }
    },
    modalDetailChange (val) {
     	if (!val) {
        this.detailParams.pageNum = 1
        document.querySelector(".rolling-detail-table .ivu-table-body").scrollTo(0, 0)
      }
    },
    modalOk () {
      let params = Object.assign({}, this.formOption, this.formCustom); // 合并对象 注意目标对象自身也会改变。假设目标对象{}是之前里的对象，他的值跟obj一样
      this.$nextTick(()=> {
        // 多个form表单验证
        const p1 = new Promise((resolve,reject)=>{
        this.$refs['formOption'].validate(valid=>{
                if(valid) resolve()
            })
        })
        const p2 = new Promise((resolve,reject)=>{
            this.$refs['formDynamic'].validate(valid=>{
                if(valid) resolve()
            })
        })
        Promise.all([p1,p2]).then(()=>{
          let canSave = true;
          let arr = this.formCustom.targetInfoList
          for (var i = 0; i < arr.length; i++) {
              for (var j = i + 1; j < arr.length; j++) {
                  if (arr[i].targetName == arr[j].targetName) 
                  { 
                    canSave = false; 
                    break;
                  }
              }
          }
          if(canSave) {
            this.saveStrategyData(params)
          } else {
            this.$Message['error']({
              background: true,
              content: '请勿设置重复设备指标名称'
            });
          }
        })
      })
    },
    saveStrategyData (params) {
      let url = ''
      if (this.title == '新增监测模型') {
        url = 'metroapi/target/addTarget'  
        if (this.formCustom.targetInfoList.length == 0) {
          this.$Message['error']({
            background: true,
            content: '指标不能为空'
          });
          return;
        }
      } else {
        url = 'metroapi/target/editTarget'
      }
      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)
          }
        })
    },
    modalCancel () {
      this.showModal = false
    },
    handleAdd(name) {
      this.$nextTick(()=> {
        this.$refs[name].validate((valid) => {
        if (valid) { 
          this.formCustom.targetInfoList.push({
            targetName: '',
            targetCode: '',
            id: null
          })
        }
       });
      }) 
    },
    handleRemove(i,id) {
      if (this.title == '新增监测模型') {
       this.formCustom.targetInfoList.splice(i,1)
      } else {
        this.$get('metroapi/target/delTarget', {targetId:id}).then(res=>{
        if ( res.httpCode == 1 ){
            this.formCustom.targetInfoList.splice(i,1)
            this.$Message.info(res.msg)
          } else {
            this.$Message.info(res.msg)
          }
        })
      }
    },
  }
};
</script>
<style scoped lang="stylus">
.content-main {
  width: 100%;
  height: calc(100% - 50px);
  overflow: hidden;
}
.common-search {
  width: 100%;
}
>>> .common-search .ivu-input {
  background-color: #06214D;
  border: 1px solid #2355A6;
  border-radius: 15px;
  color: #fff;
  height: 32px;
}
>>> .common-search .ivu-input:focus {
    border-color: #0185ea;
}
.content-body {
  width: 100%;
  height: 100%;
  background: #06214D;
}
.station-tree {
  height: 100%;
  padding: 10px;
}
.station-tree-body {
  border: 1px solid #204384;
  height: 100%;
  padding: 10px;
}
.station-tree-center {
  height: calc(100% - 32px);
  padding-top: 10px;
  // display: flex;
}
.station-tree-left {
  height: 100%;
  overflow: auto;
}
.station-tree-left-notree {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  fon-size: 14px;
}
.right-main {
  height: 100%;
  padding: 10px 0;
  position: relative;
  // padding: 16px;
}
.manage-main-top {
  padding: 12px 0;
  display: flex;
  justify-content: flex-end;
}
.manage-main-center {
  width: 100%;
  height: calc(100% - 100px);
}
.common-table {
  max-height: 100%;
}
>>> .common-table .ivu-table th {
  height: 54px;
 }
 >>> .common-table .ivu-table td {
  height: 54px;
 }
>>> .common-table .ivu-spin-fix {
  top: 54px;
  height: calc(100vh - 350px);
}
>>> .common-table .ivu-table-tip {
  background: url('../../../assets/images/noData.png') no-repeat center;
  height: calc(100vh - 350px);
}
>>> .common-table .ivu-table-tip table {
 display: none;
}
.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;
  }
}

>>> .sub-add {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  font-size: 12PX;
  color: #FFFFFF;
}
>>> .common-modal-bot {
  margin-bottom: 15px;
}
>>> .modal-content-item-value .ivu-tooltip {
  width: 100%;
}
>>> .modal-content-item-value .ivu-tooltip-rel {
  overflow: hidden;
  text-overflow:ellipsis; 
  white-space: nowrap;
}
>>> .strategy-form-scroll {
  max-height: 360px;
  overflow: hidden;
  overflow-y: auto;  
}
>>> .strategy-form {
margin-bottom: 20px;
}
>>> .strategy-form .ivu-col{
  color: #2B8EE2;
  font-size: 14PX;
}
>>> .row-first-es {
  border-left: 1px solid #21437B;
  border-bottom: 1px solid #21437B;
  border-right: 1px solid #21437B;
  display: flex;
  align-items: center;
  justify-content: center;
  // background: #13305F;
}
>>> .strategy-form-header {
  color: #2B8EE2;
  font-size: 14PX;
  display: flex;
  align-items: center;
  height: 55PX;
  .ivu-col {
    border-top: 1px solid #21437B;
    border-right: 1px solid #21437B;
    height: 100%;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #13305F;
  }
  .row-first {
    border-left: 1px solid #21437B;
  }
  .row-last {
    background: none;
    border: none;
  }
}
>>> .strategy-form .row-first{
  border-top: 1px solid #21437B;
}
 >>> .strategy-form .row-first-es {
     background: #13305F;
  }
>>> .strategy-form .ivu-form-item{
  height: 100%;
  margin-bottom: 0;
  width: 90%;
}

>>> .strategy-form .row-es-text {
  border-left: none;
  border-bottom: 1px solid #21437B;
  border-right: 1px solid #21437B;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #13305F;
}
>>> .row-select .ivu-form-item {
  height: 100%;
  border-right: 1px solid #21437B;
  border-bottom: 1px solid #21437B;
   .ivu-form-item-content {
    padding: 10px 5px;
  }
}
>>> .row-input {
  border-bottom: 1px solid #21437B;
  border-right: 1px solid #21437B;
  display: flex;
  align-items: center;
  justify-content: center;
  .ivu-input-wrapper{
   margin: 10px 0;
 }
}
>>> .strategy-form .row-es-last {
  border-right: 1px solid #21437B;
  border-bottom: 1px solid #21437B;
  height: 100%;
  // display: flex;
  // justify-content: space-around;
  // align-items: center;
  .row-es-last-text {
    font-size: 14PX;
    margin-right: 5px;
    display: inline-block;
    width: 42px;
  }
  .ivu-form-item  {
    // display: flex;
    // flex: 1;
    width: 100%;
  }
   .ivu-form-item-content {
    // display: flex;
    padding: 10px 5px;
    width: 100%;
  }
}
>>> .ivu-col-del {
  cursor:pointer;
  color:#BC2020;
  padding-left:10px;
}
>>> .strategy-form .ivu-col-btn {
  display: flex;
  align-items: center;
  border-top: none;
  border-bottom: none;
}
>>> .strategy-form .ivu-form-item-error-tip {
 padding-left: 6px;
}
</style>