<template>
  <div class="detail_container">
    <bg-breadcrumb></bg-breadcrumb>
    <div class="flex_row">
      <div class="flex_left">
        <div class="box">
          <el-input
            class="type-input"
            v-model.trim="typeKeyword"
            @input="searchType"
            :prefix-icon="Search"
            placeholder="请输入搜索内容"></el-input>

          <div class="type_station bg-scroll">
            <div
              class="type-box"
              :class="{ 'current-type': nodeClassifyId == item.class_id }"
              @click="nodeClick(item)"
              v-for="(item, index) in typeList"
              :key="'type' + index + 200">
              {{ item.class_name }}
            </div>
          </div>
        </div>
      </div>
      <div class="flex_right">
        <div class="main_container">
          <bg-filter-group @search="changeSearch" v-model="filter.search" placeholder="请输入关键字">
            <template v-slot:left_action v-if="nodeClassifyId != '263758a4-0349-4d49-a816-e8ff8d33a8bb'">
              <div class="apaas_button">
                <el-button type="primary" @click="backDict" v-if="dictLevel != 1">
                  <!-- <bg-icon style="font-size: 12px; color: #fff; margin-right: 8px" icon="#bg-ic-add"></bg-icon> -->
                  返回上级
                </el-button>
                <el-button v-if="nodeClassifyId !== 2" type="primary" @click="register">
                  <bg-icon style="font-size: 12px; color: #fff; margin-right: 8px" icon="#bg-ic-add"></bg-icon>
                  新增
                </el-button>
              </div>
            </template>
            <template v-slot:filter_group>
              <div class="left-filter filter_list">
                <div class="filter_item">
                  <span class="filter_title">状态</span>
                  <el-select v-model="filter.status" placeholder="请选择" style="width: 300px">
                    <el-option
                      v-for="(item, index) in stateOptions"
                      :key="'pushOptions' + index"
                      :label="item.name"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </div>
              </div>
              <div class="right-action apaas_button">
                <el-button type="primary" @click="filterAction"> 查询 </el-button>
                <el-button type="default" @click="filterClear"> 重置 </el-button>
              </div>
            </template>
          </bg-filter-group>
          <div class="table_container">
            <div class="table bg-scroll">
              <bg-table ref="bgTable" :headers="headers" :rows="tableRows" :isIndex="true" :stripe="true">
                <template v-slot:name="{ row }">
                  <span class="can_click_text" @click="getChildren(row)" v-if="row.children">
                    {{ row.name }}
                  </span>
                  <span v-else>
                    {{ row.name }}
                  </span>
                </template>
                <template v-slot:status="{ row }">
                  <bg-switch
                    @click="changeUseRow(row)"
                    :labels="['否', '是']"
                    :values="[2, 1]"
                    :disabled="nodeClassifyId === 3 && row.built_in === 1"
                    v-model="row.status"></bg-switch>
                </template>
                <template v-slot:action="{ row }">
                  <!-- 除技术类型之外的字典可以删除 -->
                  <bg-table-btns2 :limit="3" v-if="nodeClassifyId !== 2">
                    <bg-table-btn @click="edit_row(row)" :disabled="row.status == 1">编辑</bg-table-btn>
                    <bg-table-btn @click="delete_row(row)" :disabled="row.status == 1">删除</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>
                  </bg-table-btns2>
                  <!-- 技术类型字典不可删除 -->
                  <bg-table-btns2 :limit="3" v-else>
                    <bg-table-btn @click="edit_row(row)" :disabled="row.status == 1">编辑</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>
                  </bg-table-btns2>
                </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>
    </div>
    <!-- 新增/编辑弹窗 -->
    <el-dialog class="dialog_box" :title="addType == 1 ? '新增' : '编辑'" v-model="addDialog" width="758px">
      <el-form ref="bgForm" :model="formData" :rules="rules" label-width="80px" class="bg_form">
        <el-form-item label="名称" prop="name">
          <el-input v-model.trim="formData.name" show-word-limit maxlength="6" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item
          v-if="nodeClassifyId === 3"
          label="单位"
          prop="unit"
          :rules="[{ required: true, message: '请输入单位', trigger: 'blur' }]">
          <el-input v-model.trim="formData.unit" show-word-limit maxlength="4" placeholder="请输入单位"></el-input>
        </el-form-item>
        <el-form-item
          v-if="nodeClassifyId === 3"
          label="值域上限"
          prop="max_val"
          :rules="[{ validator: validateNumber, trigger: 'blur' }]">
          <el-input v-model.trim="formData.max_val" placeholder="请输入正整数"></el-input>
        </el-form-item>
        <el-form-item
          v-if="nodeClassifyId === 3"
          label="值域下限"
          prop="min_val"
          :rules="[{ validator: validateNumber, trigger: 'blur' }]">
          <el-input v-model.trim="formData.min_val" placeholder="请输入正整数"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :autosize="{ minRows: 5 }"
            show-word-limit
            maxlength="200"
            resize="vertical"
            placeholder="请输入描述"></el-input>
        </el-form-item>
        <el-form-item label="是否启用" prop="status" style="margin-bottom: 0px">
          <el-switch
            class="bg-switch-ele"
            v-model="formData.status"
            :active-value="1"
            :inactive-value="2"
            inline-prompt
            active-text="是"
            inactive-text="否" />
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <div class="apaas_button">
          <el-button type="default" @click="addDialog = false">取 消</el-button>
          <el-button type="primary" @click="addConfirm">保 存</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 删除弹窗 -->
    <el-dialog
      class="dialog_box"
      title="提示"
      v-model="dialogDelete"
      width="400px"
      :before-close="
        () => {
          dialogDelete = false;
        }
      ">
      <div>确定要删除此字典值吗？</div>
      <template v-slot: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 { reactive, ref, onBeforeMount, toRefs, computed, watch, nextTick, watchEffect } from "vue";
