<template>
  <div class="content-main-manage">
    <div class="content-main">
     <div class="content-body-wrap">
       <div class="content-body">
         <statistics-list :tabsInitData="tabsInitData" :tabsTitleColor="tabsTitleColor" :unitArr="unitArr" :tabsIcon="tabsIcon" url="metroapi/datarule/summary" ref="statistics"></statistics-list>
          <div class="search-list">
            <div class="search-left">
              <Form class="common-form common-form-list" ref="tableParams" :model="tableParams" inline>
                 <FormItem label="" prop="targetTypeId">
                  <Select v-model="tableParams.targetTypeId" placeholder="指标类型">
                    <Option v-for="item in targetTypeNameList" :value="item.id" :key="item.id">{{ item.value}}</Option>
                  </Select>
                </FormItem>
                <FormItem label="" prop="businessTypeId">
                  <Select v-model="tableParams.businessTypeId" placeholder="业务类型">
                      <Option v-for="item in businessData" :value="item.id" :key="item.id">{{ item.businessTypeName }}</Option>
                    </Select>
                </FormItem>
                 <FormItem label="">
                  <DatePicker type="datetimerange" :value="dateRange" format="yyyy-MM-dd HH:mm:ss" placeholder="更新时间范围" class="common-date-picker date-picker-main" :clearable="false" :editable="false" @on-change="changePicker"></DatePicker>
                </FormItem>
                <FormItem label="" prop="ruleName">
                  <Input placeholder="输入规则名称关键词查询" clearable search v-model="tableParams.ruleName" />
                </FormItem>
                <FormItem label="" prop="field">
                  <Input placeholder="输入字段关键词查询" clearable search v-model="tableParams.field" />
                </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 class="btn-container">
              <Button icon="ios-add" class="common-add-btn" @click="addClick">新增规则</Button>
            </div>
            </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="operationUser">
                  {{row.operationUser}}
                </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>
       </div>
     </div>
    </div>
    <Modal
      v-model="showModal"
      :title="title"
      width="60"
      ref="modalGrag"
      draggable
      reset-drag-position
      @on-visible-change="modalChange"
      :mask-closable="false"
      class-name="common-modal">
      <div>
        <tabs-list :currentStep="currentStep"></tabs-list>
        <div class="modal-content" v-show="currentStep==1">
          <div class="modal-content-top-title">基础信息</div>
          <Form class="common-form" ref="formOption" :model="formOption" :rules="ruleValidate" :label-width="120">
            <FormItem label="规则名称：" prop="ruleName">
              <Input v-model.trim="formOption.ruleName" maxlength="20" show-word-limit />
            </FormItem>
            <FormItem label="指标类型：" prop="targetType">
              <Select v-model="formOption.targetType" placeholder="指标类型" label-in-value @on-change="selectModalBusiness">
                <Option v-for="item in targetTypeNameModalList" :value="item.id" :key="item.id">{{ item.value}}</Option>
              </Select>
            </FormItem>
            <FormItem label="规则描述：" prop="ruleDesc">
              <Input v-model.trim="formOption.ruleDesc" type="textarea" :rows="6" maxlength="100" show-word-limit />
            </FormItem>
          </Form>
        </div>
        <div class="modal-content" v-show="currentStep==2">
          <rule-step-two :businessModalData="businessModalData" :currentObj="formOption" :modalTitle="title" v-if="showModal" ref="ruleStep2" @selectTableChange="selectTableChange"></rule-step-two>
        </div>
        <div class="modal-content" v-show="currentStep==3">
          <rule-step-three :currentObj="formOption" v-if="showModal" ref="ruleStep3"></rule-step-three>
        </div>
        <div class="modal-content" v-show="currentStep==4">
          <rule-step-four :currentObj="formOption" v-if="showModal" ref="ruleStep4"></rule-step-four>
        </div>
      </div>
      <div slot="footer" class="custom-footer">
          <Button type="primary" @click="previousStep" :style="{visibility:currentStep>1 ? 'visible': 'hidden'}">上一步</Button>
          <Button type="primary" @click="nextStep('formOption',1)" v-show="currentStep<4">下一步</Button>
          <Button type="primary" v-show="currentStep==4" @click="saveRule">保存</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 StatisticsList from '../../../components/StatisticsList.vue'
