<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">

      <el-form-item label="登录账号" prop="loginName">
        <el-input
          v-model="queryParams.loginName"
          placeholder="请输入登录账号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phonenumber">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入手机号码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户昵称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          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=""/>
          <el-option label="正常" value="0"/>
          <el-option label="停用" value="1"/>
        </el-select>
      </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="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['company:aiSipCallUser:aiSipCallUser:edit']"
        >修改
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="danger"-->
      <!--          plain-->
      <!--          icon="el-icon-delete"-->
      <!--          size="mini"-->
      <!--          :disabled="multiple"-->
      <!--          @click="handleDelete"-->
      <!--          v-hasPermi="['company:aiSipCallUser:aiSipCallUser:remove']"-->
      <!--        >删除</el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['company:aiSipCallUser:aiSipCallUser:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="aiSipCallUserList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
<!--      <el-table-column label="用户ID" align="center" prop="userId"/>-->
      <el-table-column label="登录账号" align="center" prop="loginName"/>
      <el-table-column label="用户姓名" align="center" prop="userName"/>
      <el-table-column label="手机号码" align="center" prop="phonenumber"/>
<!--      <el-table-column label="用户邮箱" align="center" prop="email"/>-->
      <el-table-column label="用户性别" align="center" prop="sex">
        <template slot-scope="scope">
          <span v-if="scope.row.sex == '0'">男</span>
          <span v-else-if="scope.row.sex == '1'">女</span>
          <span v-else-if="scope.row.sex == '2'">未知</span>
          <span v-else>{{ scope.row.sex }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户状态" align="center" prop="status">
        <template slot-scope="scope">
          <span v-if="scope.row.status == '0'">正常</span>
          <span v-else-if="scope.row.status == '1'">停用</span>
          <span v-else>{{ scope.row.status }}</span>
        </template>
      </el-table-column>
      <el-table-column label="绑定分机号" align="center" prop="extNum"/>
      <el-table-column label="绑定网关" align="center" prop="gatewayIds">
        <template slot-scope="scope">
          <span>{{ getGatewayNames(scope.row.gatewayIds) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['company:aiSipCall:aiSipCallUser:edit']"
          >修改
          </el-button>
          <!--          <el-button-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-delete"-->
          <!--            @click="handleDelete(scope.row)"-->
          <!--            v-hasPermi="['company:aiSipCallUser:aiSipCallUser:remove']"-->
          <!--          >删除</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"
    />

    <!-- 添加或修改 sip用户信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="登录账号" prop="loginName">
          <el-input v-model="form.loginName" placeholder="请输入登录账号" disabled/>
        </el-form-item>
        <el-form-item label="用户姓名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户姓名" disabled/>
        </el-form-item>
        <el-form-item label="登录密码" prop="password" v-if="!form.userId">
          <el-input v-model="form.password" placeholder="请输入密码" :type="passwordVisible ? 'text' : 'password'">
            <i slot="suffix" class="el-icon-view" style="cursor: pointer;" @click="togglePasswordVisible"></i>
          </el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入手机号码"/>
        </el-form-item>
        <el-form-item label="用户邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入用户邮箱"/>
        </el-form-item>
        <el-form-item label="用户性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择用户性别">
            <el-option label="男" :value="0"/>
            <el-option label="女" :value="1"/>
            <el-option label="未知" :value="2"/>
          </el-select>
        </el-form-item>
        <el-form-item label="用户状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择用户状态">
            <el-option label="正常" :value="0"/>
            <el-option label="停用" :value="1"/>
          </el-select>
        </el-form-item>
        <el-form-item label="绑定分机号" prop="extNum">
          <el-select v-model="form.extNum" placeholder="请选择绑定的分机号" clearable filterable>
            <el-option
              v-for="item in extNumOptions"
              :key="item.extId"
              :label="item.extNum"
              :value="item.extNum"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="网关" prop="gatewayIds">
          <el-select v-model="selectedGateways" placeholder="请选择网关" multiple collapse-tags>
            <el-option
                      v-for="item in gateways"
                      :key="item.id"
                      :label="item.gwDesc"
                      :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </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 {
  listAiSipCallUser,
  getAiSipCallUser,
  delAiSipCallUser,
  addAiSipCallUser,
  updateAiSipCallUser,
  exportAiSipCallUser,
  getUnBindExtnum
} from "@/api/aiSipCall/aiSipCallUser";
import {remoteList} from "../../api/aiSipCall/aiSipCallGateway";

export default {
  name: "AiSipCallUser",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // sip用户信息表格数据
      aiSipCallUserList: [],
      // 分机号码下拉选项
      extNumOptions: [],
      //网关列表
      gateways: [],
      // 选中的网关
      selectedGateways: [],
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        loginName: null,
        userName: null,
        userType: null,
        email: null,
        phonenumber: null,
        sex: null,
        avatar: null,
        password: null,
        salt: null,
        status: null,
        loginIp: null,
        loginDate: null,
        pwdUpdateDate: null,
        logo: null,
        companyUserId: null,
        extNum: null
      },
      // 表单参数
      form: {
        password: '123456'
      },
      // 是否显示密码明文
      passwordVisible: false,
      // 弹窗标题
      title: "",
      // 表单校验
      rules: {
        loginName: [
          {required: true, message: "登录账号不能为空", trigger: "blur"}
        ],
        password: [
          {required: true, message: "登录密码不能为空", trigger: "blur"}
        ],
        userName: [
          {required: true, message: "用户姓名不能为空", trigger: "blur"}
        ],
        extNum: [
          {required: true, message: "绑定的分机号不能为空", trigger: "change"}
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleUpdateById(id) {
      this.reset();
      getAiSipCallUser(id).then(response => {
        if (response && response.data) {
          this.form = {...response.data};
          // 将 status 转换为数字类型，确保与 el-option 的 value 类型一致
          this.form.status = Number(this.form.status);
          this.form.sex = Number(this.form.sex);
          // 修改时将密码设置为 null，不显示密码输入框
          this.form.password = null;
          // 如果有网关字符串，分割为数组并转换为数字类型
          if (this.form.gatewayIds) {
            this.selectedGateways = this.form.gatewayIds.split(',').map(id => Number(id));
          }
          // 获取最新的未绑定分机号列表
          getUnBindExtnum().then(res => {
            this.extNumOptions = res.data || [];
          });
          // 获取网关列表
          remoteList({ pageNum:1, pageSize: 500,params:{purposes: [1, 3]} }).then(response => {
            this.gateways = response.rows || [];
          });
          this.open = true;
          // 显示具体的员工姓名
          const employeeName = this.form.userName || '未知角色';
          this.title = `修改 sip 外呼角色角色 - ${employeeName}`;
        } else {
          this.$message.error("获取 sip 外呼角色信息失败");
        }
      }).catch(error => {
        console.error("获取 sip 外呼角色信息失败:", error);
        this.$message.error("获取 sip 外呼角色信息失败");
      });
    },
    /** 添加公司用户 */
    handleAddCompanyUserOnSip(userName, nickName, userId) {
      this.reset();
      this.form.userName = nickName;
      this.form.loginName = userName;
      this.form.companyUserId = userId;

      // 设置默认启用状态为 0（启用）
      this.form.status = 0;
      this.form.sex = 0;

      // 获取最新的未绑定分机号列表
      getUnBindExtnum().then(response => {
        this.extNumOptions = response.data || [];
      });

      // 获取网关列表
      remoteList({ pageNum:1, pageSize: 500,params:{purposes: [1, 3]} }).then(response => {
        this.gateways = response.rows || [];
      });

      this.open = true;
      // 显示具体的员工姓名
      const employeeName = nickName || '未知员工';
      this.title = `添加 sip 外呼角色 - ${employeeName}`;
    },
    /** 查询sip用户信息列表 */
    getList() {
      this.loading = true;
      // 先获取网关列表
      remoteList({ pageNum:1, pageSize: 500,params:{purposes: [1, 3]} }).then(response => {
        this.gateways = response.rows || [];
        // 再获取用户列表
        listAiSipCallUser(this.queryParams).then(response => {
            this.aiSipCallUserList = response.rows;
            this.total = response.total;
            this.loading = false;
        });
      }).catch(() => {
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        password: '123456'
      };
      this.selectedGateways = [];
      this.passwordVisible = false;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加 sip用户信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const userId = row.userId || this.ids
      getAiSipCallUser(userId).then(response => {
        this.form = response.data;
        // 将 status 转换为数字类型，确保与 el-option 的 value 类型一致
        this.form.status = Number(this.form.status);
        this.form.sex = Number(this.form.sex);
        // 修改时将密码设置为 null，不显示密码输入框
        this.form.password = null;
        // 如果有网关字符串，分割为数组并转换为数字类型
        if (this.form.gatewayIds) {
          this.selectedGateways = this.form.gatewayIds.split(',').map(id => Number(id));
        }
        // 获取最新的未绑定分机号列表
        getUnBindExtnum().then(res => {
          this.extNumOptions = res.data || [];
        });
        // 获取网关列表
        remoteList({ pageNum:1, pageSize: 500,params:{purposes: [1, 3]} }).then(response => {
          this.gateways = response.rows || [];
          this.open = true;
          this.title = "修改 sip 用户信息";
        });
      });
    },
    // 切换密码显示/隐藏
    togglePasswordVisible() {
      this.passwordVisible = !this.passwordVisible;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
            // 将选中的网关数组用逗号拼接成字符串
            this.form.gatewayIds = this.selectedGateways.join(',');

            if (this.form.userId != null) {
            updateAiSipCallUser(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              // 通知父组件刷新数据
              this.$emit('refreshParentData');
            });
          } else {
            addAiSipCallUser(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              // 通知父组件刷新数据
              this.$emit('refreshParentData');
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$confirm('是否确认删除sip用户信息编号为"' + userIds + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delAiSipCallUser(userIds);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有 sip 用户信息数据项？', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportAiSipCallUser(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {
      })
    },
    /** 根据网关 IDs 获取网关名称 */
    getGatewayNames(gatewayIds) {
      if (!gatewayIds) {
          return '';
      }
      const ids = gatewayIds.split(',').map(id => Number(id));
      const names = ids
          .map(id => {
              const gateway = this.gateways.find(gw => gw.id === id);
              return gateway ? gateway.gwDesc : '';
          })
          .filter(name => name);
      return names.join(', ');
    }
  }
};
</script>
