<template>

  <el-dialog
    v-model="visible"
    width="650"
    :before-close="handleClose"
  >
  <el-form :model="formData" :rules="formRules">
    <el-row class="data-category">{{message}}</el-row>
    <el-row>
      <el-input maxlength="64" show-word-limit v-model="formData.search"></el-input><el-button @click="handleSearch">搜索</el-button></el-row> 
    <!-- <el-row>
      <el-form-item prop="linkDirection">
      <el-radio v-model="formData.linkDirection" label="1">被融合（选择节点被替换）</el-radio>
      <el-radio v-model="formData.linkDirection" label="2">融合（当前节点被替换）</el-radio>
      </el-form-item>
    </el-row> -->
    <el-row class="props-content">
      <el-checkbox :indeterminate="formData.isIndeterminate" v-model="formData.checkAll" @change="handleCheckAllChange">全选</el-checkbox>
      <div style="margin: 15px 0;"></div>
      
      <el-form-item prop="selectedNodes">
        <el-checkbox-group v-model="formData.selectedNodes" class="checkbox-content" >
          <el-checkbox style="width:220px" v-for="item in formData.nodes" :value="item.id" :key="item.id">{{item.name}}({{item.category}})</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-row>
  </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">保 存</el-button>
      </span>
    </template>
  </el-dialog>

</template>
 
<script setup lang="ts">

import { ref, watch, toRefs, onMounted} from 'vue';
import r from '@/utils/request.ts';
import { ElMessageBox, ElNotification } from 'element-plus';
/**********emits**********/
const emit = defineEmits(['update:modelValue', 'confirm', 'cancel','server-saved']);

/**********props**********/
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: '确认操作'
  },
  data: {
    type: Object,
    default: {},
  },
  nodes: {
    type: Object,
    default: {},
  },
  message: {
    type: String,
    default: '您确定要执行此操作吗？'
  },
});

/**********props_watch**********/
watch(() => props.modelValue, (newValue) => {
console.log("watch modelValue");
visible.value = newValue;
});
watch(()=>props.data,(newvalue, oldvalue)=>{
console.log("watch data");
formData.value.name = '';
formData.value.id = 0;
formData.value.category = newvalue.category;
formData.value.name = newvalue.name;
formData.value.selectedNodes = [];
});

watch(()=>props.nodes,(newvalue, oldvalue)=>{
console.log("watch nodes");
formData.value.nodes = newvalue;
});
const handleClose = (done) => {
emit('update:modelValue', false);
done();
};

/**********ui_data**********/
const visible = ref(props.modelValue);
const formData = ref({
id: 0,
category: "",
name: "",
status: 0,
search: "",
nodes: [],
linkDirection: "2",
checkAll: false,    
isIndeterminate: true,
selectedNodes: []
});
const formRules = ref({
linkType: [{required: true, message:"链接类型必须选择", trigger:"blur"}],
});
/**********ui_handler**********/
function handleCheckAllChange(val) {
formData.value.selectedNodes = val ? props.nodes.map((data,index)=>{ return data.id;}) : [];
formData.value.isIndeterminate = false;
};
function handleCheckedCitiesChange(value) {
let checkedCount = value.length;
this.checkAll = checkedCount === data.nodes.length;
this.isIndeterminate = checkedCount > 0 && checkedCount < data.nodes.length;
}
const handleSearch = () =>{
const response = r.request<string[]>({
    url: "/api/nodes/search/"+formData.value.search+"/0/1",
    method: "get"
  });
response.then(result => {    
  formData.value.nodes = result["nodes"];    
});
}
const handleConfirm = () => {  
  var targetValidate = false;
  if (formData.value.linkDirection == "2" ){
    //替换候选的对象，可以替换多个
    if (formData.value.selectedNodes.length > 0){
      targetValidate = true;
    }
  }
  
  if (formData.value.linkDirection == "1" ){
    //被候选对象替换，仅允许被1个替换    
    if (formData.value.selectedNodes.length == 1 ){
      targetValidate = true;
    }
  }
  if (targetValidate == false){
      ElMessageBox.alert(
        '替换模式下，至少需要选择一个目标；被替换模式下，仅可以选择一个目标',
        '警告',
        {
          confirmButtonText: '确定',
          callback: action => {
            console.log(action)
          }
        }
      );
      return;
  }
  var requestData = [];
  var mergeData = {
    src_id: 0,
    dest_id: 0,
  }
  
  formData.value.selectedNodes.forEach((value)=>{      
    mergeData.src_id = props.data.id;
    mergeData.dest_id = value;
    if (formData.value.linkDirection == "1"){  
      mergeData.dest_id = props.data.id;
      mergeData.src_id = value;
    }
    requestData.push({...mergeData})
  });
  const response = r.request<string[]>({
    url: "/api/node-merge",
    method: "post",
    data: requestData,
  });
  response.then(result => {
    if (result.error_code == 0){
      ElNotification({
        title: '成功',
        message: '链接已经成功创建了',
        type: 'success'
      });
      emit('server-saved', result.edges);        
      emit('created');
    } else {
      ElNotification({
        title: '失败',
        message: '链接创建失败 '+ result.error_msg,
        type: 'error'
      });

    }      
    emit('update:modelValue', false);
  });
};

const handleCancel = () => {
  emit('cancel');
  emit('update:modelValue', false);
  visible.value = false;
};

/**********vue_event_handler**********/
onMounted( ()=>{



});



/**********vue_export_def**********/
const openDialog = ()=>{
//visible.value = true;
}

defineExpose({openDialog});
</script>
 
<style scoped>
.data-category{
  width: 600px;
  font-size: 18pt;
  color:rgb(3, 57, 123);
  font-weight: 800;
  justify-content: center;
  margin-bottom: 10px;
}
.data-name{
margin: 5px;
display: flex;
flex-direction: column;
width: 580px;
}

.props-content{
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: flex-start;
  overflow-y: auto;
}

.checkbox-content{
  width: 600px;  
  height: 300px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: flex-start;
  overflow-y: auto;
}
.data-prop{
margin: 5px;
width: 600px;
display: flex;
flex-direction: column;
}
.prop-name{
background-color: #efefef;
color:rgb(11, 117, 247);
width:580px;
}
.data-text{
width: 580px;
background-color: #efefef;
}
</style>