<template>
  <lay-container style="padding: 20px">
    <lay-card>
      <div style="padding: 10px">
        <span style="font-size: 18px;vertical-align: center;margin-right: 20px">党风廉政教育问卷</span>
        <lay-button type="primary" @click="openNew()" size="sm">新增问卷</lay-button>
      </div>
      <lay-table @change="changePage" :page="page" size="lg" ref="tableRef6" children-column-name="children"
        :columns="columns6" :data-source="dataSource6">
        <template v-slot:operator="{ data }">
          <lay-space size="lg">
            <span style="color: #00A394;cursor: pointer" @click="addShowMsd(data, data.id)">新增题目</span>
            <span style="color: #00A394;cursor: pointer" @click="editShowQuestMsd(data.id)">编辑题目</span>
            <span style="color: #00A394;cursor: pointer" @click="editShowMsd(data)">编辑</span>
            <lay-popconfirm trigger="click" content="确定要删除吗？" @confirm="delShowMsd(data)">
              <span style="color: #00A394;cursor: pointer">删除</span>
            </lay-popconfirm>
          </lay-space>
        </template>
      </lay-table>
    </lay-card>
    <lay-layer v-model="addShow" :title="addIsEdit == 1 ? '新增问卷' : '新增问卷'" :shade="true" :area="['500px', '500px']"
      :btn="addButton">
      <lay-container fluid="true" style="padding: 20px">
        <lay-form :model="addData">
          <lay-form-item required label="问卷标题" prop="title">
            <lay-input v-model="addData.title" placeholder="请输入菜单名称"></lay-input>
          </lay-form-item>
          <lay-form-item required label="问卷简介" prop="title">
            <lay-textarea v-model="addData.materialcontent" placeholder="请输入问卷简介">
            </lay-textarea>
          </lay-form-item>
        </lay-form>
      </lay-container>
    </lay-layer>

    <!-- 新增题目弹窗 -->
    <lay-layer v-model="questionnaireAddMode" title="新增题目" :type="4" :shade="true" :area="['800px', '100%']"
      :btn="questionnaireButton">
      <lay-container fluid="true" style="padding: 20px; overflow-y: auto;">
        <lay-form>
          <lay-card v-for="(item, index) in questionnaireData" :key="index"
            style="margin-bottom: 15px; position: relative;">
            <lay-form-item label="类型">
              <lay-radio v-model="item.type" name="type" :value="1">单选题</lay-radio>
              <lay-radio v-model="item.type" name="type" :value="2">多选题</lay-radio>
              <lay-radio v-model="item.type" name="type" :value="3">问答题</lay-radio>
            </lay-form-item>
            <lay-form-item label="排序">
              <lay-input v-model="item.wight" type="number" placeholder="请输入排序"></lay-input>
            </lay-form-item>
            <lay-form-item label="题目">
              <lay-input v-model="item.title" placeholder="请输入题目"></lay-input>
            </lay-form-item>
            <lay-form-item :label="op.name" v-for="(op, opi) in item.option" :key="opi" v-if="item.type != 3">
              <div style="display: flex;align-items: center;">
                <lay-input v-model="op.val" placeholder="请输入选项答案"></lay-input>
                <lay-button style="margin-left: 10px" type="primary" size="sm" @click="delOptionItem(index, opi)"><lay-icon
                    type="layui-icon-delete"></lay-icon></lay-button>
              </div>
            </lay-form-item>
            <div style="text-align: center" v-if="item.type != 3">
              <lay-button @click="addOption(index)" type="primary" size="sm">添加一个选项</lay-button>
            </div>
            <div style="position: absolute; right: 20px; top: 20px">
              <lay-button @click="delOptionTop(index)" type="danger" size="sm">删除题目</lay-button>
            </div>
          </lay-card>
          <div style="text-align: center; margin-top: 30px">
            <lay-button @click="addQuestionnaire()" type="warm" size="sm">添加一个题目</lay-button>
          </div>
        </lay-form>
      </lay-container>
    </lay-layer>
    <lay-layer title="编辑题目" v-model="questionnaireUpdateMode" :type="4" :shade="true" :area="['800px', '100%']">
      <lay-form>
        <lay-card v-for="(item, index) in questionnaire" style="margin-bottom: 10px;position: relative;">
          <lay-form-item label="类型">
            <lay-radio-group v-model="item.type">
              <lay-radio :value="1">单选题</lay-radio>
              <lay-radio :value="2">多选题</lay-radio>
              <lay-radio :value="3">问答题</lay-radio>
            </lay-radio-group>
          </lay-form-item>
          <lay-form-item label="排序">
            <lay-input v-model="item.wight" placeholder="请输入排序"></lay-input>
          </lay-form-item>
          <lay-form-item label="题目">
            <lay-input v-model="item.title" placeholder="请输入题目"></lay-input>
          </lay-form-item>
          <lay-form-item v-for="(op, opi) in item.option" :label="op.name" v-if="item.type != 3">
            <div style="display: flex;align-items: center;">
              <lay-input v-model="op.val" placeholder="请输入选项答案"></lay-input>
              <lay-button style="margin-left: 10px" type="primary" size="sm" @click="delUpdateOptionItem(index, opi)"><lay-icon
                  type="layui-icon-delete"></lay-icon></lay-button>
            </div>
          </lay-form-item>
          <div style="text-align: center" v-if="item.type != 3">
            <lay-button @click="addUpdateOption(index)" type="warm" size="sm">添加一个选项</lay-button>
          </div>
          <div style="position:absolute;right: 20px;top: 20px">
            <lay-popconfirm content="确认删除吗" @confirm="delUpdateOptionTop(index, item)">
              <lay-button type="danger" size="sm" style="margin-left: 20px">删除题目</lay-button>
            </lay-popconfirm>
          </div>
          <div style="text-align: center;margin-top: 20px">
            <lay-button @click="updateOption(item)" type="primary" size="sm">保存</lay-button>
          </div>
        </lay-card>
      </lay-form>
    </lay-layer>
  </lay-container>
