<template>
  <div class="dictionary">
    <div class="demo-formName">
      <my-form
        :formNewList="formList"
        :fromItem="formItem"
        @headdenForm="headdenForm"
        searchFive
        ref="myForm"
      >
      </my-form>
    </div>
    <div class="count">
      <el-button
        type="primary"
        icon="el-icon-search"
        @click="headdenForm({ page: 1, pageSize: 10 }, 'search')"
      >
        查询
      </el-button>
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="headdenForm({}, 'add')"
      >
        新增
      </el-button>
    </div>
    <div class="table-container">
      <my-table
        :tableData="tableData"
        :coloumData="coloumData"
        isShowPagination
        :paginationParam="paginationParam"
        @changeSize="handleSizeChange"
        @changePage="handlePageChange"
        @selectionChange="handleSelectionChange"
      >
      </my-table>
    </div>
    <el-drawer
      :title="title"
      :visible.sync="drawer"
      append-to-body
      direction="rtl"
      :wrapperClosable="false"
      :close-on-press-escape="false"
    >
      <div class="demo-drawer__content">
        <my-form
          :formNewList="formDrawerList"
          :fromItem="fromItem"
          dialogImageUrl
          @determine="determine"
          @handleClose="handleClose"
          @changeSelect="changeSelect"
          labelWidth="120px"
          :disabled="isEditFlag"
        >
        </my-form>
      </div>
    </el-drawer>
  </div>
</template>

