<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="callType">
          <el-select v-model="propertyForm.callType" placeholder="请选择外呼类型" style="width: 100%" @change="callTypeChange">
            <el-option v-for="item in callTypes" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item v-if="propertyForm.callType == '1'" label="通知内容" prop="content">
          <el-input v-model="propertyForm.content" type="textarea" :rows="3"> </el-input>
        </el-form-item>
        <el-form-item v-else label="选择问卷" prop="content">
          <el-select v-model="propertyForm.content" placeholder="请选择短信模板" style="width: 100%" @change="surveyChange">
            <el-option v-for="item in surveyList" :key="item.surveyId" :label="item.title" :value="item.surveyId"/>
          </el-select>
        </el-form-item>
        <el-form-item v-if="propertyForm.callType == '2'" label="标签" prop="tags">
        <el-tabs style="width: 100%" type="card" v-model="activeName" editable class="demo-tabs mt-4"
          @edit="handleTabsEdit">
          <el-tab-pane v-for="(item, index) in propertyForm.tags" :key="index" :label="item.name" :name="item.name">
            <div style="margin: 10px 0;">
              <el-switch v-model="item.alter"  inline-prompt
              active-text="提醒开启"
                inactive-text="提醒关闭"/>
              <el-select
               v-if="item.alter"
                v-model="item.alterUsers"
                filterable
                remote
                reserve-keyword
                placeholder="请输入姓名查询"
                :remote-method="remoteMethod"
                :loading="loading"
                style="margin-left: 10px;width: 200px;"
              >
                <el-option
                  v-for="item in userOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>

            <el-table :data="item.filters" style="width: 100%" max-height="250">
              <el-table-column fixed prop="title" label="题干" width="200">
                <template #default="scope">

                  <el-select v-if="item.name === activeName && scope.$index === clickRow" v-model="scope.row.id"
                    size="small" placeholder="请选择试题" style="width: 100%" @change="questionChange(index, scope.$index)">
                    <el-option v-for="qitem in questions" :key="qitem.questionId" :label="qitem.title"
                      :value="qitem.questionId" />
                  </el-select>

                  <span v-else>{{ scope.row.title }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="options" label="答案" width="150">
                <template #default="scope">
                  <el-select
                    v-if="scope.row.id && ['单选', '多选'].includes(scope.row.type) && item.name === activeName && scope.$index === clickRow"
                    v-model="scope.row.options" multiple size="small" placeholder="请选择选项" style="width: 100%">
                    <el-option v-for="oitem in questionMap[scope.row.id].optionViewList" :key="oitem.optionId"
                      :label="`${oitem.optionname}. ${oitem.optiondetail}`" :value="oitem.optionId" />
                  </el-select>
                  <el-input
                    v-if="scope.row.id && ['填空'].includes(scope.row.type) && item.name === activeName && scope.$index === clickRow"
                    v-model="scope.row.options" clearable size="small">
                    {{ scope.row.options.join('') }}
                  </el-input>
                  <span v-if="item.name === activeName && scope.$index !== clickRow">{{ getOptionText(scope.row.id, scope.row.options) }}</span>
                </template>

              </el-table-column>
              <el-table-column fixed="right" label="操作" min-width="50">
                <template #default="scope">
                  <el-button link type="danger" size="small" @click.prevent="deleteRow(index, scope.$index)">
                    删除
                  </el-button>

                  <el-button v-if="item.name === activeName && scope.$index === clickRow" link type="primary"
                    size="small" @click.prevent="saveFilter(index, scope.$index)">
                    保存
                  </el-button>
                  <el-button v-if="item.name === activeName && scope.$index !== clickRow" link type="error" size="small"
                    @click.prevent="clickRow = scope.$index">
                    编辑
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-button class="mt-4" style="width: 100%" @click="onAddItem(index)">
              新增条件
            </el-button>
          </el-tab-pane>
        </el-tabs>
      </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>

      <!-- 打标弹框 -->
    <el-dialog v-model="tagDialogVisible" title="保存计划" width="500" center>
      <div>
        <el-form :model="tagForm" label-width="auto" style="max-width: 500px">
          <el-form-item label="名称">
            <el-input v-model="tagForm.name" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="tagDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveTag">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
    </div>
  </template>
  <script setup lang="ts">
  import { ref, onMounted, reactive } from 'vue';
  import { getPageListData } from '@/api/main/system/system';
  import { ElMessage } from 'element-plus'
  import { arrayToMap } from '@/utils/index'

  const callTypes = [{
    label: '通知',
    value: '1'
  }, {
    label: '问卷对话',
    value: '2'
  }]

  const activeName = ref('')

  const tagDialogVisible = ref(false);
  const tagForm = reactive({
    name: '',
  });
  const saveTag = () => {
    if (tagForm.name == '') {
      ElMessage.error('请输入标签名称');
      return;
    }
    if (propertyForm.tags.length >= 4) {
      ElMessage.error('最多添加4个标签');
      return;
    }
    if (propertyForm.tags.some((item) => item.name == tagForm.name)) {
      ElMessage.error('标签名称已存在');
      return;
    }
    activeName.value = tagForm.name;
    propertyForm.tags.push({
      name: tagForm.name,
    });
    tagDialogVisible.value = false;
  };

  const props: any = defineProps({
    nodeData: Object,
    lf: Object || String,
    //详情
    flowDetail: {
      type: Object,
      default: () => {
        return {};
      },
    },
    optionType: {
      type: String,
    },
    
  });
  const emit: any = defineEmits();
  
  let propertyForm: any = reactive({
    name: '',
    desc: '',
    callType: '',
    content: '',
    tags: [] as any,
    assignList: [],
  });
  let rules = reactive({
    name: [
      { required: true, message: '名称不能为空' },
      {
        max: 50,
        message: '最大50字符',
      },
    ],
    desc: [
      {
        max: 50,
        message: '最大50字符',
      },
    ],
    callType: [
      { required: true, message: '请选择外呼类型' },
    ],
    content: [
      { required: true, message: '通知内容不能为空' },
    ]
  });
  let showGlobalContext = ref(false);
  let globalContextFlag = ref('');
  let tableIndex = ref(null);
  let propertyFormRef: any = ref(null);
  
  //更新节点属性
  const setProperties = () => {
    props.lf.setProperties(props.nodeData.id, {
      name: propertyForm.name,
      desc: propertyForm.desc,
      callType: propertyForm.callType,
      content: propertyForm.content,
      tags: propertyForm.tags,
      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 surveyList: any = ref([]);

  const getSurveyList = () => {
    getPageListData('/survey/survey/getGoingList', {}).then((res) => {
      if (res.data) surveyList.value = res.data;
    });
  };
  
  const callTypeChange = () => {
    propertyForm.content = '';
  }


  const clickRow = ref(-1);
  const questionMap = ref({});
  const questions: any = ref([]);
  const getQuestions = () => {
    getPageListData('/survey/survey/getdetail', {
      id: propertyForm.content,
    }).then((res) => {
      if (res.data) {
        questions.value = res.data.questionlist;
        questionMap.value = arrayToMap(res.data.questionlist, 'questionId');
      }
    });
  }

  const getOptionText = (qid, options) => {
    const que = questionMap.value[qid];
    let str = '';
    if (que && ['单选', '多选'].includes(que.type)) {
      que.optionViewList.forEach((item) => {
        if (options.includes(item.optionId)) {
          if (str) str += '/';
          str += item.optiondetail;
        }
      })
    } else if (que && que.type === '填空') {
      str = options.join('/');
    }

    return str;
  }

  const surveyChange = () => {
    if (propertyForm.callType === '2') {
      if (propertyForm.content) getQuestions();
      else {
        questions.value = [];
        questionMap.value = {};
      }
    }
  }

  // 试题切换事件
  const questionChange = (tagIndex, tableIndex) => {
    const que = propertyForm.tags[tagIndex].filters[tableIndex];
    if (que.id) {
      que.title = questionMap.value[que.id].title;
      que.type = questionMap.value[que.id].type;
      que.options = [];
    }
  }

  const saveFilter = (tagIndex, tableIndex) => {
    let que = propertyForm.tags[tagIndex].filters[tableIndex];
    if (que.id && typeof que.options === 'string') {
      que.options = [que.options];
    }
    clickRow.value = -1;
  }

  const deleteRow = (tagIndex, tableIndex) => {
    propertyForm.tags[tagIndex].filters = propertyForm.tags[tagIndex].filters.filter((item, index) => index !== tableIndex);
  }

  const onAddItem = (index) => {
    if (!propertyForm.tags[index].filters) propertyForm.tags[index].filters = [];
    
    propertyForm.tags[index].filters.push({
      id: '',
      title: '',
      options: [],
    })
    clickRow.value = propertyForm.tags[index].filters.length - 1;
  }

  const handleTabsEdit = ref((targetName, action) => {
    if (action === 'add') {
      tagDialogVisible.value = true;
    } else if (action === 'remove') {
      let tabs = propertyForm.tags;
      let activeNameStr = activeName.value
      if (activeNameStr === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            const nextTab = tabs[index + 1] || tabs[index - 1]
            if (nextTab) {
              activeNameStr = nextTab.name
            }
          }
        })
      }

      activeName.value = activeNameStr
      propertyForm.tags = tabs.filter((tab) => tab.name !== targetName)
    }
  })

  const loading = ref(false)
  const userOptions: any = ref([])

  const remoteMethod = (query, type) => {
    loading.value = true
    const params: any = {
      pageNum: 1,
      pageSize: 5,
      status: 1,
    }

    if (type == 'id') {
      params.id = query
    } else {
      params.nickName = query
    }
    getPageListData('/system/user', params).then(res => {
      userOptions.value = res.data.map(item => {
        return {
          value: item.userId,
          label: `${item.nickName}(${item.userName})`,
        }
      })

      loading.value = false
    }).catch(err => {
      loading.value = false
    })
  }

  onMounted(() => {
    getSurveyList()
    propertyForm.name = props.nodeData.properties.name;
    propertyForm.desc = props.nodeData.properties.desc ? props.nodeData.properties.desc : '';
    propertyForm.callType = props.nodeData.properties.callType ? props.nodeData.properties.callType : '';
    propertyForm.content = props.nodeData.properties.content ? props.nodeData.properties.content : '';
    propertyForm.tags = props.nodeData.properties.tags ? props.nodeData.properties.tags : [];
    if (propertyForm.content && propertyForm.callType === '2') {
      getQuestions();
    }

    if (propertyForm.tags && propertyForm.tags.length > 0) {
      activeName.value = propertyForm.tags[0].name;
    }
  });
  </script>
  <style scoped></style>
  