</template>

<script setup lang="ts">
import {
  menuDataAdd,
  menuDataEdit,
  menuDataDel,
  menuData,
  getQuestionnaireIndex,
  getQuestionnaireInfoAdd,
  getQuestionnaireInfoEdit,
  getQuestionnaireInfoFind,
  getQuestionnaireDelete,
  getQuestionnaireAdd,
  getQuestionnaireEdit,
  getQuestionnaireInfoDelete
} from '../../api/module/home' // 确保 API 路径正确
import { ref, watch, onMounted, reactive } from 'vue'
import { layer } from '@layui/layer-vue'
const page = reactive({
  current: 1,
  limit: 10,
  total: 1
});
// 列表内容
const dataSource6 = ref([]);
const addShow = ref(false)
// 1 add  2 edit
const addIsEdit = ref(1)
const addData = reactive({
  title: '',
  materialcontent: ''
})
const questionnaireUpdateMode = ref(false)
// 新增题目相关数据和方法
const questionnaireAddMode = ref(false)
const currentQuestionnaireId = ref(0)
const questionnaireData = ref([{
  type: 1, title: '', wight: 0, option: [{ name: 'A', val: "" }, { name: 'B', val: "" }]
}])
// 初始化一个题目
const initQuestionItem = () => {
  return {
    type: 1,
    wight: 0,
    title: "",
    option: [
      { name: "A", val: "" },
      { name: "B", val: "" }
    ]
  }
}
const questionnaire = ref([]);
const editShowQuestMsd = (id) => {
  questionnaireUpdateMode.value = true;
  getQuestionnaireInfoFind({ id: id }).then((res) => {
    console.log(res);
    if (res.code == 1) {
      questionnaire.value = res.data;
    } else {
      layer.msg(res.msg, { icon: 2 });
    }
  })
}
// 添加一个题目
const addQuestionnaire = () => {
  questionnaireData.value.push(initQuestionItem())
}

// 添加一个选项
const addOption = (index) => {
  const optionLength = questionnaireData.value[index].option.length
  const lastOption = questionnaireData.value[index].option[optionLength - 1]
  const lastChar = lastOption.name.charAt(lastOption.name.length - 1)
  const nextChar = String.fromCharCode(lastChar.charCodeAt(0) + 1)
  questionnaireData.value[index].option.push({
    name: `${nextChar}`,
    val: ""
  })
}
const addUpdateOption = (index) => {
  const optionLength = questionnaire.value[index].option.length
  const lastOption = questionnaire.value[index].option[optionLength - 1]
  const lastChar = lastOption.name.charAt(lastOption.name.length - 1)
  const nextChar = String.fromCharCode(lastChar.charCodeAt(0) + 1)
  questionnaire.value[index].option.push({
    name: `${nextChar}`,
    val: ""
  })
}
// 删除选项
const delOptionItem = (index, opi) => {
  if (questionnaireData.value[index].option.length <= 2) {
    layer.msg('至少需要两个选项', { icon: 2 })
    return
  }
  questionnaireData.value[index].option.splice(opi, 1)
}

// 删除题目
const delOptionTop = (index) => {
  questionnaireData.value.splice(index, 1)
}
const delUpdateOptionTop = (index, item) => {
  console.log(item);
  if (questionnaire.value.length <= 1) {
    layer.msg('至少保留一个题目', { icon: 2 });
    return;
  }
  questionnaire.value.splice(index, 1);
  getQuestionnaireDelete({ id: item.id }).then((res) => {
    console.log(res);
    if (res.code == 1) {
      //删除成功
      layer.msg('删除成功', { icon: 1 });
    } else {
      layer.msg(res.msg, { icon: 2 });
    }
    editShowQuestMsd(item.id);
  })
    .catch((e) => {
      console.log(e);
    });
}

