<template>
  <div class="page-channel p-6">
    <div class="h-full w-full flex">
      <div class="mr-2">
        <el-card shadow="never" class="h-full">
          <template #header>
            <div class="flex items-center justify-between">
              <div class="flex items-center">
                <el-input
                  v-model.trim="query.title"
                  clearable
                  placeholder="输入标题名称进行搜索"
                />
                <el-button
                  type="primary"
                  class="ml-2"
                  @click="onSearch"
                  :icon="Search"
                  >搜索</el-button
                >
              </div>

              <Auth value="healthManage:visitTemplate:edit">
                <el-button
                  type="primary"
                  :icon="Plus"
                  class="ml-2"
                  v-if="!isPageTodoItems"
                  @click="
                    editVisible = true;
                    editForm = {
                      id: undefined,
                      title: '',
                      scope: '',
                      content: {}
                    };
                  "
                  >新增</el-button
                >
              </Auth>
            </div>
          </template>
          <div>
            <el-table
              :data="state.list"
              class="w-full"
              :show-header="false"
              max-height="85vh"
              @row-click="editRow"
            >
              <el-table-column prop="name" label="姓名">
                <template #default="{ row }">
                  <div
                    class="p-2 hover:bg-gray-50 cursor-pointer rounded"
                    :class="{
                      'bg-gray-10 border-r-4 border-blue-500':
                        currentValue?.id == row.id
                    }"
                  >
                    <h3>{{ row.title }}</h3>
                    <el-text>适用范围：{{ row.scope }}</el-text> <br />
                    <el-text>最后更新时间：{{ row.updatedAt }}</el-text>
                  </div>
                </template>
              </el-table-column>
            </el-table>

            <el-pagination
              background
              class="justify-end mt-4"
              layout="total, prev, pager, next"
              :page-size="10"
              :total="state.total"
              @change="handleCurrentChange"
            />
          </div>
        </el-card>
      </div>
      <div class="flex-1 h-full">
        <div v-if="currentValue?.id" class="h-full flex flex-col bg-white">
          <div class="p-4 border-b border-solid border-gray-200">
            <div class="flex items-center justify-between">
              <div>
                <h4>{{ currentValue.title }}</h4>
                <el-text>使用范围：{{ currentValue.scope }}</el-text>
              </div>
              <div class="ml-8">
                <template v-if="isPageTodoItems">
                  <el-button
                    type="primary"
                    @click="emits('onSelect', currentValue.content)"
                    >使用该模版</el-button
                  >
                </template>
                <template v-else>
                  <Auth value="healthManage:visitTemplate:edit">
                    <el-button
                      type="primary"
                      :icon="Edit"
                      link
                      @click="handleEdit"
                      >编辑</el-button
                    >
                    <el-popconfirm
                      title="确定要删除这个模板吗？"
                      width="300"
                      @confirm="handleDelete"
                    >
                      <template #reference>
                        <el-button type="danger" :icon="Delete" link
                          >删除</el-button
                        >
                      </template>
                    </el-popconfirm>
                  </Auth>
                </template>
              </div>
            </div>
          </div>
          <div class="flex-1 p-4 overflow-y-auto">
            <div class="flex items-center">
              <div class="flex-1">
                <div
                  class="flex items-center w-fit border rounded-3xl border-solid border-gray-400 overflow-hidden"
                >
                  <div
                    v-for="(item, index) in [
                      '随访问卷',
                      '随访健康指导',
                      '随访人员指导'
                    ]"
                    :key="index"
                    @click="curTab = index"
                    class="relative after:absolute after:right-0 after:top-2.5 after:w-[1px] after:h-4 after:bg-gray-400 after:content-[''] text-xs"
                  >
                    <div
                      class="cursor-pointer text-sm py-2 px-3 first-of-type:pl-6 last-of-type:pr-6 flex items-center"
                      :class="{
                        'bg-blue-500 hover:bg-blue-500 text-white':
                          curTab == index,
                        'hover:bg-gray-100': curTab != index
                      }"
                    >
                      {{ item }}
                    </div>
                  </div>
                </div>
              </div>
              <div>
                <el-button
                  v-if="!curTab && currentValue.content?.questions?.length"
                  type="primary"
                  @click="editContentVisible.questions = true"
                  >修改问卷</el-button
                >
                <el-button
                  v-if="curTab == 1 && currentValue.content?.healthGuidance"
                  type="primary"
                  @click="editContentVisible.healthGuidance = true"
                  >修改随访健康指导</el-button
                >
                <el-button
                  v-if="curTab == 2 && currentValue.content?.visitGuidance"
                  type="primary"
                  @click="editContentVisible.visitGuidance = true"
                  >修改随访人员指导</el-button
                >
              </div>
            </div>
            <div v-if="curTab == 0" class="pt-6">
              <div v-if="currentValue.content?.questions?.length">
                <div
                  v-for="(item, index) in currentValue.content?.questions"
                  :key="index"
                  class="m-1 bg-gray-100 rounded p-4 mb-3"
                >
                  <SimpleQuestionItem
                    :info="item"
                    :id="item.id"
                    :edit="false"
                  />
                </div>
              </div>
              <div
                v-else
                class="flex flex-col items-center px-4 py-6 mx-[14%] mt-[10%] rounded-lg bg-gray-100 space-y-4"
              >
                <div>
                  创建随访问卷，可对用户情况进行标准化信息回收，方便后期对比查看管理效果
                </div>
                <el-button
                  type="primary"
                  @click="editContentVisible.questions = true"
                  >立即创建</el-button
                >
              </div>
            </div>
            <div v-else-if="curTab == 1" class="py-4 px-2">
              <div
                v-if="currentValue.content?.healthGuidance"
                v-html="currentValue.content?.healthGuidance"
              />
              <div
                v-else
                class="flex flex-col items-center px-4 py-6 mx-[14%] mt-[10%] rounded-lg bg-gray-100 space-y-4"
              >
                <div>
                  设置健康指导内容，方便用户了解在不同时期如何进行自我管理，以及健康注意事项
                </div>
                <el-button
                  type="primary"
                  @click="editContentVisible.healthGuidance = true"
                  >立即创建</el-button
                >
              </div>
            </div>
            <div v-else-if="curTab == 2" class="py-4 px-2">
              <div
                v-if="currentValue.content?.visitGuidance"
                v-html="currentValue.content?.visitGuidance"
              />
              <div
                v-else
                class="flex flex-col items-center px-4 py-6 mx-[14%] mt-[10%] rounded-lg bg-gray-100 space-y-4"
              >
                <div>设置随访人员指导内容，指导随访人员如何进行随访</div>
                <el-button
                  type="primary"
                  @click="editContentVisible.visitGuidance = true"
                  >立即创建</el-button
                >
              </div>
            </div>
          </div>
        </div>
        <el-card shadow="never" class="h-full" v-else>
          <div>
            <el-empty />
          </div>
        </el-card>
      </div>
    </div>

    <el-dialog title="回访模板" v-model="editVisible">
      <div>
        <el-form ref="formRef" :model="editForm" label-width="120px">
          <el-form-item
            label="标题："
            prop="title"
            :rules="[
              {
                required: true,
                message: '请输入模板标题',
                trigger: 'blur'
              }
            ]"
          >
            <el-input
              v-model="editForm.title"
              placeholder="请输入模板标题"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="适用范围："
            prop="scope"
            :rules="[
              {
                required: true,
                message: '请输入适用范围',
                trigger: 'blur'
              }
            ]"
          >
            <el-input
              v-model="editForm.scope"
              placeholder="请输入适用范围"
              clearable
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div>
          <el-button @click="editVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveEditTemplate">保 存</el-button>
        </div>
      </template>
    </el-dialog>

    <DialogEditQuestion
      v-model:show="editContentVisible.questions"
      :initQuestions="currentValue.content?.questions"
      :initRules="currentValue.content?.logicCode"
      :submit-questions="saveQuestions"
      :submit-logic="saveLogicCode"
    />
    <el-dialog v-model="editContentVisible.healthGuidance" title="随访健康指导">
      <Editor v-model:value="currentValue.content.healthGuidance" />
      <template #footer>
        <el-button type="primary" @click="saveCurValue('healthGuidance')"
          >保存</el-button
        >
      </template>
    </el-dialog>
    <el-dialog v-model="editContentVisible.visitGuidance" title="随访人员指导">
      <Editor v-model:value="currentValue.content.visitGuidance" />
      <template #footer>
        <el-button type="primary" @click="saveCurValue('visitGuidance')"
          >保存</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, computed, defineEmits } from "vue";
