<template>
  <div class="detail_container">
    <bg-breadcrumb></bg-breadcrumb>
    <div class="main_container">
      <div class="question-box">
        <div>问题分类 - {{ category.problem_type }}（{{ category.problem_number }}/8）</div>
        <el-button type="primary" @click="handleQuestionUpdate('create')">
          <bg-icon style="font-size: 12px; color: #fff; margin-right: 8px" icon="#bg-ic-add"></bg-icon>
          新增
        </el-button>
        <div class="table_container" style="padding: 0">
          <div class="table bg-scroll">
            <bg-table ref="bgTable" :headers="headers" :rows="tableRows" :isIndex="true" :stripe="true">
              <template #action="{ row }">
                <bg-table-btn @click="handleQuestionUpdate('edit', row)">编辑</bg-table-btn>
                <bg-table-btn @click="handleDeleteDialog(row)">删除</bg-table-btn>
                <bg-table-btn @click="moveRow(row, 1)" :disabled="!row.canMoveUp">上移</bg-table-btn>
                <bg-table-btn @click="moveRow(row, 2)" :disabled="!row.canMoveDown">下移</bg-table-btn>
              </template>
            </bg-table>
          </div>
          <!-- <bg-pagination
            :page="filter.page"
            :size="filter.size"
            :total="tableTotal"
            @change-page="changePage"
            @change-size="changeSize">
          </bg-pagination> -->
        </div>
      </div>
    </div>
    <el-dialog
      class="dialog_box"
      :title="questionEditType == 'create' ? '新增' : '编辑'"
      v-model="dialogQuestionEdit"
      width="614px">
      <el-form ref="bgForm" :model="ruleForm" :rules="rules" label-width="80px" class="bg_form">
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="ruleForm.title"
            type="text"
            show-word-limit
            maxlength="50"
            placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="回复内容" prop="content">
          <el-input
            v-model="ruleForm.content"
            type="textarea"
            :rows="8"
            show-word-limit
            maxlength="500"
            placeholder="请输入回复内容"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="apaas_button">
          <el-button type="default" @click="dialogQuestionEdit = false">取消</el-button>
          <el-button type="primary" @click="handleSaveCategory(bgForm)">保存</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      class="dialog_box"
      title="提示"
      v-model="dialogDelete"
      width="400px"
      :before-close="
        () => {
          dialogDelete = false;
        }
      ">
      <div>确定要删除吗？</div>
      <template #footer>
        <div class="apaas_button">
          <el-button type="default" @click="dialogDelete = false">取 消</el-button>
          <el-button type="primary" @click="deleteData">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, reactive, toRefs, ref } from "vue";
import bgBreadcrumb from "@/components/bg-breadcrumb.vue";
import { useRoute } from "vue-router";
import axios from "@/request/http.js";
import { ElMessage } from "element-plus";

const route = useRoute();
const { id } = route.query;

const bgForm = ref(null);
const state = reactive({
  category: {},
  tableRows: [],
  // filter: {
  //   page: 1,
  //   limit: 10,
  // },
  headers: [
    {
      label: "标题",
      prop: "title",
      width: 180,
    },
    {
      label: "回复内容",
      prop: "content",
    },
    {
      label: "操作",
      prop: "action",
      width: 260,
      fixed: "right",
    },
  ],
  questionEditType: "",
  dialogQuestionEdit: false,
  ruleForm: {
    title: "",
    content: "",
  },
  rules: {
    title: [{ required: true, message: "请输入标题", trigger: "blur" }],
    content: [{ required: true, message: "请输入回复内容", trigger: "blur" }],
  },
  dialogDelete: false,
  actionRow: null,
});

const handleDeleteDialog = (row) => {
  state.actionRow = row;
  state.dialogDelete = true;
};