// 提交问卷题目
const submitQuestionnaire = async () => {
  // 这里添加提交逻辑
  for (let item of questionnaireData.value) {
    if (!item.title) {
      layer.msg('题目不能为空', { icon: 2 })
      return
    }
    if (item.type != 3) {
      for (let op of item.option) {
        if (!op.val) {
          layer.msg('选项内容不能为空', { icon: 2 })
          return
        }
      }
    }
  }
  let jsonString = JSON.stringify(questionnaireData.value);
  // 调用API保存题目
  try {
    //这里替换为实际的API调用
    const res = await getQuestionnaireAdd({
      questionnaire_id: currentQuestionnaireId.value,
      topic: jsonString
    })
    if (res.code == 1) {
      layer.msg('保存成功', { icon: 1 })
      questionnaireAddMode.value = false
    } else {
      layer.msg(res.msg, { icon: 2 })
    }
    layer.msg('保存成功', { icon: 1 })
    questionnaireAddMode.value = false
  } catch (error) {
    layer.msg('保存失败', { icon: 2 })
  }
}
const delUpdateOptionItem = (index, opIndex) => {
  if (questionnaire.value[index].option.length <= 2) {
    layer.msg('至少保留两个选项', { icon: 2 });
    return;
  }
  questionnaire.value[index].option.splice(opIndex, 1);
  questionnaire.value[index].option.forEach((item, index) => {
    item.name = String.fromCharCode(65 + index);
  });
}
// 问卷题目弹窗按钮
const questionnaireButton = ref([
  {
    text: "确认",
    callback: submitQuestionnaire
  },
  {
    text: "取消",
    callback: () => {
      questionnaireAddMode.value = false
    }
  }
])

// 修改现有的addShowMsd方法，使其能够处理新增题目
const addShowMsd = (data, pid) => {

  console.log(data);
  // 如果是新增题目
  questionnaireAddMode.value = true;
  currentQuestionnaireId.value = data.id;
  questionnaireData.value=[{
  type: 1, title: '', wight: 0, option: [{ name: 'A', val: "" }, { name: 'B', val: "" }]
}];
}
const columns6 = [
  {
    title: "问卷标题",
    width: "200px",
    key: "title",
    align: 'center'
  },
  {
    title: "发布时间",
    width: "100px",
    key: "releasetime",
    align: 'center'
  },
  {
    title: '操作',
    width: '180px',
    customSlot: 'operator',
    key: 'operator',
    align: 'center',
    fixed: 'right'
  }
]

onMounted(() => {
  getHierarchicalData()
})

const changePage = (page) => {
  console.log(page);
  page.current = page.current;
  page.limit = page.limit;
  getHierarchicalData();
}

const openNew = () => {
  addData.id = 0;
  addIsEdit.value = 1;
  addData.title = '';
  addShow.value = true;
}

const getHierarchicalData = () => {
  getQuestionnaireIndex({ page: page.current, size: page.limit }).then((res) => {
    console.log(res)
    if (res.code == 1) {
      dataSource6.value = res.data.data;
      page.total = res.data.count;
    } else {
      layer.msg(res.msg, { icon: 2 })
    }
  })
}

const editShowMsd = (data) => {
  console.log(data);
  addShow.value = true;
  addData.id = data.id;
  addData.title = data.title;
  addData.materialcontent = data.materialcontent;
  addIsEdit.value = 2;
}

const delShowMsd = async (data) => {
  var res = await getQuestionnaireInfoDelete({ id: data.id });
  console.log(res)
  if (res.code == 1) {
    layer.msg('删除成功！', { icon: 1 })
    getHierarchicalData()
  } else {
    layer.msg(res.msg, { icon: 2 })
  }
}
const updateOption = (d) => {
  var option = d.option;
  console.log(d);
  const transformedArray = [];
  for (const key in option) {
    transformedArray.push({
      name: key,
      val: option[key].name, // 这里的`key`1111是根据你的示例构建的，可以根据实际需求调整
    });
  }
  let jsonString = d;
  getQuestionnaireEdit({
    topic: JSON.stringify(jsonString),
    id: d.id,
  })
    .then((res) => {
      console.log(res);
      if (res.code == 1) {
        layer.msg('保存成功', { icon: 1 });
      } else {
        layer.msg(res.msg, { icon: 2 });
      }
      editShowQuestMsd(d.questionnaire_id);
    })
    .catch((e) => {
      console.log(e);
    });
}
const addButton = ref([
  {
    text: "确认",
    callback: async () => {
      console.log(addData);
      if (addData.title == '') {
        layer.msg('问卷标题不能为空！', { icon: 2 })
        return;
      }
      if (addData.materialcontent == '') {
        layer.msg('问卷简介不能为空！', { icon: 2 })
        return;
      }
      if (addIsEdit.value == 1) {
        var res = await getQuestionnaireInfoAdd(addData);
      } else {
        var res = await getQuestionnaireInfoEdit(addData);
      }
      console.log(res)
      if (res.code == 1) {
        layer.msg('提交成功！', { icon: 1 })
        addShow.value = false;
        getHierarchicalData();
      } else {
        layer.msg(res.msg, { icon: 2 })
      }
    }
  },
  {
    text: "取消",
    callback: () => {
      addShow.value = false;
    }
  }
])
</script>
<style scoped></style>