import { ElMessage } from "element-plus";
import axios from "../../../../request/http.js";
import { Search } from "@element-plus/icons-vue";
import bgBreadcrumb from "@/components/bg-breadcrumb.vue";
const bgForm = ref(null);

const validateNumber = (rule, value, callback) => {
  if (value !== "" && /^(?:[1-9]\d*)$/.test(value) == false) {
    callback(new Error("请输入正整数"));
  } else {
    callback();
  }
};

const headers = computed(() => {
  let _headers = [
    {
      label: "名称",
      prop: "name",
    },
    {
      label: "描述",
      prop: "description",
      minWidth: 360,
    },
    {
      label: "更新时间",
      prop: "updated_at",
      width: 220,
    },
    {
      label: "是否启用",
      prop: "status",
    },
    {
      label: "操作",
      prop: "action",
      width: 176,
      fixed: "right",
    },
  ];

  if (state.nodeClassifyId === 3) {
    _headers.splice(
      1,
      0,
      {
        label: "单位",
        prop: "unit",
      },
      {
        label: "值域上限",
        prop: "max_val",
      },
      {
        label: "值域下限",
        prop: "min_val",
      }
    );
  }

  return _headers;
});
const state = reactive({
  bgForm,
  typeList: [], // 分类数据
  typeKeyword: "", // 分类删选关键词
  nodeClassifyId: null, // 当前选中分类的uuid  用于新增字典
  timer: null, // 定时器
  tableRows: [], // 表格数据
  tableTotal: 0, // 表格数据条数
  filter: {
    status: "",
    search: "",
    page: 1,
    page_size: 10,
  }, // 表格筛选项
  stateOptions: [
    {
      name: "全部",
      value: "",
    },
    {
      name: "启用",
      value: "1",
    },
    {
      name: "禁用",
      value: "0",
    },
  ], // 启用禁用
  actionRow: null, // 当前操作的数据
  dialogDelete: false, // 删除弹窗
  addType: 0, //
  addDialog: false,
  formData: {
    name: "",
    description: "",
    status: 1,
    unit: "",
    max_val: "",
    min_val: "",
  },
  rules: {
    name: [{ required: true, message: "请输入名称", trigger: "blur" }],
    description: [
      { required: true, message: "请输入描述", trigger: "blur" },
      { max: 200, message: "描述最大为200字", trigger: "blur" },
    ],
    status: [{ required: true, message: "请选择是否启用", trigger: "change" }],
  },
  fatherRow: null,
});

