<template>
  <div class="detail_container">
    <bg-breadcrumb></bg-breadcrumb>
    <div class="main_container">
      <div class="switch-box">
        <div class="switch-label">是否启用</div>
        <!-- 特别说明，本来这个开关适用于整个功能，但是经沟通，后端的欢迎语开关也是唯一的，他们决定用这个欢迎语开关来确认整个功能的是否启用，所以代码逻辑可能产生误会，特此说明 -->
        <bg-switch
          @click="handleWelcomeSwitch()"
          class="bg-switch-ele"
          v-model="welcome.state"
          :values="[0, 1]"
          inline-prompt
          :labels="['否', '是']" />
      </div>
      <div class="welcome-box">
        <div class="welcome-label"><span class="required">*</span>欢迎语</div>
        <div class="welcome-form">
          <el-input
            type="text"
            maxlength="50"
            v-model="welcome.content"
            placeholder="请输入欢迎语"
            show-word-limit></el-input>
          <el-button type="primary" @click="setWelcomeText">保存</el-button>
        </div>
      </div>
      <div class="question-box">
        <div>问题分类</div>
        <el-button type="primary" @click="handleCategoryUpdate('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 #state="{ row }">
                <bg-switch
                  @click="changeUseRow(row)"
                  :labels="['否', '是']"
                  :values="[0, 1]"
                  v-model="row.state"></bg-switch>
              </template>
              <template #problem_number="{ row }">
                <router-link :to="`/config/reply-settings/question-category?id=${row.id}`">{{
                  row.problem_number
                }}</router-link>
              </template>
              <template #action="{ row }">
                <bg-table-btn @click="$router.push(`/config/reply-settings/question-category?id=${row.id}`)"
                  >添加问题</bg-table-btn
                >
                <bg-table-btn @click="handleCategoryUpdate('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="categoryEditType == 'create' ? '新增' : '编辑'"
      v-model="dialogCategoryEdit"
      width="614px">
      <el-form ref="bgForm" :model="ruleForm" :rules="rules" label-width="80px" class="bg_form">
        <el-form-item label="描述" prop="categoryName">
          <el-input
            v-model="ruleForm.categoryName"
            type="text"
            show-word-limit
            maxlength="50"
            placeholder="请输入问题分类"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="apaas_button">
          <el-button type="default" @click="dialogCategoryEdit = 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 { ref, reactive, toRefs, onMounted } from "vue";
import bgBreadcrumb from "@/components/bg-breadcrumb.vue";
import axios from "@/request/http.js";
import { ElMessage } from "element-plus";
const bgForm = ref(null);
const state = reactive({
  welcome: {},
  tableRows: [],
  headers: [
    {
      label: "问题分类",
      prop: "problem_type",
      minWidth: 360,
    },
    {
      label: "问题数量",
      prop: "problem_number",
    },
    {
      label: "是否启用",
      prop: "state",
    },
    {
      label: "操作",
      prop: "action",
      width: 340,
      fixed: "right",
    },
  ],
  filter: {
    page: 1,
    limit: 10,
  },
  categoryEditType: "",
  dialogCategoryEdit: false,
  ruleForm: {
    categoryName: "",
  },
  rules: {
    categoryName: [{ required: true, message: "请输入问题分类", trigger: "blur" }],
  },
  dialogDelete: false,
  actionRow: null,
});

const getTableRows = () => {
  let params = { ...state.filter };
  axios
    .get(`/apaas/system/v5/customer/service/problem/type`, {
      params,
    })
    .then((res) => {
      if (res.data.code == 200) {
        state.tableRows = res.data.data || [];
        state.tableTotal = res.data.total;
        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;
        }
      } else {
        ElMessage.error(res.data.data);
      }
    });
};

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/type/sort`, [...params])
    .then((res) => {
      if (res.data.code == 200) {
        ElMessage.success("操作成功");
        changePage(1);
      } else {
        ElMessage.error(res.data.data);
      }
    })
    .catch((err) => {
      console.log(err);
    });
};

const changeUseRow = (row) => {
  axios
    .put(`/apaas/system/v5/customer/service/problem/type/state`, {
      id: row.id,
      state: row.state,
    })
    .then((res) => {
      if (res.data.code == 200) {
        ElMessage.success("操作成功");
        changePage(1);
      } else {
        ElMessage.error(res.data.data);
        row.state = row.state == 0 ? 1 : 0;
      }
    });
}; // 启用禁用

const changePage = (page) => {
  state.filter.page = page;
  getTableRows();
}; // 改变页码

const changeSize = (size) => {
  state.filter.limit = size;
  changePage(1);
}; // 改变每页条数

const handleCategoryUpdate = (type, row) => {
  state.dialogCategoryEdit = true;
  state.categoryEditType = type;
  if (type !== "create") {
    state.actionRow = row;
    state.ruleForm.categoryName = row.problem_type;
  }
};

const handleSaveCategory = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      const isNew = state.categoryEditType === "create";
      axios
        .post("/apaas/system/v5/customer/service/problem/type", {
          id: isNew ? 0 : 1,
          problem_type: state.ruleForm.categoryName,
          state: isNew ? 0 : state.actionRow.state,
        })
        .then(({ data }) => {
          if (data.code === 200) {
            ElMessage.success("添加成功");
            changePage(1);
            state.dialogCategoryEdit = false;
            state.ruleForm.categoryName = "";
          } else {
            ElMessage.error(data.data);
          }
        });
    } else {
      console.log("error submit!", fields);
    }
  });
};

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

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

const handleWelcomeSwitch = () => {
  // 可能会造成的bug，如果用户改了欢迎语，但是不点保存，直接点击开关，也会影响到欢迎语的变化，所以千万不要修改欢迎语不保存，去点击开关。
  axios.post("/apaas/system/v5/customer/service/welcome", state.welcome).then(({ data }) => {
    if (data.code === 200) {
      ElMessage.success("操作成功");
    } else {
      ElMessage.error(data.data);
    }
  });
};

const getWelcomeText = () => {
  axios.get("/apaas/system/v5/customer/service/welcome").then(({ data }) => {
    if (data.data) {
      state.welcome = {
        state: data.data.state,
        id: data.data.id,
        content: data.data.content,
      };
    } else {
      state.welcome = {
        content: "",
        state: 1,
      };
    }
  });
};
const setWelcomeText = () => {
  axios.post("/apaas/system/v5/customer/service/welcome", state.welcome).then(({ data }) => {
    if (data.code === 200) {
      ElMessage.success("操作成功");
    } else {
      ElMessage.error(data.data);
    }
  });
};

onMounted(() => {
  changePage(1);
  getWelcomeText();
});

const {
  welcome,
  ruleForm,
  rules,
  categoryEditType,
  dialogCategoryEdit,
  headers,
  dialogDelete,
  filter,
  tableRows,
  tableTotal,
} = 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);
      }
    }
  }
}

.switch-box {
  display: flex;
  align-items: center;
  .switch-label {
    margin-right: 17px;
  }
  .bg-switch-ele {
  }
}
.welcome-box {
  margin-top: 23px;
  .welcome-label .required {
    color: #d75138;
  }
  .welcome-form {
    margin-top: 7px;
    .el-input {
      width: 994px;
      margin-right: 8px;
    }
  }
}

.question-box {
  margin-top: 42px;
  height: 100%;
  .el-button {
    margin: 23px 0 8px;
  }
}
</style>
