<template>
  <div class="app-container">
    <el-form
      ref="ruleFormRef"
      :model="form"
      label-position="left"
      label-width="auto"
      :rules="rules"
      style="max-width: 600px"
    >
      <el-form-item label="操作类型" prop="operationType">
        <el-select v-model="form.operationType" placeholder="请选择操作类型">
          <el-option label="创建新账号" value="create"></el-option>
          <el-option label="更新旧账号" value="update"></el-option>
        </el-select>
      </el-form-item>

      <template v-if="form.operationType === 'create'">
        <el-form-item label="账号" prop="username">
          <el-input v-model="form.username" placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
      </template>

      <template v-if="form.operationType === 'update'">
        <el-form-item label="选择账号" prop="accountId">
          <el-select v-model="form.accountId" placeholder="请选择要更新的账号" @change="handleAccountChange">
            <el-option
              v-for="item in subAccountList"
              :key="item.accountId"
              :label="item.name"
              :value="item.accountId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" @click="openResetPasswordDialog">重置密码</el-button>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="form.enable" active-text="启用" inactive-text="禁用"></el-switch>
        </el-form-item>
      </template>

      <el-form-item label="姓名" prop="name">
        <el-input v-model="form.name" placeholder="请输入姓名"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="form.mobile" placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入备注"></el-input>
      </el-form-item>

      <el-form-item label="权限分配" prop="permissionCodes">
        <el-tree
          ref="permissionTree"
          :data="permissionList"
          show-checkbox
          node-key="id"
          :props="defaultProps"
          @check="handleTreeCheck"
        >
        </el-tree>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="save">保存</el-button>
      </el-form-item>
    </el-form>

    <el-dialog
      title="重置密码"
      :visible.sync="resetPasswordDialogVisible"
      width="30%"
      @close="newPassword = ''"
    >
      <el-form label-width="80px">
        <el-form-item label="新密码">
          <el-input v-model="newPassword" type="password" placeholder="请输入新密码"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetPasswordDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleResetPassword">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAvailablePermissions,
  createSubAccount,
  getSubAccountList,
  getSubAccountDetail,
  updateSubAccount,
  checkUsername,
  resetPassword
} from '@/api/modules/subaccount'
import routerConfig from '@/router/full-routers'

// Function to filter the full menu tree based on available permissions
const filterTreeByPerms = (tree, availablePerms) => {
  if (!Array.isArray(tree)) {
    return []; // Return empty array if tree is not an array
  }
  return tree.reduce((acc, node) => {
    // Recursively filter children
    const children = node.list && node.list.length > 0
      ? filterTreeByPerms(node.list, availablePerms)
      : [];

    // A node is kept if its permission is in the available list,
    // or if it has children that are kept.
    if (availablePerms.includes(node.perms) || children.length > 0) {
      acc.push({
        ...node,
        list: children, // Use the filtered list of children
      });
    }
    return acc;
  }, []);
};

// Function to map the filtered tree to the format required by el-tree
const mapTreeForElTree = (tree) => {
  return tree.map((item) => ({
    id: item.perms, // Use perms as the id
    label: item.name,
    children: item.list && item.list.length > 0 ? mapTreeForElTree(item.list) : [],
  }));
};