const dictLevel = ref(1);

const getChildren = (row) => {
  dictLevel.value = 2;
  state.tableRows = row.children || [];
  state.tableTotal = row.total_children;
  state.fatherRow = row;
};
const backDict = () => {
  dictLevel.value = 1;
  state.fatherRow = null;
  changePage(1);
};
const nodeClick = (item) => {
  dictLevel.value = 1;
  state.fatherRow = null;
  state.nodeClassifyId = item.class_id;
  state.filter = {
    status: "",
    search: "",
    page: 1,
    page_size: 10,
  };
  changePage(1);
}; // 切换字典分类

const searchType = () => {
  if (state.timer) {
    clearTimeout(state.timer);
  }
  state.timer = setTimeout(() => {
    getTypeList();
  }, 500);
}; // 字典分类筛选

const getTypeList = () => {
  let params = {
    class_name: state.typeKeyword,
  };
  axios
    .get(`/v1/api/dict/classList`, { params })
    .then((res) => {
      if (res.data.code == 200) {
        state.typeList = res.data.data || [];
        state.nodeClassifyId = state.typeList[0].class_id || null;
        getTableRows();
      } else {
        ElMessage.error(res.data.data);
      }
    })
    .catch((err) => {
      console.log(err);
    });
}; // 获取字典分类

const changeSearch = (val) => {
  state.filter.search = val;
  changePage(1);
}; // 表格关键字筛选

const filterAction = () => {
  changePage(1);
}; // 查询按钮

const filterClear = () => {
  state.filter = {
    status: "",
    search: "",
    page_size: 10,
    page: 1,
  };
  changePage(1);
}; // 重置筛选项

const getTableRows = () => {
  let params = { ...state.filter, class: state.nodeClassifyId };
  axios
    .get(`/v1/api/dict`, {
      params,
    })
    .then((res) => {
      if (res.data.code == 200) {
        let data = res.data.data || [];
        if (dictLevel.value == 1) {
          state.tableRows = data;
          state.tableTotal = res.data.total;
        } else {
          let row = data.filter((e) => {
            return e.dict_id == state.fatherRow.dict_id;
          });
          state.tableRows = row[0].children;
          state.tableTotal = row[0].total_children;
        }
        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 changeUseRow = (row) => {
  //预警规则类型且为内置数据的不可编辑删除
  if (row.class === 3 && row.built_in == 1) return;
  axios.put(`/v1/api/dict/status?id=${row.id}&status=${row.status}`).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success(res.data.msg);
      changePage(1);
    } else {
      ElMessage.error(res.data.data);
      row.status = row.status == 2 ? 1 : 2;
    }
  });
}; // 启用禁用

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

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

const register = () => {
  state.formData = {
    name: "",
    description: "",
    status: 1,
    unit: "",
    max_val: "",
    min_val: "",
  };
  if (state.bgForm) {
    nextTick().then(() => {
      state.bgForm.validate((valid) => {
        if (!valid) {
          state.bgForm.clearValidate();
        }
      });
    });
  }
  state.addType = 1;
  state.addDialog = true;
}; // 新增字典按钮

const edit_row = (row) => {
  state.actionRow = row;
  if (row.class === 3) {
    state.formData = {
      name: row.name,
      unit: row.unit,
      max_val: row.max_val,
      min_val: row.min_val,
      description: row.description,
      status: row.status,
    };
  } else {
    state.formData = {
      name: row.name,
      description: row.description,
      status: row.status,
    };
  }

  if (state.bgForm) {
    nextTick().then(() => {
      state.bgForm.validate((valid) => {
        if (!valid) {
          state.bgForm.clearValidate();
        }
      });
    });
  }
  state.addType = 2;
  state.addDialog = true;
}; // 编辑按钮

const addConfirm = () => {
  state.bgForm.validate((valid) => {
    if (valid) {
      if (state.addType == 1) {
        // 新增
        let params = {
          class: state.nodeClassifyId,
          ...state.formData,
        };
        if (state.nodeClassifyId !== 3) {
          delete params.min_val;
          delete params.max_val;
          delete params.unit;
        }
        axios.post(`/v1/api/dict`, params).then((res) => {
          if (res.data.code == 200) {
            ElMessage.success(res.data.msg);
            state.addDialog = false;
            changePage(1);
          } else {
            ElMessage.error(res.data.data);
          }
        });
      } else {
        // 编辑
        let params = {
          id: state.actionRow.id,
          class: state.actionRow.class,
          ...state.formData,
        };
        if (state.actionRow.class !== 3) {
          delete params.min_val;
          delete params.max_val;
          delete params.unit;
        }
        axios.put(`/v1/api/dict`, params).then((res) => {
          if (res.data.code == 200) {
            ElMessage.success(res.data.msg);
            state.addDialog = false;
            changePage(1);
          } else {
            ElMessage.error(res.data.data);
          }
        });
      }
    }
  });
}; // 确定新增/编辑

const delete_row = (row) => {
  state.dialogDelete = true;
  state.actionRow = row;
}; // 删除按钮

const deleteData = () => {
  axios.delete(`/v1/api/dict?id=${state.actionRow.id}`).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success(res.data.msg);
      state.dialogDelete = false;
      changePage(1);
    } 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
    .put(`/v1/api/dict/sort`, [...params])
    .then((res) => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.msg);
        changePage(1);
      } else {
        ElMessage.error(res.data.data);
      }
    })
    .catch((err) => {
      console.log(err);
    });
};

