<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <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="interlockApparatusId">
                <a-select
                  v-model="model.interlockApparatusId"
                  show-search
                  placeholder="请选择装置"
                  @change="handleApparatusChange"
                  >
                  <a-select-option v-for="(item) in apparatusData" :key="item.key" :value="item.key">{{ item.title }}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col> -->
            <!-- <a-col :span="12">
              <a-form-model-item label="系统" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="interlockSystemId">
                <a-select
                  v-model="model.interlockSystemId"
                  show-search
                  placeholder="请选择系统"
                  @change="handleSystemChange"
                  >
                  <a-select-option v-for="(item) in systemData" :key="item.key" :value="item.key">{{ item.title }}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col> -->
            <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-form-model-item>
            </a-col>
          </a-row>
          <!-- 联锁条件表格 -->
          <a-table
            ref="table"
            size="middle"
            :scroll="{x:true}"
            bordered
            :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 === '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 === '0'">
                <span>位号：{{ record.instrumentStatusTag }}</span>
              </template>
              <template v-if="record.instrumentStatusJuge === '1'">
                <span>位号：{{ record.ysmnlTag }}</span><br/>
                <span>
                  <span>高限值：{{ record.upperLimit }}</span>
                  <span>低限值：{{ record.lowerLimit }}</span>
                </span>
              </template>
              <template v-if="record.instrumentStatusJuge === '2'">
                <span>位号：{{ record.ysmnlTag }}</span>
                <span>
                  <span>时间：{{ record.thresholdTime }}</span>
                  <span>阈值：{{ record.thresholdValue }}</span>
                </span>
              </template>
            </span>
            <!-- 是否旁路 -->
            <span slot="ifBypass" slot-scope="text, record">
              <span v-if="record.ifBypass === '1'">{{ record.bypassTag }}</span>
              <span v-if="record.ifBypass === '0'">{{ record.bypass }}</span>
            </span>
            <!-- 操作 -->
            <span slot="action" slot-scope="text, record, index">
              <a @click="handleEditCondition(record, index)">编辑</a>
              <a-divider type="vertical" />
              <a @click="handleCopyCondition(record, index)">复制</a>
              <a-divider type="vertical" />
              <a-popconfirm title="确定删除吗?" @confirm="() => handleDeleteCondition(record, index)">
                <a>删除</a>
              </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"
                  :display-render="displayRender"
                  :fieldNames="customFieldNames"
                  expand-trigger="hover"
                  placeholder="请选择位号"
                  @change="dianwerChange"
                  />
              </a-form-model-item>
            </a-col>
          </a-row>
        </div>
        <!-- 新增联锁条件 -->
        <j-modal
          :title="conditionTitle"
          :visible="conditionVisible"
          @ok="handleConditionOk"
          @cancel="handleConditionCancel"
          :width="800"
          cancelText="关闭">
          <!-- :okButtonProps="{ class:{'jee-hidden': disableSubmit} }" -->
          <interlock-condition-form ref="conditionForm" @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 { mixinDevice } from '@/utils/mixin'
  // import { JeecgListMixin } from '@/mixins/JeecgListMixin'

  export default {
    name: 'InterlockSummaryForm',
    // mixins:[JeecgListMixin, mixinDevice],
    components: {
      InterlockConditionForm
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      addInterlock: {
        type: Object,
        default: function(){
            return {} // 使用工厂函数返回默认值
        }
      },
    },
    data () {
      return {
        model:{
        },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
          interlockName: [{
            required: true, message: '请输入联锁名称!',
          }],
          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'
          },
          {
            title:'输出卡件状态位号',
            align:"center",
            dataIndex: 'outputStatusTag'
          },
          {
            title:'MP状态位号',
            align:"center",
            dataIndex: 'mpStatusTag'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' }
          }
        ],
        tableClickRowIndex: -1,
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    // watch: {
    //   'model.interlockName'(val) {
    //     console.log('value', val);
    //   },
    // },
    created () {
      console.log('弹窗', this.addInterlock)
      this.getTagInfo()
      this.getData('0', 'apparatusData')
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      // 获取所有位号
      getTagInfo(){
        postAction(this.url.getTagInfo).then(res => {
          console.log(res)
          this.tagDataOptions = res.result
        })
      },
      // 获取装置/系统/联锁数据--默认获取装置数据
      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
          }
        })
      },
      // 联锁条件弹窗-取消
      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
      },
      // 装置选择改变时
      handleApparatusChange(e){
        console.log(e)
        this.getData(e, 'systemData')
      },
      // 系统选择改变时
      handleSystemChange(e){
        console.log(e)
        this.getData(e, 'interLockData')
      },
      interLockSearch(searchText){
        console.log(searchText)
        // this.interLockData = !searchText ? [] : [searchText, searchText.repeat(2), searchText.repeat(3)]
      },
      displayRender({ labels }) {
        return labels[labels.length - 1];
      },
      // 位号选择改变
      dianwerChange(e){
        console.log(e)
      },
      // 新增联锁条件
      handleAddCondition(){
        this.tableClickRowIndex = -1
        this.conditionVisible = true
      },
      // 编辑联锁条件
      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)
      },
      // 新增联锁-弹窗
      add () {
        // this.edit(this.modelDefault);
        this.visible = true;
      },
      // 编辑联锁-弹窗
      edit (record) {
        // this.model = Object.assign({}, record);
        // 编辑时获取当前联锁所有详细信息
        getAction(this.url.getLsAllData, {id: record.summaryid}).then(res => {
          console.log(res)
          var resultArr = res.result
          this.model = resultArr
          this.conditionDataSource = resultArr.interlockDetailEditQueryVOList
          this.model.interlockOutValueData = [resultArr.deviceId, resultArr.moduleName, resultArr.interlockOutValueTag+'&'+resultArr.interlockOutValue]
        })
        this.visible = true;
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            if(this.conditionDataSource.length===0){
              this.$message.error('联锁条件未设置')
              return false
            }
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            // 装置系统id赋值
            if(this.addInterlock && this.addInterlock.interlockType === '1'){
              // 当前是新增-用树选择的装置系统进行赋值
              this.model.interlockApparatusId = this.addInterlock.pid
              this.model.interlockSystemId = this.addInterlock.id
            }
            // 转换数据
            this.model.interlockDetailAddDTOList = this.conditionDataSource
            // 联锁输出值位号
            this.model.deviceId = this.model.interlockOutValueData[0]
            this.model.moduleName = this.model.interlockOutValueData[1]
            this.model.interlockOutValueTag = (this.model.interlockOutValueData[2].split('&'))[0]
            this.model.interlockOutValue = (this.model.interlockOutValueData[2].split('&'))[1]
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }

        })
      },
    }
  }
</script>
<style lang="less">
  .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: 40px;
    font-size: 15px;
    padding: 0 20px;
    margin-bottom: 10px;
    border-bottom: 1px solid #f3f3f3;
  }
  .u-flex-jab{
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
</style>