<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    okText="提交"
    cancelText="关闭">
    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :model="model" :rules="validatorRules">
        <a-form-model-item label="类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="interlockType">
          <j-dict-select-tag
            type="radio"
            v-model="model.interlockType"  dictCode="interlock_type"
            placeholder="请选择类型"
            :disabled="disableEdit"/>
        </a-form-model-item>
        <a-form-model-item label="名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="interlockName">
          <a-input v-model="model.interlockName" placeholder="请输入名称" ></a-input>
        </a-form-model-item>
        <template v-if="model.interlockType !== '0'">
          <a-form-model-item label="父级节点" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="pid">
            <!-- <j-tree-select
              ref="treeSelect"
              placeholder="请选择父级节点"
              v-model="model.pid"
              :maxLevel="'1'"
              dict="interlock_base,interlock_name,id"
              pidField="pid"
              pidValue="0"
              hasChildField="has_child"
              >
            </j-tree-select> -->
            <!-- <a-tree-select
              v-model="model.pid"
              style="width: 100%"
              :tree-data="interlockTwoTree"
              placeholder="请选择"
              tree-default-expand-all
              :replaceFields="{
                children: 'children',
                key: 'id',
                value: 'id',
                title: 'interlockName',
              }"
              ></a-tree-select> -->
              <a-select
                v-model="model.pid"
                show-search
                placeholder="请选择装置"
                @change="pidChange"
                >
                <!-- labelInValue -->
                <a-select-option v-for="(item) in interlockTwoTree" :key="item.key" :value="item.key">{{ item.title }}</a-select-option>
              </a-select>
              <!-- :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" -->
          </a-form-model-item>
          <a-form-model-item label="默认类别" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="interlockType">
            <j-dict-select-tag
              ref="systemTypeRef"
              type="radio"
              v-model="model.systemType"  dictCode="system_type"
              placeholder="请选择默认类别"/>
              <!-- <a-radio-group name="radioGroup" v-model="model.systemType">
                <a-radio :value="item.value" v-for="item in systemTypeDicts" :key="item.value"> {{item.label}} </a-radio>
              </a-radio-group> -->
          </a-form-model-item>
          <a-divider orientation="left"> <span>状态值设置</span> </a-divider>
          <!-- 控制系统状态 -->
          <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="controlSystemStatus" ref="controlSystemStatus">
            <span slot="label">
              <span class="red-star-label">*</span>
              控制系统状态&nbsp;
              <a-tooltip title="选择对应状态代表的参数值并自定义系统中显示的名称">
                <a-icon type="question-circle-o" />
              </a-tooltip>
            </span>
            <div style="display: flex;align-items: center;">
              <span style="width: 100px;">正常状态：</span>
              <a-input-group compact>
                <a-select v-model="model.controlSystemStatusNormal" style="width: 15%" @change="controlNormalChange">
                  <a-select-option value="0"> 0 </a-select-option>
                  <a-select-option value="1"> 1 </a-select-option>
                </a-select>
                <a-input v-model="model.controlSystemStatusNormalName" placeholder="请输入该状态系统中显示名称" @change="onStatusChange('controlSystemStatus')" style="width: 85%"/>
              </a-input-group>
            </div>
            <div style="display: flex;align-items: center;">
              <span style="width: 100px;">故障状态：</span>
              <a-input-group compact>
                <a-select v-model="model.controlSystemStatusAbnormal" style="width: 15%" @change="controlAbnormalChange">
                  <a-select-option value="0"> 0 </a-select-option>
                  <a-select-option value="1"> 1 </a-select-option>
                </a-select>
                <a-input v-model="model.controlSystemStatusAbnormalName" placeholder="请输入该状态系统中显示名称" @change="onStatusChange('controlSystemStatus')" style="width: 85%"/>
              </a-input-group>
            </div>
          </a-form-model-item>

          <!-- 旁路状态 -->
          <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bypassStatus" ref="bypassStatus">
            <span slot="label">
              <span class="red-star-label">*</span>
              旁路状态&nbsp;
              <a-tooltip title="选择对应状态代表的参数值并自定义系统中显示的名称">
                <a-icon type="question-circle-o" />
              </a-tooltip>
            </span>
            <div style="display: flex;align-items: center;">
              <span style="width: 100px;">正常状态：</span>
              <a-input-group compact>
                <a-select v-model="model.bypassYes" style="width: 15%" @change="bypassYesChange">
                  <a-select-option value="0"> 0 </a-select-option>
                  <a-select-option value="1"> 1 </a-select-option>
                </a-select>
                <a-input v-model="model.bypassYesName" placeholder="请输入该状态系统中显示名称" @change="onStatusChange('bypassStatus')" style="width: 85%"/>
              </a-input-group>
            </div>
            <div style="display: flex;align-items: center;">
              <span style="width: 100px;">故障状态：</span>
              <a-input-group compact>
                <a-select v-model="model.bypassNo" style="width: 15%" @change="bypassNoChange">
                  <a-select-option value="0"> 0 </a-select-option>
                  <a-select-option value="1"> 1 </a-select-option>
                </a-select>
                <a-input v-model="model.bypassNoName" placeholder="请输入该状态系统中显示名称" @change="onStatusChange('bypassStatus')" style="width: 85%"/>
              </a-input-group>
            </div>
          </a-form-model-item>

          <!-- 仪表状态(位号读取) -->
          <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="instrumentStatus" ref="instrumentStatus">
            <span slot="label">
              <span class="red-star-label">*</span>
              仪表状态&nbsp;
              <a-tooltip title="选择对应状态代表的参数值并自定义系统中显示的名称">
                <a-icon type="question-circle-o" />
              </a-tooltip>
            </span>
            <div style="display: flex;align-items: center;">
              <span style="width: 100px;">正常状态：</span>
              <a-input-group compact>
                <a-select v-model="model.instrumentStatusNormal" style="width: 15%" @change="instrumentNormalChange">
                  <a-select-option value="0"> 0 </a-select-option>
                  <a-select-option value="1"> 1 </a-select-option>
                </a-select>
                <a-input v-model="model.instrumentStatusNormalName" placeholder="请输入该状态系统中显示名称" @change="onStatusChange('instrumentStatus')" style="width: 85%"/>
              </a-input-group>
            </div>
            <div style="display: flex;align-items: center;">
              <span style="width: 100px;">故障状态：</span>
              <a-input-group compact>
                <a-select v-model="model.instrumentStatusAbnormal" style="width: 15%" @change="instrumentAbnormalChange">
                  <a-select-option value="0"> 0 </a-select-option>
                  <a-select-option value="1"> 1 </a-select-option>
                </a-select>
                <a-input v-model="model.instrumentStatusAbnormalName" placeholder="请输入该状态系统中显示名称" @change="onStatusChange('instrumentStatus')" style="width: 85%"/>
              </a-input-group>
            </div>
          </a-form-model-item>

          <!-- 联锁状态 -->
          <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="interlockStatus" ref="interlockStatus">
            <span slot="label">
              <span class="red-star-label">*</span>
              联锁状态&nbsp;
              <a-tooltip title="选择对应状态代表的参数值并自定义系统中显示的名称">
                <a-icon type="question-circle-o" />
              </a-tooltip>
            </span>
            <div style="display: flex;align-items: center;">
              <span style="width: 100px;">正常状态：</span>
              <a-input-group compact>
                <a-select v-model="model.interlockStatusTy" style="width: 15%" @change="interlockTyChange">
                  <a-select-option value="0"> 0 </a-select-option>
                  <a-select-option value="1"> 1 </a-select-option>
                </a-select>
                <a-input v-model="model.interlockStatusTyName" placeholder="请输入该状态系统中显示名称" @change="onStatusChange('interlockStatus')" style="width: 85%"/>
              </a-input-group>
            </div>
            <div style="display: flex;align-items: center;">
              <span style="width: 100px;">故障状态：</span>
              <a-input-group compact>
                <a-select v-model="model.interlockStatusWty" style="width: 15%" @change="interlockWtyChange">
                  <a-select-option value="0"> 0 </a-select-option>
                  <a-select-option value="1"> 1 </a-select-option>
                </a-select>
                <a-input v-model="model.interlockStatusWtyName" placeholder="请输入该状态系统中显示名称" @change="onStatusChange('interlockStatus')" style="width: 85%"/>
              </a-input-group>
            </div>
          </a-form-model-item>
        </template>
      </a-form-model>
    </a-spin>
  </j-modal>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'
  import {initDictOptions, filterDictText} from '@/components/dict/JDictSelectUtil'
  export default {
    name: "InterlockBaseModal",
    components: { 
    },
    data () {
      return {
        title:"操作",
        width:800,
        visible: false,
        disableEdit: false,
        model:{
          // 设置默认值
          interlockType: '0',
          systemType: '0',

          controlSystemStatusNormal: '0', // 控制系统正常状态
          controlSystemStatusAbnormal: '1',
          controlSystemStatusNormalName: '正常',
          controlSystemStatusAbnormalName: '非正常',
          
          bypassYes	: '0', // 旁路正常状态
          bypassNo: '1',
          bypassYesName: '非旁路',
          bypassNoName: '旁路',

          instrumentStatusNormal: '1', // 仪表正常状态
          instrumentStatusAbnormal: '0',
          instrumentStatusNormalName: '正常',
          instrumentStatusAbnormalName: '非正常',

          interlockStatusTy: '1', // 联锁正常状态
          interlockStatusWty: '0',
          interlockStatusTyName: '投用',
          interlockStatusWtyName: '未投用',

        },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },

        confirmLoading: false,
        validatorRules: {
          interlockType: [{required: true, message: '请选择类型'}],
          interlockName: [
            {required: true, message: '请输入名称'},
            { validator: (rule, value, callback) => validateDuplicateValue('interlock_base', 'interlock_name', value, this.model.id, callback)},
          ],
          pid: [{required: true, message: '请选择上级'}],
          controlSystemStatus: [
            {
              validator: (rule, value, callback) => {
                if(!this.model.controlSystemStatusNormal || !this.model.controlSystemStatusAbnormal || !this.model.controlSystemStatusNormalName || !this.model.controlSystemStatusAbnormalName){
                  callback(new Error('控制系统状态未全部设置'));
                } else {
                  callback()
                }
              },
              trigger: ['blur', 'change']
            },
          ],
          bypassStatus: [
            // {required: true, message: '请设置控制系统状态'},
            {
              validator: (rule, value, callback) => {
                if(!this.model.bypassYes || !this.model.bypassNo || !this.model.bypassYesName || !this.model.bypassNoName){
                  callback(new Error('旁路状态未全部设置'));
                } else {
                  callback()
                }
              },
              trigger: ['blur', 'change']
            },
          ],
          instrumentStatus: [
            {
              validator: (rule, value, callback) => {
                if(!this.model.instrumentStatusNormal || !this.model.instrumentStatusAbnormal || !this.model.instrumentStatusNormalName || !this.model.instrumentStatusAbnormalName){
                  callback(new Error('仪表状态未全部设置'));
                } else {
                  callback()
                }
              },
              trigger: ['blur', 'change']
            },
          ],
          interlockStatus: [
            {
              validator: (rule, value, callback) => {
                if(!this.model.interlockStatusTy || !this.model.interlockStatusWty || !this.model.interlockStatusTyName || !this.model.interlockStatusWtyName){
                  callback(new Error('联锁状态未全部设置'));
                } else {
                  callback()
                }
              },
              trigger: ['blur', 'change']
            },
          ],
        },
        url: {
          // add: "/base/interlockBase/add",
          add: "/iotedgeCollectData/iotedgeCollectData/addGroup",
          // edit: "/base/interlockBase/edit",
          edit: "/iotedgeCollectData/iotedgeCollectData/updateGroup",
          lever12: '/base/interlockBase/lever12',
          interLockSelect: '/sys/dict/loadTreeData',
          getSystemValue: '/sys/dict/getDictItems/system_value_set',
        },
        expandedRowKeys:[],
        pidField:"pid",
        // 装置和系统树
        interlockTwoTree: [],
        // 系统点位值列表
        systemValueOptions: [],
        // 系统类别dict
        systemTypeDicts: [],
      }
    },
    created () {
      // this.initDictConfig()
      //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      // initDictConfig() {
      //   //初始化字典 - 系统类别：原是3个还有个其他，后来需求改变了不需要过滤处理了
      //   initDictOptions('system_type').then((res) => {
      //     console.log(res)
      //     if (res.success) {
      //       this.systemTypeDicts = res.result.filter(item => item.value<2);
      //     }
      //   });
      // },
      // 父级节点-装置改变时
      pidChange(e, option){
        console.log(e, option)
      },
      // 输入框内容变化时调用对应的检验
      onStatusChange(ref){
        this.$refs[ref].onFieldChange()
      },
      // 参数值选择改变时
      controlNormalChange(e){
        this.model.controlSystemStatusAbnormal = e === '0' ? '1' : '0'
      },
      controlAbnormalChange(e){
        this.model.controlSystemStatusNormal = e === '0' ? '1' : '0'
      },
      bypassYesChange(e){
        this.model.bypassNo = e === '0' ? '1' : '0'
      },
      bypassNoChange(e){
        this.model.bypassYes = e === '0' ? '1' : '0'
      },
      instrumentNormalChange(e){
        this.model.instrumentStatusAbnormal = e === '0' ? '1' : '0'
      },
      instrumentAbnormalChange(e){
        this.model.instrumentStatusNormal = e === '0' ? '1' : '0'
      },
      interlockTyChange(e){
        this.model.interlockStatusWty = e === '0' ? '1' : '0'
      },
      interlockWtyChange(e){
        this.model.interlockStatusTy = e === '0' ? '1' : '0'
      },
      // 获取系统点位值设置数据
      getSystemValue(){
        getAction(this.url.getSystemValue).then(res => {
          if(res.success){
            this.systemValueOptions = res.result
          }
        })
      },
      // change(e){
      //   console.log(e)
      //   var index = this.systemValueOptions.findIndex(item => item.value === e)
      //   console.log(this.separateNumbersAndSymbols(this.systemValueOptions[index].label))
      // },
      // // 拆分数字和文字方法
      // separateNumbersAndSymbols(input) {
      //   let numbers = [];
      //   let words = [];
      //   // 使用正则表达式分割字符串
      //   let parts = input.split(/(\d+)/)
      //   // 循环处理分割结果
      //   parts.forEach(part => {
      //     if (part.match(/\d+/)) { // 匹配数字
      //       numbers.push(Number(part));
      //     } else if (part) { // 匹配非数字符号
      //       words.push(part);
      //     }
      //   });
      //   return { numbers, words };
      // },
      // getInterlockTwoTree(){
      //   getAction(this.url.lever12).then(res => {
      //     console.log(res)
      //     this.interlockTwoTree = res
      //   })
      // },
      // 获取装置/系统/联锁数据--默认获取装置数据
      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
          }
        })
      },
      add (obj) {
        // this.getInterlockTwoTree()
        this.getData('0', 'interlockTwoTree')
        // this.getSystemValue()
        this.modelDefault.pid=''
        this.edit(Object.assign(this.modelDefault , obj));
      },
      edit (record) {
        // this.getInterlockTwoTree()
        this.getData('0', 'interlockTwoTree')
        // this.getSystemValue()
        this.model = Object.assign({}, record);
        // this.model.pid = {key: record.key}
        this.model.controlSystemStatusAbnormal = this.model.controlSystemStatusNormal === '0' ? '1' : '0'
        this.model.bypassNo = this.model.bypassYes === '0' ? '1' : '0'
        this.model.instrumentStatusAbnormal = this.model.instrumentStatusNormal === '0' ? '1' : '0'
        this.model.interlockStatusWty = this.model.interlockStatusTy === '0' ? '1' : '0'
        this.visible = true;
      },
      close () {
        this.$emit('close');
        this.visible = false;
        this.$refs.form.clearValidate()
      },
      handleOk () {
        var _this = this
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            _this.$confirm({
              title: '提示',
              content: '是否确定提交',
              okButtonProps: {
                style: {
                  backgroundColor: '#008cd6',
                  fontSize: '16px',
                }
              },
              cancelButtonProps: {
                style: {
                  fontSize: '16px',
                }
              },
              onOk() {
                _this.submit()
              },
              onCancel() {},
            });
          }else{
             return false
          }
        })
      },
      submit(){
        this.confirmLoading = true;
        let httpurl = '';
        let method = '';
        if(!this.model.id){
          httpurl+=this.url.add;
          method = 'post';
        }else{
          httpurl+=this.url.edit;
            method = 'put';
        }
        if(this.model.id && this.model.id === this.model[this.pidField]){
          this.$message.warning("父级节点不能选择自己");
          this.confirmLoading = false;
          return;
        }
        if(this.model.interlockType === '1'){
          var index = this.interlockTwoTree.findIndex(item => item.key === this.model.pid)
          this.model.groupName = this.interlockTwoTree[index].title + '_' + this.model.interlockName
        }
        // console.log(this.model.groupName)
        httpAction(httpurl,this.model,method).then((res)=>{
          if(res.success){
            this.$message.success(res.message);
            this.$emit('ok');
          }else{
            this.$message.warning(res.message);
          }
        }).finally(() => {
          this.confirmLoading = false;
          this.close();
        })
      },
      handleCancel () {
        this.close()
      },
    }
  }
</script>
<style lang="less">
  .red-star-label{
    margin-right: 4px;
    color: #ff4d4f;
    font-size: 14px;
    font-family: SimSun, sans-serif;
    line-height: 1;
  }
</style>