// 开始节点配置界面
/* eslint-disable vue/no-side-effects-in-computed-properties */
<template>
  <div class="InformationBlock">
    <div  class="content">
      <div :class="`form_content rule_content`">
        <div  class="form">
          <p >
            <span class="label">优先级:</span>
            <Input type="text" :disabled="readOnly" v-model="configData.priority" :regx="/^[0-9]*$/"   />
          </p>
          <p v-if="moduleType === 1">
            <span class="label"><i class="requireStyle">*</i>单据类型:</span>
            <DropDownSelectFilter
              :disabled="readOnly"
              v-bind="tableConfig.props"
              v-on="tableConfig.event"
            >
            </DropDownSelectFilter>
          </p>
          <p v-if="moduleType === 1">
            <span class="label">查询索引:</span>
            <DropDownSelectFilter
              :disabled="readOnly"
              v-bind="indexQuery.props"
              v-on="indexQuery.event"
            >
            </DropDownSelectFilter>
          </p>
          <p v-if="moduleType === 1">
            <span class="label">触发按钮:</span>
            <Select v-model="configData.triggerBt" :disabled="readOnly" multiple @on-change="triggerBtChange">
              <Option v-for="(item,index) in triggerButtons" :key="index" :value="item.ID">{{item.Label}}</Option>
            </Select>
          </p>
          <p v-if="moduleType === 1">
            <span class="label">可见按钮:</span>
            <Select v-model="configData.visibleBt" :disabled="readOnly" multiple @on-change="visibleBtChange">
              <Option v-for="(item,index) in visibleButtons" :key="index" :value="item.ID">{{item.Label}}</Option>
            </Select>
          </p>
          
        </div>
        <div  class="rule">
          <p class="title">
            <span>配置规则</span>
            <span @click="addRule" v-if="!readOnly">添加规则</span>
          </p>
          <div class="form" v-if="configData.ruleList.length >= 2">
            <p >
              <span class="label">规则并行条件:</span>
              <Select v-model="configData.conditionType" >
                <Option :value="0" :key="0">且</Option>
                <Option :value="1" :key="1">或</Option>
              </Select>
            </p>
          </div>
          <div class="ruleContent" v-if="configData.ruleList.length > 0">
            <RuleConfigurationComponent
              v-for="(rule,index) in configData.ruleList"
              v-bind:key="Math.random()"
              :data="rule"
              :index="index"
              :TABLE_ID="[{ID:configData.businessType,Label:configData.businessTypeName}]"
              :readOnly="readOnly"
            >
            <span slot="delete" class="deleteIcon" @click.stop="delectRule(index)" v-if="!readOnly">
              <i class="iconfont iconbj_delete"></i>
            </span>
            </RuleConfigurationComponent>
          </div>
        </div>
      </div>
      
    </div>
    <p>
      <Button type="fcdefault" @click="closeDrawer">取消</Button>
      <Button type="primary" @click="saveConfig" v-if="!readOnly">确定</Button>
    </p>
  </div>
