<template>
  <div>
    <el-form ref="propertyFormRef" :model="propertyForm" :inline-message="true" :rules="rules" label-position="top"
      :disabled="flowDetail.status == '2'">
      <el-form-item label="节点名称" prop="name">
        <el-input v-model="propertyForm.name" clearable> </el-input>
      </el-form-item>
      <el-form-item label="节点描述" prop="desc">
        <el-input v-model="propertyForm.desc" type="textarea" :rows="2"> </el-input>
      </el-form-item>

      <el-form-item label="查询类型" prop="attr">
        <el-select v-model="propertyForm.attr.id" @change="changeSql" placeholder="请选择" clearable>
          <el-option v-for="(item, index) in sqlList" :key="index" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="分支" prop="anchors" v-if="branchParams.show">
        <div style="width: 100%;">
          <el-checkbox v-for="(item, index) in propertyForm.anchors" :key="index" v-model="item.checked"
            :label="item.text" :disabled="item.isDefault" class="mt10">
            <template #default>
              <el-dropdown :disabled="item.isDefault" placement="top" @command="handleCommand($event, item, index)">
                {{ item.text }} <el-icon class="el-icon--right" style="margin-left: 5px;"><arrow-donw /> </el-icon>
                <template #dropdown>
                  <el-dropdown-item command="edit">编辑</el-dropdown-item>
                  <el-dropdown-item command="delete">删除</el-dropdown-item>
                </template>
              </el-dropdown>
            </template>
          </el-checkbox>

        </div>
        <div v-if="branchParams.showAdd" style="width: 100%;overflow: hidden;">
          <div style="float: left;" v-if="branchParams.addClick">
            <el-select v-model="branchParams.model.case" style="width: 80px;text-align: left;" placeholder="条件">
              <el-option label="等于" value="=">等于</el-option>
              <el-option v-if="['string'].includes(branchParams.type)" label="包含" value="in">包含</el-option>

            </el-select>
            <el-input v-model="branchParams.model.v" style="width: 200px;text-align: left;" v-if="['string'].includes(branchParams.type)"
              placeholder="多个值可用英文逗号分割" />
            <el-input-number v-model="branchParams.model.v" style="width: 100px;text-align: left;" v-if="['number'].includes(branchParams.type)" />
            <el-input v-model="branchParams.model.name" style="width: 100px;text-align: left;" placeholder="备注" />
          </div>
          <div style="float: right;">
            <el-button v-if="!branchParams.addClick" type="primary" link @click="() => { branchParams.addClick = true; branchParams.model = { k: '', case: '', v: '', name: '' }; }"> + 添加分支 </el-button>
            <el-button v-if="branchParams.addClick" type="primary" link @click="addBranch" > 保存分支 </el-button>
          </div>
        </div>
      </el-form-item>

    </el-form>
    <div class="mt15" v-if="flowDetail.status != '2'">
      <el-button @click="cancelFunc"> 取消 </el-button>
      <el-button type="primary" @click="confirmFunc"> 确定 </el-button>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted, reactive } from 'vue';
import { getPageListData } from '@/api/main/system/system';
import { randomNumber } from '@/utils/index';
import { ElMessage } from 'element-plus'

