<script setup>
/**
 * name：
 * user：sa0ChunLuyu
 * date：2024年10月12日 16:29:26
 */
import {ref, onMounted, computed} from 'vue';
import $router from '@/router'
import {onBeforeRouteUpdate} from "vue-router";
import {ElMessage, ElMessageBox} from 'element-plus'
import {
  QuestionCreateAction,
  QuestionUpdateAction,
  QuestionDeleteAction,
  QuestionListAction,
  QuestionItemItemAction,
  QuestionQuestionSelectAction,
  ComboGetAllList
} from '@/api/api.js'

const default_page_options = {
  search: '',
  type: '',
  page: 1,
}
const page_options = ref(JSON.parse(JSON.stringify(default_page_options)))
onBeforeRouteUpdate((to) => {
  routerChange(to.query)
})
const item_list = ref([])
const QuestionItemItem = async () => {
  const response = await QuestionItemItemAction({})
  if (response.status !== 'no') {
    item_list.value = response.data.list.map((item) => {
      return {
        ...item,
        name: item.sex !== 0 ? `${item.name}(${item.sex === 1 ? '男' : '女'})` : item.name
      }
    })
  } else {
    ElMessage.error(response.msg)
  }
}
const question_list = ref([])
const QuestionQuestionSelect = async () => {
  const response = await QuestionQuestionSelectAction({})
  if (response.status !== 'no') {
    question_list.value = response.data.list
  } else {
    ElMessage.error(response.msg)
  }
}
const table_list = ref([])
const last_page = ref(0)
const QuestionList = async () => {
  const response = await QuestionListAction(page_options.value)
  if (response.status !== 'no') {
    table_list.value = response.data.list.data.map((item) => {
      return {
        ...item,
        items: JSON.parse(item.items),
        questions: JSON.parse(item.questions)
      }
    })
    last_page.value = response.data.list.last_page
  } else {
    ElMessage.error(response.msg)
  }
}

const routerChange = (query) => {
  page_options.value = {
    search: query.search || default_page_options.search,
    type: query.type || default_page_options.type,
    page: Number(query.page) || default_page_options.page,
  }
  QuestionList()
}
//获取可用套餐列表
let combolist=ref([]);
const GetCombolist = async () => {
  const response = await ComboGetAllList({status:"enable"})
  if (response.status) {
    combolist.value=response.data.list
  } else {
    ElMessage.error(response.msg)
  }
}
const searchClick = (page = 1) => {
  page_options.value.page = page
  $router.push({
    query: JSON.parse(JSON.stringify(page_options.value))
  })
}

const itemNameShow = (items) => {
  let names = []
  for (let i in item_list.value) {
    if (items.includes(String(item_list.value[i].item_id))) {
      names.push(item_list.value[i].name)
    }
  }
  return names.join('、')
}
const edit_data_default = {
  id: 0,
  type: '问卷调查',
  name: '',
  items: [],
  questions: []
}
const edit_data = ref(JSON.parse(JSON.stringify(edit_data_default)))
const edit_show = ref(false)
const createClick = () => {
  updateClick(edit_data_default)
}
const updateClick = (row) => {
  edit_data.value = JSON.parse(JSON.stringify(row))
  edit_show.value = true
}
const editDoneClick = async () => {
  const $func = edit_data.value.id !== 0 ? QuestionUpdateAction : QuestionCreateAction
  const response = await $func({
    ...edit_data.value,
    items: JSON.stringify(edit_data.value.items),
    questions: JSON.stringify(edit_data.value.questions),
  })
  if (response.status !== 'no') {
    edit_show.value = false
    await QuestionList()
  } else {
    ElMessage.error(response.msg)
  }
}

const QuestionDelete = async (id) => {
  const response = await QuestionDeleteAction({id})
  if (response.status !== 'no') {
    await QuestionList()
  } else {
    ElMessage.error(response.msg)
  }
}

const deleteClick = (id) => {
  ElMessageBox.confirm(
      '是否确认删除该问卷？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    QuestionDelete(id)
  }).catch(() => {
  })
}
const edit_item_data = ref([])
const edit_item_show = ref(false)
const editItemClick = () => {
  edit_item_data.value = JSON.parse(JSON.stringify(edit_data.value.items))
  edit_item_show.value = true
}
const editItemDoneClick = () => {
  edit_data.value.items = JSON.parse(JSON.stringify(edit_item_data.value))
  edit_item_show.value = false
}
const filterMethod = (query, item) => {
  return item.name.toLowerCase().includes(query.toLowerCase()) || item.pinyin.toLowerCase().includes(query.toLowerCase())
}
const moveQuestionClick = (index, type) => {
  if (edit_data.value.questions.length - 1 >= index + type) {
    const question = edit_data.value.questions[index]
    edit_data.value.questions[index] = JSON.parse(JSON.stringify(edit_data.value.questions[index + type]))
    edit_data.value.questions[index + type] = JSON.parse(JSON.stringify(question))
  }
}
const delQuestionClick = (index) => {
  edit_data.value.questions.splice(index, 1)
}

const question_edit_list = computed(() => {
  return edit_data.value.questions.map((item) => {
    return {
      id: item,
      question: question_list.value.find((i) => i.id === Number(item)).question
    }
  })
})
const edit_question_active = ref(null)
const addQuestionClick = () => {
  if (edit_question_active.value) {
    edit_data.value.questions.push(String(edit_question_active.value))
  }
}