import TabsList from '../../../components/TabsList.vue'
import RuleStepTwo from './QualityRules/RuleStepTwo.vue'
import RuleStepThree from './QualityRules/RuleStepThree.vue'
import RuleStepFour from './QualityRules/RuleStepFour.vue'
const defaultFrom = {ruleName:'',targetType:'',targetName: '',ruleDesc:'',applicationId:'',applicationName: '',equipmentTypeCode:'',field:'',expr: '',dataType:'all',dataValue:null,logicalValueDTOList:[],exprDesc: ''}
export default {
  name: "DataRules",
  components: {
      StatisticsList,TabsList,RuleStepTwo,RuleStepThree,RuleStepFour
    },
  data() {
    return {
      tabsIcon: [
        { imgSrc: require('@/assets/images/dataQuality1.png') },
        { imgSrc: require('@/assets/images/dataQuality2.png') },
        { imgSrc: require('@/assets/images/dataQuality3.png') },
        { imgSrc: require('@/assets/images/dataQuality4.png') },
      ],
      tabsTitleColor:['#45F2FD', '#EBF310', '#54D593', '#FD7545'],
      unitArr: ['条','条','条','条'],
      tabsInitData: [
        { name: '准确性规则', value: 0},
        { name: '及时性规则', value: 0},
        { name: '一致性规则', value: 0},
        { name: '完整性规则', value: 0}
      ],
      loading: true,
      businessData: [],
      businessModalData: [],
      targetTypeNameList: [],
      targetTypeNameModalList: [],
      // targetTypeNameList: [{label:"及时性",value:'及时性'}, {label:"一致性",value:'一致性'}, {label:"准确性",value:'准确性'}, {label:"完整性",value:'完整性'}],
      dateRange: [],
      tableParams: {
        targetTypeId: '',
        businessTypeId: '',
        beginUpdateTime: '',
        endOperateTime: '',
        ruleName: '',
        field: '',
        pageNum: 1,
        pageSize: 10
      },
      tableData: [],
      tableTotal: 0,
      tablePage: 0,
      columns: [
          {
            title: '序号',
            type: 'index',
            align: 'center',
            ellipsis: true,
            tooltip: true
          },
           {
            title: '规则名称',
            key: 'ruleName',
            align: 'center',
            ellipsis: true,
            tooltip: true
          },
          // {
          //   title: '',
          //   // key: 'operationUser',
          //   slot: 'operationUser',
          //   align: 'center',
          //   // ellipsis: true,
          //   // tooltip: true
          // },
          {
            title: '规则描述',
            key: 'ruleDesc',
            align: 'center',
            ellipsis: true,
            tooltip: true
          },
          {
            title: '规则类型',
            key: 'targetName',
            align: 'center',
            ellipsis: true,
            tooltip: true
          },
          {
            title: '应用',
            key: 'applicationName',
            align: 'center',
            ellipsis: true,
            tooltip: true
          },
          {
            title: '应用业务类型',
            key: 'businessTypeName',
            align: 'center',
            ellipsis: true,
            tooltip: true
          },
          {
            title: '字段',
            key: 'field',
            align: 'center',
            ellipsis: true,
            tooltip: true
          },
          {
            title: '计算方法',
            key: 'expr',
            align: 'center',
            ellipsis: true,
            tooltip: true
          },
          {
            title: '更新时间',
            key: 'updateTime',
            align: 'center',
            ellipsis: true,
            tooltip: true
          },
          {
            title: '操作',
            align: 'center',
            slot: 'action',
            width: 120,
          }
      ],   
      showModal: false,
      modalStatus: false,
      title: '新增规则',
      commonTitle: "确认删除",
      activeColor: '#E92E2E',
      activeClass: '',
      modalTitle: '',
      currentStep: 1,
      formOption: {ruleName:'',targetType:'',targetName: '',ruleDesc:'',applicationId:'',applicationName: '',equipmentTypeCode:'',field:'',expr: '',dataType:'all',dataValue: null,logicalValueDTOList:[],exprDesc: ''},
      ruleValidate: {
        ruleName: [{
          required: true,
          message: '请输入规则名称',
          trigger: 'blur'
        }],
        targetType: [{
          required: true,
          type: 'number',
          message: '请选择指标类型',
          trigger: 'change'
        }],
        ruleDesc: [{
          required: true,
          message: '请输入规则描述',
          trigger: 'blur'
        }],
      }, 
      rowObj: {},
    };
  },
  mounted() {
    this.getType()
    this.getTableData()
  },
  methods: {
    changePicker (date) {
      this.tableParams.beginUpdateTime = date[0]
      this.tableParams.endOperateTime = 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/dic/queryDictionary', {name:'指标类型'}).then(res=>{
        if (res.httpCode == 1 ){
          this.targetTypeNameModalList = JSON.parse(JSON.stringify(res.data))
          this.targetTypeNameList = res.data
          this.targetTypeNameList.unshift({ id: '-1', value: '指标类型' })
        } else {
          this.targetTypeNameList = []
        }
      })
      // 业务类型数据
      this.$get('metroapi/businessType/box').then(res=>{
        if (res.httpCode == 1 ){
          this.businessData = res.data
          this.businessData.unshift({ id: '-1', businessTypeName: '业务类型' })
          this.businessModalData = this.businessData
        } else {
          this.businessData = []
          this.businessModalData = []
        }
      })
    },
    // 获取表格数据
    getTableData () {
      let params = JSON.parse(JSON.stringify(this.tableParams))
      params.targetTypeId= params.targetTypeId == '-1'?'':params.targetTypeId
      params.businessTypeId= params.businessTypeId == '-1'?'':params.businessTypeId
      this.loading = true
      this.$get('metroapi/datarule/queryDataRulePage', 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
          }
        })
    },
    searchClick () {
      this.tableParams.pageNum = 1
      this.getTableData()
    },
    resetClick (name) {
     this.dateRange = []
     this.tableParams.beginUpdateTime = ''
     this.tableParams.endOperateTime = ''
     this.$refs[name].resetFields()
     this.tableParams.pageNum = 1
     this.getTableData()
    },   
    addClick () {
      this.formOption = JSON.parse(JSON.stringify(defaultFrom))
      this.currentStep = 1
      this.title = '新增规则'
      this.showModal = true
    },
     editClick (row) {
      this.currentStep = 1
      this.rowObj = row
      // this.rowObj.dataValue = Number(this.rowObj.dataValue)
      this.title = '编辑规则'
      this.showModal = true
      // this.formOption = JSON.parse(JSON.stringify(this.rowObj));
      this.formOption = JSON.parse(JSON.stringify(row));
      this.formOption.equipmentTypeCode = !this.formOption.equipmentTypeCode ? 0 : this.formOption.equipmentTypeCode
    },
    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();
     }
    },
    nextStep (formName,num) {    
    if (this.currentStep ==1) {
       this.$refs[formName].validate((valid) => {
        if (valid) {
          this.currentStep = this.currentStep + num
        } else {
          this.showModal = true
        }
      })
    } else if (this.currentStep ==2) {
      if (this.$refs.ruleStep2.saveValid()) {
        this.currentStep = this.currentStep + num
      }
    } else if (this.currentStep == 3) {
      if (this.$refs.ruleStep3.saveValid()) {
        if (this.formOption.targetName == '及时性（数据采集）') {
          this.formOption.dataValue = this.$refs.ruleStep3.formCustom.timelinArry1[0].dataValue
        } else if (this.formOption.targetName == '及时性（数据入库）') {
          this.formOption.dataValue = this.$refs.ruleStep3.formCustom.timelinArry2[0].dataValue
        } else if (this.formOption.targetName == '准确性') {
          this.formOption.logicalValueDTOList = this.$refs.ruleStep3.formCustomAcc.accuracyArr
          this.formOption.exprDesc = this.$refs.ruleStep3.formCustomAcc.exprDesc
        }
        if (this.$refs.ruleStep3.ruleObj.dataType) {
          this.formOption.dataType = this.$refs.ruleStep3.ruleObj.dataType
        } else {
          if (this.formOption.targetName == '一致性') {
            delete this.formOption.dataType
          }
        }
        this.currentStep = this.currentStep + num
      } 
    } 
    },
    previousStep () {
      this.currentStep--
    },
    saveRule () {
      let params = JSON.parse(JSON.stringify(this.formOption))
      params.equipmentTypeCode = params.equipmentTypeCode== '展示全部字段' ? '': params.equipmentTypeCode
      this.saveData(params)
    },
    commonOk () {
      let params = {
        id: this.rowObj.id
      }
      this.delData(params)
    },
    commonCancel () {
      this.modalStatus = false
    },
    saveData (params) {
      let url = ''
      if (this.title == '新增规则') {
        url = 'metroapi/datarule/addDataRule'
      } else {
        url = 'metroapi/datarule/editDataRule'
      }
      this.$post(url, params).then(res=>{
          if (res.httpCode == 1 ){
            this.$refs.statistics.getStatisList()
            this.showModal = false
            this.$Message.info(res.msg)
            this.getTableData()
          } else {
            this.$Message.info(res.msg)
          }
        })
    },
    // 删除接口
    delData (params) {
      this.$get('metroapi/datarule/delDataRule',params).then(res=>{
        if (res.httpCode == 1 ){
          this.$refs.statistics.getStatisList()
          this.modalStatus = false
          this.$Message.info(res.msg)
          this.getTableData()
        } else {
          this.$Message.info(res.msg)
        }
      })
    },
    selectTableChange (obj) {
      if (obj.text == 'applicationId') {
        this.formOption.applicationId = obj.id
        this.formOption.applicationName = obj.applicationName
        this.formOption.equipmentTypeCode = ''
      } else if (obj.text == 'equipmentTypeCode') {
        this.formOption.equipmentTypeCode = obj.id
      } else {
        this.formOption.field = obj.id
      }
    },
    selectModalBusiness (option) {
      if (option) {
       this.formOption.targetName = option.label
      }
    }
  }
};
</script>
<style scoped lang="stylus">
.content-main-manage {
  overflow: hidden;
  height: calc(100% - 50px);
  width: 100%;
}
.content-main {
  width: 100%;
  height: 100%;
}
.content-body-wrap {
  width: 100%;
  height: 100%;
  background: #06214d;
  padding: 10px;
}
.content-body {
  height: 100%;
  position: relative;
}
.search-list {
  display: flex;
  justify-content: space-between;
  padding: 15px 0;
}
.search-left {
  display: flex;
  align-items: center;
   .ivu-select {
     width: 150px;
     height: 32px;
   }
   .ivu-select-single .ivu-select-selection {
     height: 100%;
   }
    >>> .ivu-input {
     width: 225px;
     height: 32px;
   }
    >>> .ivu-date-picker-editor .ivu-input {
     width: 315px;
   }
    >>> .ivu-input-prefix, >>> .ivu-input-suffix {
     height: 32px;
     line-height: 32px;
   }
}
>>> .common-form-list .ivu-form-item {
 margin-bottom: 0px;
}
.manage-main-center {
  width: 100%;
  height: calc(100% - 150px);
}
.common-table {
  max-height: 100%;
}
>>> .common-table .ivu-table th {
  height: 48px;
 }
 >>> .common-table .ivu-table td {
  height: 47px;
 }
  >>> .common-table .ivu-spin-fix {
   top: 48px;
 }
  >>> .app-table .ivu-spin-fix {
   height: calc(100vh - 355px);
 }
 >>> .common-table .ivu-table-tip {
  background: url('../../../assets/images/noData.png') no-repeat center;
}
>>> .common-table .ivu-table-tip table {
 display: none;
}
>>> .app-table .ivu-table-tip {
   height: calc(100vh - 355px);
 }
.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;
  }
}
.modal-content-top-title {
  font-size: 12px;
  color: #fff;
  padding-left: 8px;
  border-left: 2px solid #0185EA;
  height: 18px;
  line-height: 18px;
  margin-bottom: 20px;
}
.modal-content {
  margin-top: 20px;
}
/* 对话框里的input里的placeholder样式修改 */
/deep/ .ivu-input::-webkit-input-placeholder , /deep/ .ivu-input-number-input::-webkit-input-placeholder{
  color: #718EBD;
}
/deep/ .ivu-input::-moz-placeholder, /deep/ .ivu-input-number-input::-webkit-input-placeholder{   /* Mozilla Firefox 19+ */
  color: #718EBD;
}
/deep/ .ivu-input::-moz-placeholde, /deep/ .ivu-input-number-input::-webkit-input-placeholderr{    /* Mozilla Firefox 4 to 18 */
 color: #718EBD;
}
/deep/ .ivu-input::-ms-input-placeholder, /deep/ .ivu-input-number-input::-webkit-input-placeholder{  /* Internet Explorer 10-11 */
  color: #718EBD;
}
</style>