const props = defineProps({
  nodeData: Object,
  lf: Object || String,
  //详情
  flowDetail: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

const clickRow = ref(-1);
const emit = defineEmits();

let propertyForm = reactive({
  name: '',
  desc: '',
  attr: {},
  anchors: [],
  nodeVars: [], // 可使用变量
});

let sqlList = ref([]);
let vars = reactive([]);

const branchParams = reactive({
  addClick: false,
  show: false,
  showAdd: false,
  type: '',
  info: null,
  model: {
    case: '',
    v: '',
    name: '',
  }
});

let rules = reactive({
  name: [
    { required: true, message: '名称不能为空' },
    {
      max: 50,
      message: '最大50字符',
    },
  ],
  desc: [
    {
      max: 50,
      message: '最大50字符',
    },
  ],
  attr: [
    { required: true, message: '请选择查询类型' },
  ],
});
let propertyFormRef = ref(null);

//更新节点属性
const setProperties = () => {
  
  props.lf.setProperties(props.nodeData.id, {
    name: propertyForm.name,
    desc: propertyForm.desc,
    attr: propertyForm.attr,
    anchors: propertyForm.anchors,
    frontend_status: '1', //0配置错误，1配置正常
  });
};

//确定
const confirmFunc = () => {
  propertyFormRef.value.validate((valid) => {
    if (valid) {
      setProperties();
      // props.lf.updateText(props.nodeData.id, propertyForm.name);
      emit('closed');
    }
  });
};

//取消
const cancelFunc = () => {
  emit('closed');
};

const addBranch = () => {
  if (!branchParams.model.case || !branchParams.model.v || !branchParams.model.name) ElMessage.success('请填写完整');

  // 判断是否存在锚点
  const isExist = propertyForm.anchors.find(o => o.text === branchParams.model.name || o.v === branchParams.model.v);
  if (isExist) ElMessage.success('锚点已存在');

  propertyForm.anchors.push({
    id: randomNumber(),
    text: branchParams.model.name,
    checked: true,
    isDefault: false,
    outParams: {
      type: 'sql',
      field: branchParams.info.field,
      case: branchParams.model.case,
      expression: branchParams.model.v,
    },
  });

  branchParams.addClick = false;
}

const changeSql = (val) => {
  branchParams.showAdd = false;
  branchParams.show = true;
  propertyForm.anchors = [];
  if (!val) return;
  let isDefaultName = false;
  let info = sqlList.value.find((o) => {
    if (o.name === propertyForm.desc) isDefaultName = true;
    return o.id == val;
  });
  if (!info || !info.sqlContent) return;
  if (!propertyForm.desc || isDefaultName) propertyForm.desc = info.name;
  if (info?.sqlContent) {
    const { result, field, type } = JSON.parse(info.sqlContent);
    branchParams.type = result?.type;
    branchParams.info = info;
    switch (result?.type) {
      case 'bool': {
        propertyForm.anchors = [{
          id: randomNumber(),
          text: '是',
          checked: true,
          isDefault: true,
          outParams: {
            type: 'sql',
            field,
            type: type,
            expression: 1,
          },

        }, {
          id: randomNumber(),
          text: '否',
          checked: true,
          isDefault: true,
          outParams: {
            type: 'sql',
            field,
            type: type,
            expression: 0
          },
        }];
      } break;
      case 'number':
      case 'string': {
        branchParams.show = true;
        branchParams.showAdd = true;
        // propertyForm.anchors = [{
        //   id: randomNumber(),
        //   text: '默认',
        //   checked: true,
        //   isDefault: true,
        //   outParams: {
        //     type: 'sql',
        //     field,
        //     type: type,
        //     expression: 'other',
        //   },
        // }];
        propertyForm.nodeVars = [{
          name: `${info.name}结果`,
          key: info.code,
          type: result.type,
        }];
      } break;
      default: break;
    }
  }
}

const getSqlList = () => {
  getPageListData('/call/ivrsql', {}).then((res) => {
    console.log('sqlList', res);
    if (res.data) sqlList.value = res.data;
  });
};

onMounted(() => {
  getSqlList();
  propertyForm.name = props.nodeData.properties.name;
  propertyForm.desc = props.nodeData.properties.desc ? props.nodeData.properties.desc : '';
  propertyForm.attr = props.nodeData.properties.attr ? props.nodeData.properties.attr : {};
  propertyForm.anchors = props.nodeData.properties.anchors? props.nodeData.properties.anchors : [];
  console.log('props.nodeData.properties', props.nodeData.properties);

  if (propertyForm.anchors.length) {
    branchParams.show = true;
    branchParams.showAdd = true;
    propertyForm.nodeVars = [{
      name: `${propertyForm.desc}结果`,
      key: propertyForm.attr.id,
      type: propertyForm.anchors[0].outParams.type,
    }];
  }

  // vars = [];
  // for (let key in propertyForm.attr) {
  //   vars.push({
  //     key: key,
  //     value: propertyForm.attr[key]
  //   })
  // }
});
</script>
<style scoped></style>