export default {
  name: 'SubOperator',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (this.form.operationType !== 'create') {
        return callback();
      }
      if (!value) {
        return callback(new Error('请输入账号'));
      }
      checkUsername(value).then(res => {
        if (res && res.data && res.data.data && res.data.data.available === true) {
          callback();
        } else {
          callback(new Error('账号已被占用'));
        }
      }).catch(() => {
        callback(new Error('账号校验失败'));
      });
    };

    return {
      resetPasswordDialogVisible: false,
      newPassword: '',
      form: {
        operationType: 'create',
        username: '',
        password: '',
        name: '',
        mobile: '',
        permissionCodes: [],
        remark: '',
        accountId: null,
        enable: true
      },
      subAccountList: [],
      permissionList: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      rules: {
        operationType: [
          { required: true, message: "请选择操作类型", trigger: "change" },
        ],
        username: [
          { required: true, validator: validateUsername, trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
        ],
        name: [
          { required: true, message: "请输入姓名", trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
        ],
        permissionCodes: [
          { required: true, message: "请选择菜单权限", trigger: "change", type: 'array' },
        ],
        accountId: [
          { required: true, message: "请选择要更新的账号", trigger: "change" },
        ],
      },
    };
  },
  watch: {
    'form.operationType'(newType) {
      // Manually reset form fields to avoid resetting the operationType
      this.form.username = '';
      this.form.password = '';
      this.form.name = '';
      this.form.mobile = '';
      this.form.permissionCodes = [];
      this.form.remark = '';
      this.form.accountId = null;

      // Clear validation messages after the DOM has updated
      this.$nextTick(() => {
        this.$refs.ruleFormRef.clearValidate();
      });

      // Reset the tree's visual state
      if (this.$refs.permissionTree) {
        this.$refs.permissionTree.setCheckedKeys([]);
      }

      if (newType === 'update') {
        this.loadSubAccountList();
      }
    }
  },
  created() {
    this.getPermissions();
  },
  methods: {
    getPermissions() {
      getAvailablePermissions().then((res) => {
        const availablePerms = (res && res.data && Array.isArray(res.data.data)) ? res.data.data : [];
        const menuList = (routerConfig && Array.isArray(routerConfig.menuList)) ? routerConfig.menuList : [];
        const filteredTree = filterTreeByPerms(menuList, availablePerms);
        this.permissionList = mapTreeForElTree(filteredTree);
      });
    },
    openResetPasswordDialog() {
      if (!this.form.accountId) {
        this.$message.error('请先选择要更新的账号');
        return;
      }
      this.resetPasswordDialogVisible = true;
    },
    handleResetPassword() {
      if (!this.newPassword) {
        this.$message.error('请输入新密码');
        return;
      }
      resetPassword(this.form.accountId, this.newPassword).then(() => {
        this.$message.success('密码重置成功');
        this.resetPasswordDialogVisible = false;
      });
    },
    handleTreeCheck() {
      // getCheckedKeys(true) will return an array of keys of the currently checked leaf nodes.
      this.form.permissionCodes = this.$refs.permissionTree.getCheckedKeys(true);
    },
    loadSubAccountList() {
      getSubAccountList().then(res => {
        this.subAccountList = res.data.data.data || [];
      });
    },
    handleAccountChange(accountId) {
      if (!accountId) return;
      getSubAccountDetail(accountId).then(res => {
        const accountDetails = res.data.data;
        this.form.name = accountDetails.name;
        this.form.mobile = accountDetails.mobile;
        this.form.remark = accountDetails.remark;
        this.form.permissionCodes = accountDetails.permissionCodes || [];
        this.form.enable = accountDetails.enabled;
        this.$nextTick(() => {
          this.$refs.permissionTree.setCheckedKeys(this.form.permissionCodes);
        });
      });
    },
    save() {
      this.$refs.ruleFormRef.validate((valid) => {
        if (valid) {
          if (this.form.operationType === 'create') {
            const createData = { ...this.form };
            if (createData.accountId === null) {
              delete createData.accountId;
            }
            createSubAccount(createData).then(() => {
              this.$message.success('创建成功');
              this.$refs.ruleFormRef.resetFields();
            });
          } else if (this.form.operationType === 'update') {
            if (!this.form.accountId) {
              this.$message.error('请先选择要更新的账号');
              return;
            }
            const updateData = {
              subAccountId: this.form.accountId,
              name: this.form.name,
              mobile: this.form.mobile,
              permissionCodes: this.form.permissionCodes,
              remark: this.form.remark,
              enabled: this.form.enable
            };
            updateSubAccount(updateData).then(() => {
              this.$message.success('更新成功');
              this.$refs.ruleFormRef.resetFields();
            });
          }
        }
      });
    }
  },
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>
