<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="type">
        <el-select v-model="propertyForm.attr.type" placeholder="请选择类型" clearable>
          <el-option label="本地语音" value="audio"></el-option>
          <el-option label="文本" value="text"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="欢迎语">
        <el-input v-model="propertyForm.attr.content" type="textarea" :rows="3"
          v-if="propertyForm.attr.type === 'text'" />

        <el-upload v-if="propertyForm.attr.type === 'audio'" :on-success="(data) => clUploadSucc(data, 'file')" :limit="'1'"
          :headers="uploadHeadData" ref="uploadRef" accept=".mp3,.wav" class="upload-demo"
          :action="`${baseUrl}system/accessories/upload`" :show-file-list="false">
          <template #trigger>
            <div>
              <el-button link text type="primary" style="margin-right: 20px;">{{ propertyForm.attr.file ? '更换音频' :
                '上传音频' }}</el-button>
              <span v-if="propertyForm.attr.file" style="color: darkgray;">{{ propertyForm.attr.file.split('/').at(-1) }}</span>
              <span v-else style="color: darkgray;">上传文件格式为.mp3,.wav，大小不能超过200kb</span>

            </div>
          </template>
        </el-upload>
      </el-form-item>

      <el-form-item label="提示语">
        <el-input v-model="propertyForm.attr.greetShort" type="textarea" :rows="3"
          v-if="propertyForm.attr.type === 'text'" />

        <el-upload v-if="propertyForm.attr.type === 'audio'" :on-success="(data) => clUploadSucc(data, 'greetShortUrl')" :limit="'1'"
          :headers="uploadHeadData" ref="uploadRef" accept=".mp3,.wav" class="upload-demo"
          :action="`${baseUrl}system/accessories/upload`" :show-file-list="false">
          <template #trigger>
            <div>
              <el-button link text type="primary" style="margin-right: 20px;">{{ propertyForm.attr.greetShortUrl ? '更换音频' :
                '上传音频' }}</el-button>
              <span v-if="propertyForm.attr.greetShortUrl" style="color: darkgray;">{{ propertyForm.attr.greetShortUrl.split('/').at(-1) }}</span>
              <span v-else style="color: darkgray;">上传文件格式为.mp3,.wav，大小不能超过200kb</span>

            </div>
          </template>
        </el-upload>
      </el-form-item>

      <el-form-item label="退出菜单提示音">
        <el-input v-model="propertyForm.attr.xitSound" type="textarea" :rows="3"
          v-if="propertyForm.attr.type === 'text'" />

        <el-upload v-if="propertyForm.attr.type === 'audio'" :on-success="(data) => clUploadSucc(data, 'xitSoundUrl')" :limit="'1'"
          :headers="uploadHeadData" ref="uploadRef" accept=".mp3,.wav" class="upload-demo"
          :action="`${baseUrl}system/accessories/upload`" :show-file-list="false">
          <template #trigger>
            <div>
              <el-button link text type="primary" style="margin-right: 20px;">{{ propertyForm.attr.xitSoundUrl ? '更换音频' :
                '上传音频' }}</el-button>
              <span v-if="propertyForm.attr.xitSoundUrl" style="color: darkgray;">{{ propertyForm.attr.xitSoundUrl.split('/').at(-1) }}</span>
              <span v-else style="color: darkgray;">上传文件格式为.mp3,.wav，大小不能超过200kb</span>

            </div>
          </template>
        </el-upload>
      </el-form-item>

      <el-form-item label="错误按键提示音">
        <el-input v-model="propertyForm.attr.invalidSound" type="textarea" :rows="3"
          v-if="propertyForm.attr.type === 'text'" />

        <el-upload v-if="propertyForm.attr.type === 'audio'" :on-success="(data) => clUploadSucc(data, 'invalidSoundUrl')" :limit="'1'"
          :headers="uploadHeadData" ref="uploadRef" accept=".mp3,.wav" class="upload-demo"
          :action="`${baseUrl}system/accessories/upload`" :show-file-list="false">
          <template #trigger>
            <div>
              <el-button link text type="primary" style="margin-right: 20px;">{{ propertyForm.attr.invalidSoundUrl ? '更换音频' :
                '上传音频' }}</el-button>
              <span v-if="propertyForm.attr.invalidSoundUrl" style="color: darkgray;">{{ propertyForm.attr.invalidSoundUrl.split('/').at(-1) }}</span>
              <span v-else style="color: darkgray;">上传文件格式为.mp3,.wav，大小不能超过200kb</span>

            </div>
          </template>
        </el-upload>
      </el-form-item>

      <el-form-item label="按键超时时间（毫秒）">
        <el-input v-model="propertyForm.attr.timeout" :min="0" :max="60000" type="number" />
      </el-form-item>

      <el-form-item label="最大按键错误次数">
        <el-input v-model="propertyForm.attr.maxFailures" :max="10" :min="0" type="number" />
      </el-form-item>

      <el-form-item label="最大超时次数">
        <el-input v-model="propertyForm.attr.maxTimeouts"  :max="10" :min="0" type="number" />
      </el-form-item>

      <el-form-item label="按键" prop="attr">
        <div class="keyboard">
          <div @click="keyClick(item)" :class="{'checked': propertyForm.anchors.findIndex((o) => {
            return o.text === item
          }) >= 0 }" v-for="(item, index) in ['1', '2', '3', '4', '5', '6', '7', '8', '9', '*', '0', '#']" :key="index">{{ item }}</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 { getToken } from '@/utils/auth';
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();
const uploadHeadData = ref({ Authorization: `Bearer ${getToken()}` });
const baseUrl = import.meta.env.VITE_APP_BASE_API;