import { Search, Plus, Edit, Delete } from "@element-plus/icons-vue";

import DialogEditQuestion from "@/components/Survey/DialogEditQuestion.vue";
import Editor from "@/components/Editor.vue";
import SimpleQuestionItem from "@/components/Survey/SimpleQuestionItem.vue";

import { request } from "@/utils";
import { ElMessage } from "element-plus";
import { useRoute } from "vue-router";
const route = useRoute();

const isPageTodoItems = computed(() =>
  ["healthManagementTodoList", "archivesProject"].includes(route.name)
);
const emits = defineEmits(["onSelect"]);
const state = reactive({
  visible: false,
  list: [],
  total: 0,
  rowData: {}
});
const query = reactive({
  title: "",
  page: 1
});

const onSearch = () => {
  query.page = 1;
  getList();
};
const getList = async () => {
  const { data } = await request.get(
    "dataService/schemeManage/visit/paginate",
    { params: query }
  );
  state.list = data.list;
  state.total = data.total;
  if (query.page == 1 && data.list[0]) {
    currentValue.value = data.list[0];
  }
};
const handleCurrentChange = page => {
  query.page = page;
  getList();
};
const handleDelete = async () => {
  const { message } = await request.post(
    `dataService/schemeManage/visit/delete`,
    {
      id: currentValue.value.id
    }
  );
  ElMessage.success(message);
  getList();
};
getList();