<script>
"use script";
import {
  whitListList,
  whitListAdd,
  whitListUpdate,
  whitListDelete
} from "@/api/whitList.js";
import { devPositionList } from "@/api/position.js";
export default {
  name: "whitListDialog",
  data() {
    return {
      formList: [
        {
          label: "名称",
          type: "input",
          model: "key"
        }
      ],
      tableData: [],
      coloumData: [
        {
          type: "text",
          label: "sn",
          prop: "sn",
          width: 150
        },
        {
          type: "text",
          label: "描述",
          prop: "message"
        }
      ],
      paginationParam: {
        currentPage: 1,
        size: 10,
        total: 0
      },
      formItem: {},
      formDrawerList: [
        {
          label: "sn",
          type: "input",
          model: "sn",
          rules: [{ required: true, message: "请输入sn" }]
        },
        {
          label: "是否全天",
          type: "select",
          model: "allDay",
          options: [
            { label: "是", key: "0" },
            { label: "否", key: "1" }
          ],
          rules: [
            { required: true, message: "请选择是否全天", trigger: "change" }
          ]
        },
        {
          label: "关联防区",
          type: "select",
          model: "positionId",
          options: [],
          disabled: false,
          rules: [
            { required: true, message: "请选择关联防区", trigger: "change" }
          ]
        },
        {
          label: "时间日期",
          type: "datetimerange",
          model: "date",
          format: "yyyy-MM-dd HH:mm:ss"
        }
      ],
      drawer: false,
      title: "",
      fromItem: {},
      isType: "",
      isEditFlag: false,
      PositionList: []
    };
  },
  components: {},
  mounted() {
    this.headdenForm({}, "search");
    this.search();
  },
  methods: {
    changeSelect(value) {
      const lastItem = this.formDrawerList[this.formDrawerList.length - 1];
      const dateTimeItem = {
        label: "时间日期",
        type: "datetimerange",
        model: "date",
        format: "yyyy-MM-dd HH:mm:ss"
      };

      if (value === "0") {
        if (lastItem.label === "时间日期") {
          this.formDrawerList.pop();
          this.$set(this.fromItem, "date", null); // 清除 date 数据
        }
      } else if (value === "1") {
        if (lastItem.label !== "时间日期") {
          this.formDrawerList.push(dateTimeItem);
          this.$set(this.fromItem, "date", []); // 初始化 date 数据
        }
      }
    },
    initPosition() {
      devPositionList().then((res) => {
        if (res.code === 0) {
          this.PositionList = res.data.items;
          this.formDrawerList.forEach((item) => {
            if (item.label === "关联防区") {
              item.options = res.data.items.map((item) => {
                item.label = item.name;
                item.key = item.id;
                return item;
              });
            }
          });
        }
      });
    },
    search() {
      this.headdenForm({}, "search");
    },
    // 搜索
    headdenForm(value, type) {
      let params = {};
      if (type === "search") {
        params = JSON.parse(JSON.stringify(this.$refs.myForm.ruleForm));
        if (params.dateRange) {
          params.startTime = params.dateRange[0];
          params.endTime = params.dateRange[1];
        }
        if (value.page !== undefined) {
          this.paginationParam.currentPage = value.page;
          this.paginationParam.size = value.pageSize;
        }
        params.pageNum = this.paginationParam.currentPage;
        params.pageSize = this.paginationParam.size;
        this.$delete(params, "dateRange");
        whitListList(params).then((res) => {
          if (res.code === 0) {
            this.tableData = res.data.items;
            this.paginationParam.total = res.data.total;
          }
        });
      } else if (type === "add") {
        this.isType = "add";
        this.title = "新增白名单";
        this.initPosition();
        this.fromItem = {};
        this.formDrawerList = this.getDefaultFormDrawerList();
        this.isEditFlag = false;
        this.drawer = true;
      }
    },
    // 确定按钮
    determine(value) {
      const params = { ...value };
      console.log(params, "params");

      // 设置 positionName
      const position = this.PositionList.find(
        (item) => item.id === params.positionId
      );
      params.positionName = position ? position.name : "";

      // 处理 allDay 和时间
      if (params.allDay === "0") {
        params.allDay = true;
        params.startTime = "";
        params.endTime = "";
      } else {
        params.allDay = false;
        if (Array.isArray(params.date) && params.date.length === 2) {
          params.startTime = params.date[0];
          params.endTime = params.date[1];
        } else {
          params.startTime = "";
          params.endTime = "";
        }
      }
      delete params.date; // 移除 date 字段
      const apiCall = this.isType === "add" ? whitListAdd : whitListUpdate;
      apiCall(params)
        .then((res) => {
          if (res.code === 0) {
            this.$message.success(
              `${this.isType === "add" ? "新增" : "编辑"}成功`
            );
            this.search();
          } else {
            this.$message.error(
              `${this.isType === "add" ? "新增" : "编辑"}失败`
            );
          }
        })
        .catch((err) => {
          console.error(`${this.isType === "add" ? "新增" : "编辑"}错误:`, err);
          this.$message.error(
            `${this.isType === "add" ? "新增" : "编辑"}时发生错误`
          );
        });
      this.drawer = false;
    },
    // 编辑 删除
    handleClick(value, type) {
      if (type === "edit") {
        this.isType = "edit";
        this.title = "编辑白名单";
        this.isEditFlag = false;
        this.fromItem = { ...value };
        this.formDrawerList = this.getDefaultFormDrawerList();
        value.allDay = value.allDay ? "0" : "1";
        this.changeSelect(value.allDay); // 根据 allDay 调整时间日期字段
        this.initPosition();
        this.drawer = true;
      } else if (type === "delete") {
        console.log(value);
        let params = {
          id: value.id
        };
        this.$confirm("此操作将永久删除该白名单, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            whitListDelete(params).then((res) => {
              if (res.code === 0) {
                this.$message.success("删除成功");
                this.headdenForm({}, "search");
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      }
    },
    // 关闭抽屉
    handleClose() {
      this.drawer = false;
    },
    //分页
    handleSizeChange(value) {
      console.log(value);
      this.paginationParam.size = value;
      this.headdenForm({}, "search");
    },
    handlePageChange(value) {
      console.log(value);
      this.paginationParam.currentPage = value;
      this.headdenForm({}, "search");
    },
    handleSelectionChange(value) {
      console.log(value);
    }, // 初始化 formDrawerList 的公共方法
    getDefaultFormDrawerList() {
      return [
        {
          label: "sn",
          type: "input",
          model: "sn",
          rules: [{ required: true, message: "请输入sn" }]
        },
        {
          label: "是否全天",
          type: "select",
          model: "allDay",
          options: [
            { label: "是", key: "0" },
            { label: "否", key: "1" }
          ],
          rules: [
            { required: true, message: "请选择是否全天", trigger: "change" }
          ]
        },
        {
          label: "关联防区",
          type: "select",
          model: "positionId",
          options: [],
          disabled: false,
          rules: [
            { required: true, message: "请选择关联防区", trigger: "change" }
          ]
        },
        {
          label: "时间日期",
          type: "datetimerange",
          model: "date",
          format: "yyyy-MM-dd HH:mm:ss"
        }
      ];
    }
  }
};
</script>
<style scoped lang="scss">
.dictionary {
  width: 95%;
  height: 100%;
  padding: 20px;
  position: relative;
}
</style>
