<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      v-model:page="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
    </avue-crud>
  </basic-container>
</template>

<script>
import {
  addEncryTypeAPI,
  updateEncryTypeAPI,
  deleteEncryTypeAPI,
  getEncryTypeListAPI,
} from '@/api/filesTransfer/encryption';
import { mapGetters } from 'vuex';
import website from '@/config/website';

export default {
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 32,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: true,
        selection: false,
        addBtn:true,
        dialogClickModal: false,
        column: [

          {
            label: '数据加密名称',
            prop: 'encryptName',
            search: true,
          },

          {
            label: '数据加密类型',
            prop: 'encryptType',  //该列对应的数据字段名（即后端返回或提交时使用的 key）。
            type: 'select', //指定该字段在表单中的输入类型为“下拉选择框”
            dicUrl: '/blade-system/system/dict/data/type', // 接口地址
            dicMethod: 'post', // 指定为 POST 请求
            dicQuery: {
              dictType: 'file_encryption_type' //作为请求体（body）发送（Avue 内部会处理）
            },
            props: {
              label: 'dictLabel',
              value: 'dictValue',
            },
            slot: true,
            rules: [
              {
                required: true,
                message: '请选择数据加密类型',
                trigger: 'blur',
              },
            ],
          },

          {
            label: '加密参数',
            prop: 'encryptParams',
          },
        ],
      },
      data: [],
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.post_add, false),
        viewBtn: this.validData(this.permission.post_view, false),
        delBtn: this.validData(this.permission.post_delete, false),
        editBtn: this.validData(this.permission.post_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
  },
  methods: {
    rowSave(row, done, loading) {
      // 只提取需要的字段
      const submitData = {
        encryptName: row.encryptName,
        encryptParams: row.encryptParams,
        encryptType: row.encryptType,
      };
      addEncryTypeAPI(submitData).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          done();
        },
        error => {
          console.error('新增失败:', error);
          loading(); // 恢复按钮 loading 状态
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      // 只保留需要的字段
      const submitData = {
        id: row.id,
        encryptName: row.encryptName,
        encryptParams: row.encryptParams,
        encryptType: row.encryptType,
      };

      updateEncryTypeAPI(submitData).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          done();
        },
        error => {
          console.log(error);
          loading(); // 恢复按钮状态
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return deleteEncryTypeAPI(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return deleteEncryTypeAPI(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type, row) {
      done(); // 必须调用 done()
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      let data = {
        ...params,
        pageNum:page.currentPage,
        pageSize:page.pageSize
      };
      getEncryTypeListAPI(data).then(res => {
        const data = res.data;
        this.page.total = data.total;
        this.data = data.rows;
        this.loading = false;
        this.selectionClear();
      });
    },
  },
};
</script>

<style></style>