const editRow = row => {
  row.content = row.content
    ? row.content
    : {
        questions: [],
        logicCode: [],
        healthGuidance: "",
        visitGuidance: ""
      };
  currentValue.value = row;
};
const editForm = ref({
  id: "",
  title: "",
  scope: "",
  content: {
    questions: [],
    logicCode: [],
    healthGuidance: "",
    visitGuidance: ""
  }
});
const editVisible = ref(false);
const currentValue = ref({
  id: ""
});
const curTab = ref(0);
const handleEdit = () => {
  editForm.value = currentValue.value;
  editVisible.value = true;
};
const saveEditTemplate = async () => {
  const { message } = await request.post(
    `dataService/schemeManage/visit${editForm.value.id ? "/update" : ""}`,
    {
      id: editForm.value.id,
      title: editForm.value.title,
      scope: editForm.value.scope,
      content: editForm.value.content || ""
    }
  );
  ElMessage.success(message);
  editVisible.value = false;
  if (!editForm.value.id) {
    onSearch();
  }
  getList();
};

const editContentVisible = reactive({
  questions: false,
  healthGuidance: false,
  visitGuidance: false
});

const saveQuestions = async questions => {
  currentValue.value.content.questions = questions;
  console.log(questions);
  // ElMessage.success("保存成功");
  saveCurValue("questions");
};
const saveLogicCode = async rules => {
  currentValue.value.content.logicCode = rules;
  // ElMessage.success("保存成功");
  saveCurValue("logicCode");
};

const saveCurValue = async prop => {
  editForm.value = currentValue.value;
  console.log(currentValue.value);
  await saveEditTemplate();

  editContentVisible[prop] = false;
};
</script>
<style lang="scss">
.el-scrollbar__view {
  height: 100%;
  .main-content.page-channel {
    height: 100%;
    margin: 0;
  }
}
::v-deep {
  .el-card__header {
    height: 74px;
  }
  .el-table .el-table__body tr:hover > td {
    background-color: transparent;
  }
}
</style>
