<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="AppId" prop="appId">
        <el-input
          v-model="queryParams.appId"
          placeholder="请输入AppId"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="账号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入归属账号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
      <!-- 销售名称（nickName） -->
      <el-form-item label="销售名称" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入销售名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- 归属组别（deptId） -->
      <el-form-item label="归属组别" prop="deptId">
        <el-cascader
          v-model="queryParams.deptId"
          :options="deptOptions"
          :props="cascaderProps"
          placeholder="请选择组别"
          clearable
          size="small"
          style="width: 200px"
          @change="handleDeptChange"
        />
      </el-form-item>
      <!-- 我的飞书应用勾选框 -->
      <el-form-item label="我的应用" prop="myAccount">
        <el-checkbox v-model="queryParams.myAccount"></el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="accountList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="AppId" align="center" prop="appId" min-width="180" />
      <el-table-column label="AppSecret" align="center" prop="appSecret" min-width="200" show-overflow-tooltip />
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            :disabled="!scope.row.isMyAccount"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="错误信息" align="center" prop="errorMsg" min-width="150" show-overflow-tooltip />
      <el-table-column label="归属账号" align="center" prop="phone" width="120" />
      <el-table-column label="所属分组" align="center" prop="deptName" width="120" />
      <el-table-column label="所属员工" align="center" prop="nickName" width="120" />
<!--      <el-table-column label="已使用次数" align="center" prop="numberUse" width="100" />-->
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- 仅当 isMyAccount 为 true 时显示修改和删除按钮 -->
          <el-button
            v-if="scope.row.isMyAccount"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-if="scope.row.isMyAccount"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增/修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="AppId" prop="appId">
          <el-input v-model="form.appId" placeholder="请输入飞书AppId" />
        </el-form-item>
        <el-form-item label="AppSecret" prop="appSecret">
          <el-input v-model="form.appSecret" placeholder="请输入飞书AppSecret" show-password />
        </el-form-item>
        <el-form-item label="归属手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入归属手机号" />
        </el-form-item>
        <el-form-item label="已使用次数" prop="numberUse">
          <el-input-number v-model="form.numberUse" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listFeishuAccount,
  getFeishuAccount,
  delFeishuAccount,
  addFeishuAccount,
  updateFeishuAccount,
  changeFeishuAccountStatus
} from "@/api/qw/feishuAccount";
// 导入部门树接口（根据实际路径调整）
import { treeselect } from "@/api/company/companyDept";
import {parseTime} from "../../../utils/common";

export default {
  name: "FeishuAccount",
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      accountList: [],
      title: '',
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        appId: null,
        phone: null,
        status: null,
        nickName: null,    // 销售名称
        deptId: null,      // 归属组别ID
        myAccount: true    // 默认勾选“我的飞书应用”
      },
      form: {
        id: null,
        appId: null,
        appSecret: null,
        status: 1,
        errorMsg: null,
        phone: null,
        numberUse: null
      },
      rules: {
        appId: [{ required: true, message: 'AppId不能为空', trigger: 'blur' }],
        appSecret: [{ required: true, message: 'AppSecret不能为空', trigger: 'blur' }]
      },
      // 部门树数据（用于归属组别下拉）
      deptOptions: [],
      // 级联选择器配置
      cascaderProps: {
        value: 'id',
        label: 'label',
        children: 'children',
        checkStrictly: true,   // 允许选择任意层级
        emitPath: false        // 只返回选中节点的 value（即 id）
      }
    };
  },
  created() {
    this.getList();
    this.getDeptTree(); // 加载部门树
  },
  methods: {
    parseTime,
    /** 查询账号列表 */
    getList() {
      this.loading = true;
      listFeishuAccount(this.queryParams).then(response => {
        this.accountList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 加载部门树 */
    getDeptTree() {
      treeselect()
        .then(response => {
          this.deptOptions = response.data || [];
        })
        .catch(() => {
          this.deptOptions = [];
        });
    },
    /** 搜索按钮 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置搜索 */
    resetQuery() {
      this.resetForm("queryForm");
      // 清空查询字段，并重置 myAccount 为 true
      this.queryParams.nickName = null;
      this.queryParams.deptId = null;
      this.queryParams.myAccount = true;
      this.handleQuery();
    },
    /** 归属组别变化时自动触发搜索 */
    handleDeptChange(value) {
      this.handleQuery();
    },
    /** 多选变化 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 重置表单 */
    reset() {
      this.form = {
        id: null,
        appId: null,
        appSecret: null,
        status: 1,
        errorMsg: null,
        phone: null,
        numberUse: null,
      };
      this.resetForm("form");
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 新增按钮 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增飞书应用账号";
    },
    /** 修改按钮 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids[0];
      getFeishuAccount(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改飞书应用账号";
      });
    },
    /** 提交表单 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateFeishuAccount(this.form).then(() => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFeishuAccount(this.form).then(() => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return delFeishuAccount(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      });
    },
    /** 状态切换 */
    handleStatusChange(row) {
      const newStatus = row.status;
      const oldStatus = newStatus === 1 ? 0 : 1; // 用于回滚
      const text = newStatus === 1 ? '启用' : '禁用';
      this.$confirm('确认要' + text + '该账号吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        changeFeishuAccountStatus({
          id: row.id,
          status: newStatus,
          errorMsg: newStatus === 1 ? '' : row.errorMsg
        }).then(() => {
          this.msgSuccess('状态修改成功');
          this.getList();
        }).catch(() => {
          // 恢复状态
          row.status = oldStatus;
        });
      }).catch(() => {
        // 恢复状态
        row.status = oldStatus;
      });
    }
  }
};
</script>