let propertyForm = reactive({
  name: '',
  desc: '',
  attr: {
    type: 'audio',
    content: '',
    file: '',
    greetShortUrl: '',
    greetShort: '', // 该项指定一个简短的提示音。如果用户长时间没有按键，则应重新提示拨号，但重新提示应该简短，比如直接说“请直拨分机号，查号请拨0”，而不用再把公司的欢迎广告再重复播放一遍。所以，可以把这么一个声音文件录制到welcome_short.wav中。
    xitSoundUrl: '',
    xitSound: '', // 该项指定最后菜单退出时（一般是超时没有按键）的声音，默认会提示“Good Bye”。
    invalidSoundUrl: '',
    invalidSound: '', // 如果用户按错了键，则会使用该提示
    timeout: 30000, // 指定超时时间（毫秒），即多长时间没有收到按键就超时，播放其他提示音。
    maxFailures: 3, // 为容忍用户按键错误的次数。如果用户的按键与下面配置的正则表达式不匹配（即没有找到相关的菜单项），就认为是错误的。
    maxTimeouts: 3, // 即最大超时次数。
  },
  anchors: [],
});

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

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, {
    ...propertyForm,
    frontend_status: '1', //0配置错误，1配置正常
  });
};

const keyClick = (key) => {
  const index = propertyForm.anchors.findIndex((o) => { return o.text === key });
  if (index > -1) {
    // 移除
    propertyForm.anchors.splice(index, 1);
  } else {
    // 添加
    propertyForm.anchors.push({
      id: randomNumber(),
      text: key,
      checked: true,
      isDefault: false,
      outParams: {
        type: 'audiodtmf',
        // field: branchParams.info.field,
        // case: branchParams.model.case,
        expression: key,
      },
    });
  }
}

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

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

const saveFilter = (tagIndex, tableIndex) => {
  
  clickRow.value = -1;
}

const deleteRow = (tagIndex, tableIndex) => {
  vars = vars.filter((item, index) => index !== tableIndex);
}

const onAddItem = (index) => {
  if (!vars) vars = [];

  vars.push({
    key: '',
    value: ''
  })
  clickRow.value = vars.length - 1;
}

const clUploadSucc = ({state, data}, field = 'file') => {
  if (state === 'success') {
    console.log(field, 'field');
    propertyForm.attr[`${field}`] = data.url;
    ElMessage.success('上传成功');
  } else {
    ElMessage.error('上传失败');
  }
}
// const getSqlList = () => {
//   getPageListData('/call/ivrsql', {}).then((res) => {
//     if (res.data) sqlList = 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 : {};

  if (!propertyForm.attr.type) propertyForm.attr.type = 'audio';

  // vars = [];
  // for (let key in propertyForm.attr) {
  //   vars.push({
  //     key: key,
  //     value: propertyForm.attr[key]
  //   })
  // }
});
</script>
<style scoped>
.keyboard {
    width: 100%;
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 5px;
    margin: 20px;
  }
  .keyboard div {
    text-align: center;
    font-size: 20px;
    padding: 10px;
    border: none;
    background-color: #f0f0f0;
    cursor: pointer;
    
  }
  .keyboard div.checked {
    background-color: #add8e6;
    
  }
  .keyboard div:hover {
    background-color: #e0e0e0;
  }
  .keyboard div:active {
    background-color: #d0d0d0;
  }
  .keyboard .special {
    grid-column: span 2;
  }
  </style>