onMounted(() => {
  routerChange($router.currentRoute.value.query)
  QuestionItemItem()
  QuestionQuestionSelect()
  GetCombolist()
})
</script>
<template>
  <div>
    <el-dialog v-model="edit_item_show" title="关联项目管理" width="910px"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :show-close="false">
      <div>
		  <div class="eltransfer">
			  <el-transfer
			      :titles="['可选项目', '已选项目']"
			      :props="{key: 'item_id', label: 'name'}"
			      v-model="edit_item_data"
			      filterable
			      :filter-method="filterMethod"
			      filter-placeholder="搜索"
			      :data="item_list"
			  />
		  </div>
        
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editItemDoneClick()" type="primary">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="edit_show" title="题目配置" width="1000px">
      <div>
        <el-form label-width="150">
          <el-form-item label="问卷名称">
            <el-input v-model="edit_data.name" placeholder="请输入问卷名称"></el-input>
          </el-form-item>
          <el-form-item label="问卷类型">
            <el-select v-model="edit_data.type" placeholder="请选择问卷类型">
              <el-option label="检前评估" value="检前评估"></el-option>
              <el-option label="问卷调查" value="问卷调查"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="基础项目">
            <span style="margin-right: 10px;">{{ edit_data.items.length }} 个关联项目</span>
            <el-button type="primary" size="small" @click="editItemClick()">编辑项目</el-button>
          </el-form-item>
		  <el-form-item label="基础">
		     <el-select  v-model="edit_data.jichu_combo"
		                placeholder="选择套餐">
		       <el-option v-for="(item,index) in combolist" :key="index" :label="item.name" :value="item.combo_id" ></el-option> 
		     </el-select>
		  </el-form-item>
		  <el-form-item label="推荐">
		     <el-select  v-model="edit_data.tuijian_combo"
		                placeholder="选择套餐">
		       <el-option v-for="(item,index) in combolist" :key="index" :label="item.name" :value="item.combo_id" ></el-option> 
		     </el-select>
		  </el-form-item>
		  <el-form-item label="高端">
		     <el-select  v-model="edit_data.gaoduan_combo"
		                placeholder="选择套餐">
		       <el-option v-for="(item,index) in combolist" :key="index" :label="item.name" :value="item.combo_id" ></el-option> 
		     </el-select>
		  </el-form-item>
          <el-form-item label="题目">
            <div class="question_edit_title_wrapper">
              <el-select style="width: 300px;margin-right: 10px;" v-model="edit_question_active"
                         placeholder="请选择题目">
                <el-option v-for="(i,k) in question_list" :key="k" :label="i.question" :value="i.id"></el-option>
              </el-select>
              <el-button type="primary" size="small" @click="addQuestionClick()">添加题目</el-button>
            </div>
            <el-table :data="question_edit_list" style="width: 100%;" row-key="id" :tooltip-options="{
        popperClass: 'popper_class_wrapper'
      }">
              <el-table-column prop="id" label="ID" width="100"/>
              <el-table-column prop="question" label="题目" show-overflow-tooltip/>
              <el-table-column label="操作" width="140">
                <template #default="scope">
                  <el-button :disabled="scope.$index===0" type="primary" size="small"
                             @click="moveQuestionClick(scope.$index, -1)">
                    ↑
                  </el-button>
                  <el-button :disabled="scope.$index===edit_data.questions.length - 1" type="primary" size="small"
                             @click="moveQuestionClick(scope.$index, 1)">↓
                  </el-button>
                  <el-button :disabled="edit_data.questions.length === 1" type="primary" size="small"
                             @click="delQuestionClick(scope.$index)">X
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="edit_show = false">取消</el-button>
					<el-button type="primary" @click="editDoneClick()">确定</el-button>
				</span>
      </template>
    </el-dialog>

    <div class="head">
      <div class="head">
        <el-row>
          <el-form-item label="问卷类型">
            <el-select :empty-values="[undefined, null]" style="width: 120px;" v-model="page_options.type"
                       placeholder="请选择问卷类型">
              <el-option label="全部" value=""></el-option>
              <el-option label="检前评估" value="检前评估"></el-option>
              <el-option label="问卷调查" value="问卷调查"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item style="margin-left: 10px;">
            <el-input v-model="page_options.search" placeholder="搜索项目名称"/>
          </el-form-item>
          <el-button type="primary" @click="searchClick()" style="margin-left: 10px;">查询</el-button>
          <el-button type="success" @click="createClick()" style="margin-left: 10px;">添加</el-button>
        </el-row>
      </div>
    </div>
    <el-table :data="table_list" style="width: 100%;" row-key="id" :tooltip-options="{
        popperClass: 'popper_class_wrapper'
      }">
      <el-table-column prop="id" label="ID" width="100"/>
      <el-table-column prop="name" label="问卷名称" width="200"/>
      <el-table-column prop="type" label="问卷类型" width="120"/>
      <el-table-column label="基础项目" show-overflow-tooltip>
        <template #default="scope">
          {{ itemNameShow(scope.row.items) }}
        </template>
      </el-table-column>
      <el-table-column label="题目"  width="60">
        <template #default="scope">
          {{ scope.row.questions.length }}个
        </template>
      </el-table-column>
      <el-table-column label="操作" width="140">
        <template #default="scope">
          <el-button type="primary" @click="updateClick(scope.row)" size="small">修改</el-button>
          <el-button type="danger" @click="deleteClick(scope.row.id)" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="page">
      <el-pagination v-if="last_page > 0" :current-page="page_options.page" mt-2 background layout="prev, pager, next"
                     :page-count="last_page" @update:current-page="searchClick"/>
    </div>
  </div>
</template>
<style>
.popper_class_wrapper {
  width: 300px;
}
</style>
<style scoped>
.question_edit_title_wrapper {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.page {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}
.eltransfer >>> .el-transfer-panel{
	width: 350px;
}
</style>