const deleteData = () => {
  axios.delete(`/apaas/system/v5/customer/service/problem/${state.actionRow.id}`).then(({ data }) => {
    if (data.code === 200) {
      ElMessage.success("操作成功");
      getCategoryWithQuestions();
      state.dialogDelete = false;
    } else {
      ElMessage.error(data.data);
    }
  });
};

const handleQuestionUpdate = (type, row) => {
  state.dialogQuestionEdit = true;
  state.questionEditType = type;
  if (type !== "create") {
    state.actionRow = row;
    state.ruleForm.title = row.problem_type;
  }
};

const handleSaveCategory = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      const isNew = state.questionEditType === "create";
      axios
        .post(
          "/apaas/system/v5/customer/service/problem",
          Object.assign(
            {
              problem_type_id: state.category.problem_type_id,
              title: state.ruleForm.title,
              content: state.ruleForm.content,
            },
            !isNew && { id: actionRow.id }
          )
        )
        .then(({ data }) => {
          if (data.code === 200) {
            getCategoryWithQuestions();
            ElMessage.success("添加成功");
            state.dialogQuestionEdit = false;
            state.ruleForm.title = "";
            state.ruleForm.content = "";
          } else {
            ElMessage.error(data.data);
          }
        });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const getCategoryList = () => {
  axios.get(`/apaas/system/v5/customer/service/problem/type`).then((res) => {
    if (res.data.code == 200) {
      const [category] = res.data.data.filter((item) => item.id.toString() === id);
      state.category = category;
    } else {
      ElMessage.error(res.data.data);
    }
  });
};

const getQuestionList = () => {
  axios.get(`/apaas/system/v5/customer/service/problem/${id}`).then(({ data }) => {
    state.tableRows = data.data || [];
    if (state.tableRows.length > 0) {
      state.tableRows.forEach((e) => {
        e.canMoveUp = true;
        e.canMoveDown = true;
      });
      state.tableRows[0].canMoveUp = false;
      state.tableRows[state.tableRows.length - 1].canMoveDown = false;
    }
  });
};

const moveRow = (row, type) => {
  let index;
  state.tableRows.forEach((e, i) => {
    if (e.id == row.id) {
      index = i;
    }
  });
  let nextRow;
  if (type == 1) {
    // 上移
    nextRow = state.tableRows[index - 1];
  } else {
    // 下移
    nextRow = state.tableRows[index + 1];
  }
  let params = [
    {
      id: row.id,
      sort: nextRow.sort,
    },
    {
      id: nextRow.id,
      sort: row.sort,
    },
  ];
  axios
    .post(`/apaas/system/v5/customer/service/problem/sort`, [...params])
    .then((res) => {
      if (res.data.code == 200) {
        ElMessage.success("操作成功");
        getCategoryWithQuestions();
      } else {
        ElMessage.error(res.data.data);
      }
    })
    .catch((err) => {
      console.log(err);
    });
};

const getCategoryWithQuestions = () => {
  getCategoryList();
  getQuestionList();
};

onMounted(() => {
  getCategoryWithQuestions();
});

const { category, tableRows, headers, ruleForm, rules, questionEditType, dialogQuestionEdit, dialogDelete } =
  toRefs(state);
</script>

<style lang="scss" scoped>
.detail_container {
  width: 100%;
  padding: 0 24px;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: stretch;
  font-size: 14px;
  .main_container {
    padding: 40px;
    flex-grow: 1;
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: stretch;
    background-color: #fff;
    box-shadow: 0px 1px 4px 0px rgba(0, 7, 101, 0.15);
    border-radius: 6px;
    margin: 0 0 16px;
    position: relative;
    height: calc(100% - 62px);
    .table_container {
      height: calc(100% - 70px);
      padding: 0 16px;
      .table {
        max-height: calc(100% - 64px);
      }
    }
  }
}

.question-box {
  height: 100%;
  .el-button {
    margin: 40px 0 8px;
  }
}

:deep(.el-dialog__body) {
  padding-bottom: 0;
}
</style>