onBeforeMount(() => {
  getTypeList();
});

const {
  typeList,
  typeKeyword,
  nodeClassifyId,
  tableRows,
  tableTotal,
  filter,
  stateOptions,
  dialogDelete,
  addType,
  addDialog,
  formData,
  rules,
} = toRefs(state);
</script>

<style lang="scss" scoped>
.detail_container {
  width: 100%;
  height: calc(100vh - 56px);
  padding: 0 24px;
  min-height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: stretch;
  .flex_row {
    // flex-grow: 1;
    width: 100%;
    display: flex;

    margin-bottom: 16px;
    position: relative;
    height: calc(100% - 62px);
    .flex_left {
      width: 240px;
      background-color: #fff;
      margin-right: 16px;
      border-radius: 6px;
      padding: 16px;
      height: 100%;
      box-shadow: 0px 1px 4px 0px rgba(0, 7, 101, 0.15);
      overflow: hidden;

      .box {
        width: 208px;
        height: 100%;
        overflow: hidden;
        .type_station {
          width: 100%;
          margin-top: 16px;
          height: calc(100% - 50px);
          .type-box {
            height: 32px;
            line-height: 32px;
            text-align: center;
            font-size: 14px;
            color: #404a62;
            cursor: pointer;
            &:hover {
              background-color: #f2f3f7;
            }
          }
          .current-type {
            background-color: #f2f3f7;
            border-radius: 4px;
          }
        }
      }
    }
    .flex_right {
      flex: 1;
      background-color: #fff;
      border-radius: 6px;
      box-shadow: 0px 1px 4px 0px rgba(0, 7, 101, 0.15);
      height: 100%;
      .main_container {
        height: 100%;
        .filter-group {
          .left-filter {
            flex: 1;
            display: flex;
            justify-content: start;
            flex-wrap: wrap;
          }
          .right-action {
            width: 144px;
            padding-bottom: 16px;
            .el-button {
              width: 64px;
            }
          }
        }

        .table_container {
          height: calc(100% - 70px);
          width: 100%;
          padding: 0 16px;
          .table {
            max-height: calc(100% - 64px);
          }
        }
      }
    }
  }

  .bg_form {
    width: 100%;
    box-sizing: border-box;
    .el-form-item {
      margin-bottom: 24px;
      :deep().el-form-item__label {
        line-height: 36px;
        height: 36px;
      }
      .el-form-item__content {
        width: 100%;
        .el-textarea {
          :deep().el-input__count {
            bottom: -16px;
            right: 4px;
            font-family: Roboto-Regular;
            color: #a9b1c7;
          }
        }
        .bg-switch-ele {
          width: 52px;
          height: 24px;
          :deep().el-switch__core {
            width: 100%;
            height: 24px;
            .el-switch__inner,
            .el-switch__action {
              top: 3px;
            }
          }
        }
      }
    }
  }
}
</style>
