<template>
    <a-spin :spinning="confirmLoading" class="interlock-summary-set">
      <div class="u-flex-jab top-title">
        <div class="left">
          <a-icon type="arrow-left" @click="goBack"/>
          <span>{{ summaryType }}</span>
        </div>
        <div>
          <a-button @click="goBackCheck" style="margin-right: 10px;font-size: 16px;">关闭</a-button>
          <a-button @click="handleOk" type="primary">提交</a-button>
        </div>
      </div>
      <j-form-container class="content-container">
        <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
          <div class="interlock-summary-item">
            <div class="interlock-summary-item-title">联锁基本信息</div>
            <a-row>
              <a-col :span="12">
                <a-form-model-item label="联锁名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="interlockName">
                  <a-input v-model="model.interlockName" placeholder="请输入联锁名称"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
                  <a-input v-model="model.remark" placeholder="请输入备注"></a-input>
                </a-form-model-item>
              </a-col>
            </a-row>
          </div>
          <!-- 联锁条件信息 -->
          <div class="interlock-summary-item" style="padding-bottom: 12px;">
            <div class="interlock-summary-item-title u-flex-jab">
              <div>联锁条件信息</div>
              <a-button @click="handleAddCondition" type="primary" icon="plus">新增联锁条件</a-button>
            </div>
            <a-row>
              <a-col :span="12">
                <a-form-model-item label="逻辑关系" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="ljgx">
                  <!-- <a-input v-model="model.ljgx" placeholder="请输入逻辑关系"></a-input> -->
                  <!-- <j-dict-select-tag v-model="model.ljgx"  placeholder="请选择操作类型" dictCode="ljgx"/> -->
                  <a-auto-complete :data-source="ljgxOptions" v-model="model.ljgx" :filter-option="filterOption" placeholder="请设置逻辑关系"></a-auto-complete>
                </a-form-model-item>
              </a-col>
            </a-row>
            <!-- 联锁条件表格 -->
            <a-table
              ref="table"
              size="middle"
              :scroll="{x:true}"
              :pagination="false"
              :rowKey="(record,index)=>{return index}"
              :columns="columns"
              :dataSource="conditionDataSource"
              class="j-table-force-nowrap"
              style="margin: 0 12px;">
              <!-- 仪表状态依据 -->
              <span slot="instrumentStatusJuge" slot-scope="text, record">
                <template v-if="record.instrumentStatusJuge === '3'">
                  <span>默认正常</span>
                </template>
                <template v-if="record.instrumentStatusJuge === '0'">
                  <span>位号读取</span>
                </template>
                <template v-if="record.instrumentStatusJuge === '1'">
                  <span>高低限判断</span>
                </template>
                <template v-if="record.instrumentStatusJuge === '2'">
                  <span>突变超限判断</span>
                </template>
              </span>
              <!-- 仪表状态内容 -->
              <span slot="instrumentStatusContent" slot-scope="text, record">
                <template v-if="record.instrumentStatusJuge === '3'">
                  {{ (record.instrumentStatusNormalName?record.instrumentStatusNormalName:itSystemDefaultValue.instrumentStatusNormalName)+'('+record.instrumentStatusValue+')' }}
                </template>
                <template v-if="record.instrumentStatusJuge === '0'">
                  <span>位号：{{ record.instrumentStatusTag }}</span>
                </template>
                <template v-if="record.instrumentStatusJuge === '1'">
                  <span>位号：{{ record.ysmnlTag }}</span><br/>
                  <span>
                    <span>高限值：{{ record.upperLimit }}</span>&nbsp;
                    <span>低限值：{{ record.lowerLimit }}</span>
                  </span>
                </template>
                <template v-if="record.instrumentStatusJuge === '2'">
                  <span>位号：{{ record.ysmnlTag }}</span><br/>
                  <span>
                    <span>高限值：{{ record.upperLimit }}</span> &nbsp;
                    <span>低限值：{{ record.lowerLimit }}</span>
                  </span><br/>
                  <span>
                    <span>时间：{{ record.thresholdTime }}</span>&nbsp;
                    <span>阈值：{{ record.thresholdValue }}</span>
                  </span>
                </template>
              </span>
              <!-- 是否旁路 -->
              <span slot="ifBypass" slot-scope="text, record">
                <!-- 否：正常状态 -->
                <span v-if="record.ifBypass === '0'">{{ (record.bypassYesName?record.bypassYesName:itSystemDefaultValue.bypassYesName)+'('+record.bypass+')' }}</span>
                <!-- 是 -->
                <span v-if="record.ifBypass === '1'">{{ record.bypassTag }}</span>
                <!-- 现场旁路 -->
                <template v-if="record.ifBypass === '2'">
                  <!-- 选择为正常状态 -->
                  <span v-if="record.bypass === itSystemDefaultValue.bypassYes">{{ (record.bypassYesName?record.bypassYesName:itSystemDefaultValue.bypassYesName)+'('+record.bypass+')' }}</span>
                  <!-- 选择为异常状态 -->
                  <span v-else>{{ (record.bypassNoName?record.bypassNoName:itSystemDefaultValue.bypassNoName)+'('+record.bypass+')' }}</span>
                </template>
              </span>
              <!-- 操作 -->
              <span slot="action" slot-scope="text, record, index">
                <a-tooltip>
                  <template slot="title"> 设置 </template>
                  <span class="edit-btn" @click="handleEditCondition(record, index)"></span>
                </a-tooltip>
                <a-tooltip>
                  <template slot="title"> 复制 </template>
                  <span class="copy-btn" @click="handleCopyCondition(record, index)"></span>
                </a-tooltip>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDeleteCondition(record, index)">
                  <a-tooltip>
                    <template slot="title"> 删除 </template>
                    <span class="delete-btn"></span>
                  </a-tooltip>
                </a-popconfirm>
              </span>
            </a-table>
          </div>
          <!-- 联锁输出 -->
          <div class="interlock-summary-item">
            <div class="interlock-summary-item-title">联锁输出</div>
            <a-row>
              <a-col :span="12">
                <a-form-model-item label="联锁输出值" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="interlockOutValueData">
                  <a-cascader
                    v-model="model.interlockOutValueData"
                    :options="tagDataOptions"
                    :fieldNames="customFieldNames"
                    :show-search="{ filter }"
                    expand-trigger="hover"
                    placeholder="请选择"
                    @change="changeCascader"
                    />
                    <!-- :display-render="displayRender" -->
                </a-form-model-item>
              </a-col>
            </a-row>
          </div>
          <!-- 新增联锁条件 -->
          <j-modal
            :title="conditionTitle"
            :visible="conditionVisible"
            @ok="handleConditionOk"
            @cancel="handleConditionCancel"
            :width="800"
            cancelText="关闭"
            class="interlock-condition-form">
            <!-- :okButtonProps="{ class:{'jee-hidden': disableSubmit} }" -->
            <interlock-condition-form ref="conditionForm" :itSystemDefaultValue="itSystemDefaultValue" :tagDataOptions="tagDataOptions" @ok="submitCallback"></interlock-condition-form>
          </j-modal>
        </a-form-model>
      </j-form-container>
    </a-spin>
  </template>
  
  <script>
    import { httpAction, getAction, postAction } from '@/api/manage'
    import { validateDuplicateValue } from '@/utils/util'
    import InterlockConditionForm from './InterlockConditionForm.vue'
    import {ajaxGetDictItems,getDictItemsFromCache} from '@/api/api'
    // import { mixinDevice } from '@/utils/mixin'
    // import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  
    export default {
      name: 'InterlockSummaryForm',
      // mixins:[JeecgListMixin, mixinDevice],
      components: {
        InterlockConditionForm
      },
      data () {
        return {
          originalData: null, // 原始数据，退出时新老数据比较
          model:{
          },
          labelCol: {
            xs: { span: 24 },
            sm: { span: 5 },
          },
          wrapperCol: {
            xs: { span: 24 },
            sm: { span: 16 },
          },
          confirmLoading: true,
          validatorRules: {
            interlockName: [
              { required: true, message: '请输入联锁名称!', },
              { validator: (rule, value, callback) => validateDuplicateValue('interlock_summary	', 'interlock_name', value, this.model.id, callback)},
            ],
            // ljgx: [{
            //   required: true, message: '请输入逻辑关系!',
            // }],
            // interlockOutValueData: [{
            //   required: true, message: '请选择联锁输出值!',
            // }],
          },
          url: {
            interLockSelect: '/sys/dict/loadTreeData',
            add: "/summary/interlockSummary/addLS",
            edit: "/summary/interlockSummary/editLS",
            queryById: "/summary/interlockSummary/queryById",
            getLsAllData: "/summary/interlockSummary/xxxxLS",
            getTagInfo: "/iotedgeCollectData/iotedgeCollectData/getTagInfo",
          },
          customFieldNames: {
            label: 'name',
            value: 'info',
            children: 'children'
          },
          apparatusData: [],
          systemData: [],
          interLockData: [],
          // 设备-模块-位号
          tagDataOptions: [],
          // 新增联锁条件
          conditionTitle: '设置联锁条件',
          conditionVisible: false,
          // 联锁条件表格
          conditionDataSource: [],
          columns: [
            // {
            //   title: '序号',
            //   dataIndex: '',
            //   key:'rowIndex',
            //   width:60,
            //   align:"center",
            //   customRender:function (t,r,index) {
            //     return parseInt(index)+1;
            //   }
            // },
            {
              title:'联锁条件',
              align:"center",
              dataIndex: 'interlockConditionTag'
            },
            {
              title:'仪表状态依据',
              align:"center",
              // dataIndex: 'instrumentStatusJuge',
              scopedSlots: { customRender: 'instrumentStatusJuge' }
            },
            {
              title:'仪表状态内容',
              align:"center",
              // dataIndex: 'instrumentStatusTag',
              scopedSlots: { customRender: 'instrumentStatusContent' }
            },
            {
              title:'描述',
              align:"center",
              dataIndex: 'description'
            },
            {
              title:'联锁设定值',
              align:"center",
              dataIndex: 'interlockSetValue'
            },
            // {
            //   title:'当前值',
            //   align:"center",
            //   dataIndex: 'currentValueTag'
            // },
            {
              title:'旁路状态',
              align:"center",
              scopedSlots: { customRender: 'ifBypass' }
            },
            {
              title:'输入卡件状态',
              align:"center",
              dataIndex: 'inputStatusTag',
              customRender: (text, record, index)=> {
                if(record.inputStatusTag){
                  return record.inputStatusTag
                } else {
                  var name = record.controlSystemStatusNormalName ? record.controlSystemStatusNormalName : this.itSystemDefaultValue.controlSystemStatusNormalName
                  return name +'('+ record.inputStatus+')'
                }
              }
            },
            {
              title:'输出卡件状态',
              align:"center",
              dataIndex: 'outputStatusTag',
              customRender: (text, record, index)=> {
                if(record.outputStatusTag){
                  return record.outputStatusTag
                } else {
                  var name = record.controlSystemStatusNormalName ? record.controlSystemStatusNormalName : this.itSystemDefaultValue.controlSystemStatusNormalName
                  return name +'('+ record.outputStatus+')'
                }
              }
            },
            {
              title:'MP状态',
              align:"center",
              dataIndex: 'mpStatusTag',
              customRender: (text, record, index)=> {
                if(record.mpStatusTag){
                  return record.mpStatusTag
                } else {
                  var name = record.controlSystemStatusNormalName ? record.controlSystemStatusNormalName : this.itSystemDefaultValue.controlSystemStatusNormalName
                  return name +'('+ record.mpStatus+')'
                }
              }
            },
            {
              title: '操作',
              dataIndex: 'action',
              align:"center",
              fixed:"right",
              width:147,
              scopedSlots: { customRender: 'action' }
            }
          ],
          tableClickRowIndex: -1,
          itSystemDefaultValue: {}, // 该系统设置的默认值
          ljgxOptions: [],
        }
      },
      computed: {
        summaryEditInfo() {
          return this.$store.getters.summaryEditInfo
        },
        summaryType() {
          return this.$store.getters.summaryType
        },
        clickSystemNode() {
          return this.$store.getters.clickSystemNode
        },
      },
      // watch: {
      //   'model.interlockName'(val) {
      //     console.log('value', val);
      //   },
      // },
      mounted(){
        window.addEventListener('onunload', this.handleRefresh);
      },
      beforeDestroy() {
        // 一定要在组件销毁前移除事件监听，避免内存泄露
        window.removeEventListener('onunload', this.handleRefresh);
      },
      created () {
        if(this.summaryType === '编辑'){
          this.getEditData()
        } else if(this.summaryType === '新增'){
          this.setAdd()
        } else {
          this.getCopyData()
        }
        // this.getTagInfo()
        this.initDictData()
        // this.getData('0', 'apparatusData')
      },
      methods: {
        handleRefresh(){
          console.log(1111)
          this.$router.go(-1)
          // this.$router.replace("*")
        },
        // 获取逻辑关系字典
        initDictData() {
          //优先从缓存中读取字典配置
          if(getDictItemsFromCache('ljgx')){
            var dicts = getDictItemsFromCache('ljgx');
            this.ljgxOptions = dicts.map(item => item.label)
            return
          }
          //根据字典Code, 初始化字典数组
          ajaxGetDictItems('ljgx', null).then((res) => {
            if (res.success) {
              var dicts = res.result;
              this.ljgxOptions = dicts.map(item => item.label)
            }
          })
        },
        // 设置装置系统id并获取该系统默认设置值
        getZzXtData(){
          console.log('model', this.model)
          getAction('/base/interlockBase/queryById', {id: this.model.interlockSystemId}).then(res => {
            if(res.success){
              this.itSystemDefaultValue = res.result
            }
          })
        },
        // 获取所有位号
        getTagInfo(groupId){
          // console.log('this.clickSystemNode', this.clickSystemNode)
          // console.log('groupId', groupId)
          postAction(this.url.getTagInfo, {groupId: groupId}).then(res => {
            this.tagDataOptions = res.result
            this.confirmLoading = false
          })
        },
        // 逻辑关系过滤
        filterOption(input, option) {
          return (
            option.componentOptions.children[0].text.toUpperCase().indexOf(input.toUpperCase()) >= 0
          );
        },
        // 联锁条件弹窗-取消
        handleConditionCancel(){
          this.conditionVisible = false
        },
        // 联锁条件弹窗-确认
        handleConditionOk(){
          this.$refs.conditionForm.submitForm();
        },
        // 联锁条件弹窗-确认回调
        submitCallback(model){
          if(this.tableClickRowIndex >= 0){
            // 编辑回调
            this.conditionDataSource[this.tableClickRowIndex] = model
          } else {
            // 新增回调
            this.conditionDataSource.push(model)
          }
          this.conditionVisible = false
        },
        interLockSearch(searchText){
          console.log(searchText)
          // this.interLockData = !searchText ? [] : [searchText, searchText.repeat(2), searchText.repeat(3)]
        },
        // displayRender({ labels }) {
        //   // 设置选择最后一位
        //   return labels[labels.length - 1];
        // },
        // 位号选择改变
        changeCascader(value, selectedOptions){
          // console.log(value, selectedOptions)
          this.model = {...this.model}
          this.model.deviceId = value[0]
          this.model.moduleName = value[1]
          this.model.interlockOutValueTag = value[2]
          this.model.interlockOutValue = selectedOptions[2].value
        },
        // 级联选择过滤搜索
        filter(inputValue, path) {
          return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
        },
        // 新增联锁条件
        handleAddCondition(){
          this.tableClickRowIndex = -1
          this.conditionVisible = true
          this.$nextTick(()=>{
            this.$refs.conditionForm.add();
          })
        },
        // 编辑联锁条件
        handleEditCondition(record, index){
          console.log(index)
          this.tableClickRowIndex = index
          this.conditionVisible = true
          this.$nextTick(()=>{
            this.$refs.conditionForm.edit(record);
          })
        },
        // 复制联锁条件
        handleCopyCondition(record){
          this.tableClickRowIndex = -1
          this.conditionVisible = true
          this.$nextTick(()=>{
            this.$refs.conditionForm.edit(record);
          })
        },
        // 删除联锁条件
        handleDeleteCondition(record, index){
          this.conditionDataSource.splice(index, 1)
        },
        // 新增联锁-弹窗
        setAdd() {
          if(this.clickSystemNode && this.clickSystemNode.interlockType === '1'){
            // 当前是新增-用树选择的装置系统进行赋值
            this.model.interlockApparatusId = this.clickSystemNode.pid
            this.model.interlockSystemId = this.clickSystemNode.id
          }
          this.getZzXtData()
          this.getTagInfo(this.clickSystemNode.groupId)
          //备份model原始值
          this.originalData = JSON.parse(JSON.stringify(this.model));
          this.originalData.interlockDetailAddDTOList = [];
        },
        // 编辑联锁-弹窗
        getEditData() {
          var record = this.summaryEditInfo
          // console.log(record)
          // this.model = Object.assign({}, record);
          // 编辑时获取当前联锁所有详细信息
          getAction(this.url.getLsAllData, {id: record.summaryid}).then(res => {
            var resultArr = res.result
            this.model = resultArr
            this.conditionDataSource = resultArr.interlockDetailEditQueryVOList // 表格数据
            this.model.interlockOutValueData = [resultArr.deviceId, resultArr.moduleName, resultArr.interlockOutValueTag]
            this.getZzXtData()
            this.getTagInfo(this.model.groupId)
            //备份model原始值
            this.originalData = JSON.parse(JSON.stringify(this.model));
            this.originalData.interlockDetailAddDTOList = JSON.parse(JSON.stringify(resultArr.interlockDetailEditQueryVOList));
          })
        },
        // 复制联锁-弹窗
        getCopyData() {
          var record = this.summaryEditInfo
          // this.model = Object.assign({}, record);
          // 编辑时获取当前联锁所有详细信息
          getAction(this.url.getLsAllData, {id: record.summaryid}).then(res => {
            // console.log("复制model数据：", res.result)
            var resultArr = res.result
            this.model = resultArr
            // 清空主表与子表的id
            this.model.id = null;
            this.model.interlockDetailEditQueryVOList.forEach(function(item, index, array) {
              item.id = null;
              item.summaryid = null;
            });
            this.conditionDataSource = resultArr.interlockDetailEditQueryVOList // 表格数据
            this.model.interlockOutValueData = [resultArr.deviceId, resultArr.moduleName, resultArr.interlockOutValueTag]
            this.getZzXtData()
            this.getTagInfo(this.model.groupId)
            //备份model原始值，不能直接用等于（等于的话，就传递指针了），必须用JSON.parse(JSON.stringify())方法
            this.originalData = JSON.parse(JSON.stringify(this.model));
            this.originalData.interlockDetailAddDTOList = JSON.parse(JSON.stringify(resultArr.interlockDetailEditQueryVOList));
          })
        },
        goBackCheck(){
          var _this = this          
          // 转换数据
          this.model.interlockDetailAddDTOList = this.conditionDataSource
          console.log("原始数据：", JSON.stringify(_this.originalData), "新的数据：", JSON.stringify(_this.model))
          if (JSON.stringify(_this.originalData) !== JSON.stringify(_this.model)) {
            _this.$confirm({
              title: '提示',
              content: '联锁信息已修改，是否确定退出？',
              okButtonProps: {
                style: {
                  backgroundColor: '#008cd6',
                  fontSize: '16px',
                }
              },
              cancelButtonProps: {
                style: {
                  fontSize: '16px',
                }
              },
              onOk() {
                _this. goBack()
              },
              onCancel() {},
            });
          }
          else {
            _this. goBack()
          }
        },
        goBack(){
          this.$router.go(-1)
          this.$store.commit('SET_SUMMARYEDITINFO', []);
          // this.$router.push({path: '/interLock/summary'})
        },
        handleOk(){
          var _this = this
          // 触发表单验证
          this.$refs.form.validate((ok, err) => {
            if (ok) {
              if(this.conditionDataSource.length===0){
                this.$message.error('联锁条件未设置')
                return false
              }
              _this.$confirm({
                title: '提示',
                content: '是否确定提交',
                okButtonProps: {
                  style: {
                    backgroundColor: '#008cd6',
                    fontSize: '16px',
                  }
                },
                cancelButtonProps: {
                  style: {
                    fontSize: '16px',
                  }
                },
                onOk() {
                  _this.submitForm()
                },
                onCancel() {},
              });
            }
          })
        },
        submitForm () {
          const that = this;
          that.confirmLoading = true;
          let httpurl = '';
          let method = '';
          if(!this.model.id){
            httpurl+=this.url.add;
            method = 'post';
          }else{
            httpurl+=this.url.edit;
              method = 'put';
          }
          // 转换数据
          this.model.interlockDetailAddDTOList = this.conditionDataSource
          // 联锁输出值位号
          // if(this.model.interlockOutValueData && this.model.interlockOutValueData.length > 0){
          //   this.model.deviceId = this.model.interlockOutValueData[0]
          //   this.model.moduleName = this.model.interlockOutValueData[1]
          //   this.model.interlockOutValueTag = this.model.interlockOutValueData[2]
          //   // this.model.interlockOutValue = (this.model.interlockOutValueData[2].split('&'))[1]
          // }
          console.log(this.model)
          httpAction(httpurl,this.model,method).then((res)=>{
            if(res.success){
              that.$message.success(res.message);
              this.$router.go(-1)
              this.$store.commit('SET_SUMMARYEDITINFO', []);
              // that.$emit('ok');
            }else{
              that.$message.warning(res.message);
            }
          }).finally(() => {
            that.confirmLoading = false;
          })
        },
        // 获取装置/系统/联锁数据--默认获取装置数据-方式一需要方法
        // getData(pid, dataName){
        //   let param = {
        //     pid: pid,
        //     tableName: 'interlock_base',
        //     text: 'interlock_name',
        //     code: 'id',
        //     pidField: 'pid',
        //     hasChildField: 'has_child',
        //     condition: ''
        //   }
        //   getAction(this.url.interLockSelect,param).then(res=>{
        //     if(res.success){
        //       this[dataName] = res.result
        //     }
        //   })
        // },
        // 装置选择改变时-方式一需要方法
        // handleApparatusChange(e){
        //   console.log(e)
        //   this.getData(e, 'systemData')
        // },
        // 系统选择改变时-方式一需要方法
        // handleSystemChange(e){
        //   console.log(e)
        //   this.getData(e, 'interLockData')
        // },
      }
    }
  </script>
  <style lang="less">
    .interlock-summary-set{
      height: 100%;
      overflow: hidden;
      .ant-spin-container{
        height: 100%;
        overflow: hidden;
      }
      .top-title{
        padding: 12px 10px 12px 20px;
        .left{
          font-size: 20px; 
          font-weight: 700;
          color: #323233;
          line-height: 40px;
        }
        .anticon{
          color: #008cd6;
          padding-right: 8px;
        }
      }
      .content-container{
        height: calc(100% - 64px);
        background: #fff;
        overflow: auto;
        .interlock-summary-item{
          // box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
          margin-bottom: 12px;
          // border-radius: 4px;
        }
        .interlock-summary-item-title{
          background-color: #F5F7FA;
          line-height: 44px;
          font-size: 16px;
          padding: 0 10px 0 20px;
          margin-bottom: 10px;
          border-bottom: 1px solid #f3f3f3;
          color: #323233;
          font-weight: 600;
        }
      }
      .u-flex-jab{
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      .interlock-condition-form{
        .ant-modal{
          top: 4px;
        }
      }
    }
  </style>