</template>
<script>
import ProcessNodeConfig from '@/components/ProcessNodeConfig'
import RuleConfigurationComponent from '@/components/RuleConfigurationComponent'
export default {
  name:'startNodeInfo',
  components:{RuleConfigurationComponent},
  props:{
    configData:{
    },
    TABLE_ID:{},  //主表数据
    status:null,
    readOnly:{
      type:Boolean,
      default:false
    },
    moduleType:{
      type: Number,
      default: 0
    }
  },
  computed: {
    defaultData () {
      // eslint-disable-next-line vue/no-side-effects-in-computed-properties
      this.infoData = this.configData
      return this.configData
    },
    currentComponent () {
      return ProcessNodeConfig
    }
  },
  watch:{
    defaultData:{
      handler () {
        this.infoData = this.defaultData
      },
      deep:true
    }
  },
  data () {
    return {
      infoData:[],
      defaultObj:{},

      
      triggerButtons:[],// 触发按钮
      visibleButtons:[], // 可见按钮

      //节点表的配置
      tableConfig:{
        props:{
          columnsKey: ['NAME'],
          AutoData: [],
          hidecolumns: ['id'],
          data: {},
          totalRowCount: 0,
          defaultSelected: [],
          isBackRowItem: true
        },
        event:{
          'on-input-value-change': (value) => {
              // 外键的模糊搜索
              this.tableConfig.props.AutoData = []
              this.$network.post('/p/c/meta/table/list',{DESCRIPTION:value}).then(res => {
                if(res.data.code === 0){
                  // this.row = res.data.data.row.concat([])
                  this.tableConfig.props.AutoData = res.data.data.row.reduce((arr,item) => {
                    arr.push({
                      value:item.NAME.val,
                      id:item.ID.val,
                      NAME:item.DESCRIPTION.val
                    })
                    return arr
                  },[]);
                }
                
              })
          },
          'on-popper-show': ($this) => {
            // 当外键下拉站开始去请求数据
            // this.freshDropDownSelectFilterData($this)
            this.$network.post('/p/c/meta/table/list',{
              pageSize:$this.pageSize,
              page:1
            }).then(res => {
              if(res.data.code === 0){
                res.data.data.tabth.forEach(item => {
                  if(item.colname === 'DESCRIPTION'){
                    item.isak = true
                  }
                  return item
                })
                this.tableConfig.props.data = res.data.data;
                this.tableConfig.props.totalRowCount = res.data.data.totalRowCount;
              }
              
            })
          },
          'on-page-change': (currentPage, $this) => {
            // 外键的分页查询
            // this.freshDropDownSelectFilterData($this,currentPage)
            this.$network.post('/p/c/meta/table/list',{
              pageSize:$this.pageSize,
              page:currentPage
            }).then(res => {
              if(res.data.code === 0){
                res.data.data.tabth.forEach(item => {
                  if(item.colname === 'DESCRIPTION'){
                    item.isak = true
                  }
                  return item
                })
                this.tableConfig.props.data = res.data.data;
                this.tableConfig.props.totalRowCount = res.data.data.totalRowCount;
              }
              
            })
          },
          'on-blur':(event,instance) => {
            // if(Object.prototype.toString.call(this.data.businessType) !== '[object Array]' || this.data.businessType.length === 0){
            //   instance.inputValue = ''

            //   /* 
            //     todo
            //     清空所有和主表有关的数据
            //   */

            // }
          },
          'on-fkrp-selected': (value) => {
            if(value.length > 0){
              this.configData.businessTypeName = value[0].rowItem.NAME.val?value[0].rowItem.NAME.val:value[0].rowItem.NAME
              this.configData.businessType= value[0].ID
              this.configData.businessTypeText = value[0].Label
              this.getTriggerButtons()
              this.getVisibleButtons()
            }else{
              this.configData.businessTypeName = null
              this.configData.businessType = null
              this.configData.businessTypeText = null
            }

            

            // 清除可显示字段数据
            // this.onClear()
            this.configData.visibleBt = []
            this.configData.triggerBt = []
            this.configData.businessKeyId = null
            this.configData.businessKey = null
            this.configData.businessKeyName = null
            this.indexQuery.defaultSelected = []
          },
          'on-clear': () => {
            // 清除可显示字段数据
            // this.onClear()
            this.configData.visibleBt = []
            this.configData.triggerBt = []
            this.configData.businessKeyId = null
            this.configData.businessKey = null
            this.configData.businessKeyName = null
            this.indexQuery.defaultSelected = []


            this.configData.businessTypeName = null
            this.configData.businessType = null
            this.configData.businessTypeText = null
            this.tableConfig.props.AutoData = []
              this.$network.post('/p/c/meta/table/list',{DESCRIPTION:''}).then(res => {
                if(res.data.code === 0){
                  this.tableConfig.props.AutoData = res.data.data.row.reduce((arr,item) => {
                    arr.push({
                      value:item.NAME.val,
                      id:item.ID.val,
                      NAME:item.DESCRIPTION.val
                    })
                    return arr
                  },[]);
                }
              })
          }
        }
      },

      // 查询索引
      indexQuery:{
        props:{
          columnsKey: ['NAME'],
          AutoData: [],
          hidecolumns: ['id'],
          data: {},
          totalRowCount: 0,
          defaultSelected: [],
          isBackRowItem: true
        },
        event:{
          'on-input-value-change': (value,instance) => {
              if(!this.configData.businessType){
                this.$Modal.fcWarning({
                  title:'警告',
                  content:'请先选择节点表!'
                })
                this.configData.businessKeyId = null
                this.configData.businessKey = null
                this.configData.businessKeyName = null
                instance.inputValue = ''
                return
              }
              // 外键的模糊搜索
              this.indexQuery.props.AutoData = []
              this.$network.post('/p/c/meta/column/list',{DESCRIPTION:value,AD_TABLE_ID:this.configData.businessType}).then(res => {
                if(res.data.code === 0){
                  // this.row = res.data.data.row.concat([])
                  this.indexQuery.props.AutoData = res.data.data.row.reduce((arr,item) => {
                    arr.push({
                      value:item.NAME.val,
                      id:item.ID.val,
                      NAME:item.DESCRIPTION.val
                    })
                    return arr
                  },[]);
                }
                
              })
          },
          'on-popper-show': ($this) => {
            if(!this.configData.businessType){
              this.$Modal.fcWarning({
                title:'警告',
                content:'请先选择节点表!'
              })
              this.configData.businessKeyId = null
              this.configData.businessKey = null
              this.configData.businessKeyName = null
              $this.inputValue = ''
              return
            }
            // 当外键下拉站开始去请求数据
            // this.freshDropDownSelectFilterData($this)
            this.$network.post('/p/c/meta/column/list',{
              pageSize:$this.pageSize,
              page:1,
              AD_TABLE_ID:this.configData.businessType
            }).then(res => {
              if(res.data.code === 0){
                res.data.data.tabth.forEach(item => {
                  if(item.colname === 'DESCRIPTION'){
                    item.isak = true
                  }
                  return item
                })
                this.indexQuery.props.data = res.data.data;
                this.indexQuery.props.totalRowCount = res.data.data.totalRowCount;
              }
              
            })
          },
          'on-page-change': (currentPage, $this) => {
            // 外键的分页查询
            // this.freshDropDownSelectFilterData($this,currentPage)
            this.$network.post('/p/c/meta/column/list',{
              pageSize:$this.pageSize,
              page:1,
              AD_TABLE_ID:this.configData.businessType
            }).then(res => {
              if(res.data.code === 0){
                res.data.data.tabth.forEach(item => {
                  if(item.colname === 'DESCRIPTION'){
                    item.isak = true
                  }
                  return item
                })
                this.indexQuery.props.data = res.data.data;
                this.indexQuery.props.totalRowCount = res.data.data.totalRowCount;
              }
            })
          },
          'on-blur':(event,instance) => {
            // if(Object.prototype.toString.call(this.data.businessType) !== '[object Array]' || this.data.businessType.length === 0){
            //   instance.inputValue = ''

            //   /* 
            //     todo
            //     清空所有和主表有关的数据
            //   */

            // }
          },
          'on-fkrp-selected': (value) => {
            this.configData.businessKey = value[0].rowItem.NAME.val?value[0].rowItem.NAME.val:value[0].rowItem.NAME
            this.configData.businessKeyId= value[0].ID
            this.configData.businessKeyName = value[0].Label
          },
          'on-clear': () => {
            // 清除可显示字段数据
            // this.onClear()

            this.configData.businessKey = null
            this.configData.businessKeyId= null
            this.configData.businessKeyName = null
            this.indexQuery.props.AutoData = []
            this.$network.post('/p/c/meta/column/list',{DESCRIPTION:''}).then(res => {
              if(res.data.code === 0){
                this.indexQuery.props.AutoData = res.data.data.row.reduce((arr,item) => {
                  arr.push({
                    value:item.NAME.val,
                    id:item.ID.val,
                    NAME:item.DESCRIPTION.val
                  })
                  return arr
                },[]);
              }
            })
          }
        }
      },
    }
  },
  created () {
    this.defaultObj = JSON.parse(JSON.stringify(this.configData))

    if(this.TABLE_ID){  //如果为固定模版
      this.configData.businessType = this.TABLE_ID[0].ID
      this.configData.businessTypeName = this.TABLE_ID[0].Label
    }

    if(this.configData.businessType){
      this.tableConfig.props.defaultSelected= [
        {
          ID: this.configData.businessType,
          Label: this.configData.businessTypeName
        }
      ]
      this.getTriggerButtons()
      this.getVisibleButtons()
    }

    if(this.configData.businessKeyId){
      this.indexQuery.props.defaultSelected= [
        {
          ID: this.configData.businessKeyId,
          Label: this.configData.businessKey
        }
      ]
    }
  },
  methods:{
    addRule () {  //添加规则
        this.configData.ruleList.push({
          name: null,
          rule: null,
          ruleType: 0,
          threshold: {
            id:'',
            label:''
          }
        })
    },
    delectRule (itemIndex) { //删除规则
      console.log(itemIndex)
      this.configData.ruleList.splice(itemIndex, 1)
      this.configData.ruleList.concat([])
      this.$set(this.configData.ruleList,this.configData.ruleList)
    },
    async saveConfig () {  //确定按钮点击
      await this.inputChange().then(() => {  //判断完优先级
        // 存在配置规则，校验各项是否必填
        let errorFlag = false //判断标志

        // 判断单据类型是否必填
        if(!this.configData.businessType){
          this.$Modal.fcError({
            title:'错误',
            content:'单据类型不能为空!',
            mask: true
          })
          errorFlag = true
          return
        }

        if(this.configData.ruleList && this.configData.ruleList.length > 0){
          this.configData.ruleList.map(item => {
            if(item.ruleType === 0 && (!item.fTableInfo || !item.rule || !item.threshold.id)){  //直接选择
              this.$Modal.fcError({
                title:'错误',
                content:'请完善规则配置',
                mask: true
              })
              errorFlag = true
              return
            }

            if(item.ruleType === 1 && !item.businessExpansion){
              this.$Modal.fcError({
                title:'错误',
                content:'请完善规则配置',
                mask: true
              })

              errorFlag = true
              return
            }
          })
        }

        if(!errorFlag){
          this.$emit('closeDrawer')
        }
        
      })
    },
    closeDrawer () {  //取消按钮点击
      this.$parent.$parent.nodeMsg[Number(this.configData.key)] = this.defaultObj
      this.$emit('closeDrawer')
    },
    async inputChange () {  //优先级失去焦点判断
      return new Promise((resolve) => {
        this.$network.post('/p/cs/node/priority',{
          defaultPriority:this.configData.priority,
          BUSINESS_TYPE:this.configData.businessType,
          id:this.configData.id
        }).then(res => {
          if(res.data.resultCode === -1){
            this.$Modal.fcError({
              title:'错误',
              content:res.data.resultMsg,
              mask:true
            })
          }

          if(res.data.resultCode === 0){
            resolve(res)
          }

          
        })
      })
    },
    
    getTriggerButtons () {  //获取触发按钮
      this.$network.post('/p/cs/node/define/bt',{
        id: this.configData.businessType,
        vueDispaly: 1
      })
      .then(res => {
        if(res.data.resultCode === 0){
          this.triggerButtons = res.data.data.difineData
        }else{
          this.triggerButtons = []
        }
      })
    },
    triggerBtChange (value) {  //触发按钮选择
      if(value[0] === 'bSelect-all'){
        this.configData.triggerBt = this.triggerButtons.reduce((arr,current) => {
          arr.push(current.ID)
          return arr
        },[])
      }
    },
    getVisibleButtons () { //获取可见按钮
      this.$network.post('/p/cs/node/define/bt',{
        id: this.configData.businessType,
        vueDispaly: 0
      })
      .then(res => {
        if(res.data.resultCode === 0){
          this.visibleButtons = res.data.data.difineData
        }else{
          this.visibleButtons = []
        }
      })
    },
    visibleBtChange (value) {  //可见按钮选择
      if(value[0] === 'bSelect-all'){
        this.configData.visibleBt = this.visibleButtons.reduce((arr,current) => {
          arr.push(current.ID)
          return arr
        },[])
      }
    }
  }
}
</script>
<style lang="scss" scoped>

  
  .InformationBlock{
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    >p{
      text-align: right;
      margin-top: 16px;

      >button:first-child{
        margin-right: 10px;
      }
    }
    .content{
      flex:1;
      display: flex;
      flex-direction: column;
      overflow: auto;

      

      .rule_content{
        flex: 1;
        overflow: auto;
        display: flex;
        flex-direction: column;
        .rule{
          flex: 1;
          display: flex;
          flex-direction: column;

          >.title{
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 10px;

            span:first-child{
              font-size:14px;
              font-family:PingFangSC-Regular;
              font-weight:400;
              color:rgba(146,146,146,1);
              line-height:20px;
            }
            span:last-child{
              font-size:14px;
              font-family:PingFangSC-Regular;
              font-weight:400;
              color:rgba(16,142,233,1);
              line-height:20px;
              cursor: pointer;
            }
          }

          >.form{
            height:64px;
            background:rgba(255,255,255,1);
            border:1px solid rgba(220,222,226,1);
            border-bottom: 0;
            margin-bottom: 0;
          }

          >.ruleContent{
            border:1px solid rgba(220,222,226,1);
            overflow: auto;
            max-height: 100%;

            >.RuleConfigurationComponent{
              border-top:1px solid rgba(220,222,226,1);
              &:first-child{
                border-top: none;
              }
            }
          }
        }
      }
    }

    .form{
      background:rgba(255,255,255,1);
      border:1px solid rgba(220,222,226,1);
      padding: 16px 40px 16px 0;
      margin-bottom: 16px;

      >p{
        display: flex;
        align-items: center;
        width: 100%;
        margin-bottom: 10px;

        &:last-child{
          margin-bottom: 0;
        }

        >.label{
          display: inline-block;
          width: 100px;
          text-align: right;
          margin-right: 8px;

          .requireStyle {
            font-size: 14px;
            vertical-align: middle;
            color: red;
            padding-top: 5px;
            display: inline-block;
          }
        }

        >div{
          flex:1;
          overflow: hidden;
        }

        span.tips{
          font-size:12px;
          font-family:PingFangSC-Regular;
          font-weight:400;
          color:rgba(146,146,146,1);
          line-height:16px;
        }

        &.tips{
          margin-top: 4px;
        }
      }
    }

    
  }
</style>