<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="网关用途" prop="purpose">
        <el-select
          v-model="queryParams.purpose"
          placeholder="请选择网关用途"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        >
          <el-option label="全部" value="" />
          <el-option label="已废弃" :value="0" />
          <el-option label="电话条" :value="1" />
          <el-option label="外呼任务" :value="2" />
          <el-option label="无限制" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="网关名称" prop="gwName">
        <el-input
          v-model="queryParams.gwName"
          placeholder="请输入网关名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="profile" prop="profileName">
        <el-select
          v-model="queryParams.profileName"
          placeholder="请选择profile"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        >
          <el-option label="全部" value="" />
          <el-option label="external" value="extemal" />
          <el-option label="internal" value="internal" />
        </el-select>
      </el-form-item>
      <el-form-item label="主叫号码" prop="caller">
        <el-input
          v-model="queryParams.caller"
          placeholder="请输入主叫号码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="被叫前缀" prop="calleePrefix">
        <el-input
          v-model="queryParams.calleePrefix"
          placeholder="请输入被叫前缀"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </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"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['platform:aiSipCall:gateway:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['platform:aiSipCall:gateway: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="['platform:aiSipCall:gateway: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="['platform:aiSipCall:gateway:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="aiSipCallList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="网关名称" align="center" prop="gwName" />
      <el-table-column label="网关用途" align="center" prop="purpose">
        <template slot-scope="scope">
          <span>{{ purposeFormat(scope.row.purpose) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="profile" align="center" prop="profileName" />

      <el-table-column label="主叫号码" align="center" prop="caller" />
      <el-table-column label="网关地址" align="center" prop="gwAddr" />
      <el-table-column label="网关名称描述;" align="center" prop="gwDesc" />
      <el-table-column label="网关最大并发数" align="center" prop="maxConcurrency" />
      <el-table-column label="认证用户名" align="center" prop="authUsername" />
      <el-table-column label="是否认证注册" align="center" prop="register">
        <template slot-scope="scope">
          <span>{{ registerFormat(scope.row.register) }}</span>
        </template>
      </el-table-column>
      <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="['platform:aiSipCall:gateway:edit']"-->
<!--          >修改</el-button>-->
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['platform:aiSipCall:gateway: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"
    />

    <!-- 添加或修改aiSIP外呼网关对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="网关名称" prop="gwName">
          <el-input v-model="form.gwName" placeholder="请输入网关名称" />
        </el-form-item>
        <el-form-item label="网关用途" prop="purpose">
          <el-select
            v-model="form.purpose"
            placeholder="请选择网关用途"
            clearable
            size="small"
          >
            <el-option label="已废弃" :value="0" />
            <el-option label="电话条" :value="1" />
            <el-option label="外呼任务" :value="2" />
            <el-option label="无限制" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="profile" prop="profileName">
          <el-select
            v-model="form.profileName"
            placeholder="请选择profile"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          >
            <el-option label="external" value="extemal" />
            <el-option label="internal" value="internal" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否认证注册" prop="register">
          <el-select
            v-model="form.register"
            placeholder="请选择认证注册方式"
            clearable
            size="small"
          >
            <el-option label="对接模式" :value="0" />
            <el-option label="注册模式" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="网关地址" prop="gwAddr">
          <el-input v-model="form.gwAddr" placeholder="请输入网关地址" />
        </el-form-item>
        <el-form-item label="被叫前缀" prop="calleePrefix">
          <el-input v-model="form.calleePrefix" placeholder="请输入被叫前缀" />
        </el-form-item>
        <el-form-item label="外呼语音编码" prop="codec">
          <el-input v-model="form.codec" placeholder="请输入外呼语音编码" />
        </el-form-item>
        <el-form-item label="网关名称描述;" prop="gwDesc">
          <el-input v-model="form.gwDesc" placeholder="请输入网关名称描述;" />
        </el-form-item>
        <el-form-item label="网关最大并发数" prop="maxConcurrency">
          <el-input v-model="form.maxConcurrency" placeholder="请输入网关最大并发数" />
        </el-form-item>
        <el-form-item label="使用优先级" prop="priority">
          <el-input v-model="form.priority" placeholder="数字1-9 数字越小,越优先被使用" />
        </el-form-item>
        <el-form-item label="主叫号码" prop="caller">
          <el-input v-model="form.caller" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="配置项">
          <el-button type="primary" size="mini" @click="addConfigItem">增加配置项</el-button>
          <div v-for="(item, index) in configItems" :key="index" class="config-item-row">
            <el-input v-model="item.key" placeholder="请输入参数名" style="width: 45%; margin-right: 10px;" />
            <el-input v-model="item.value" placeholder="请输入参数值" style="width: 45%; margin-right: 10px;" />
            <el-button type="danger" size="mini" @click="removeConfigItem(index)">删除</el-button>
          </div>
        </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 { listAiSipCallGateway, getAiSipCallGateway, delAiSipCallGateway, addAiSipCallGateway, updateAiSipCallGateway, exportAiSipCallGateway,remoteList } from "@/api/aiSipCall/aiSipCallGateway";

export default {
  name: "aiSipCallGateway",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // aiSIP外呼网关表格数据
      aiSipCallList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        gwName: null,
        profileName: null,
        caller: null,
        calleePrefix: null,
        gwAddr: null,
        codec: null,
        gwDesc: null,
        maxConcurrency: null,
        authUsername: null,
        authPassword: null,
        priority: null,
        register: null,
        configs: null,
        purpose: null,
        remoteGatewayId: null
      },
      // 表单参数
      form: {},
      // 配置项列表
      configItems: [],
      // 表单校验
      rules: {
        gwName: [
          { required: true, message: "网关名称不能为空", trigger: "blur" },
          { pattern: /^[a-zA-Z][a-zA-Z0-9]*$/, message: "网关名称必须以字母开头，且只能包含字母和数字", trigger: "blur" }
        ],
        purpose: [
          { required: true, message: "网关用途不能为空", trigger: "blur" }
        ],
        profileName: [
          { required: true, message: "profile名称不能为空", trigger: "blur" }
        ],
        register: [
          { required: true, message: "是否认证注册不能为空", trigger: "blur" }
        ],
        gwAddr: [
          { required: true, message: "网关地址不能为空", trigger: "blur" }
        ],
        codec: [
          { required: true, message: "外呼语音编码不能为空", trigger: "blur" }
        ],
        gwDesc: [
          { required: true, message: "网关名称描述不能为空", trigger: "blur" }
        ],
        maxConcurrency: [
          { required: true, message: "网关最大并发数不能为空", trigger: "blur" }
        ],
        priority: [
          { required: true, message: "使用优先级不能为空", trigger: "blur" }
        ],
        caller: [
          { required: true, message: "主叫号码不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询aiSIP外呼网关列表 */
    getList() {
        this.loading = true;
        // listAiSipCallGateway(this.queryParams).then(response => {
        //   this.aiSipCallList = response.rows;
        //   this.total = response.total;
        //   this.loading = false;
        // });
        remoteList(this.queryParams).then(response => {
            this.aiSipCallList = response.rows;
            this.total = response.total;
            this.loading = false;
        });

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        gwName: null,
        profileName: 'extemal',
        caller: null,
        calleePrefix: null,
        gwAddr: null,
        codec: null,
        gwDesc: null,
        maxConcurrency: null,
        authUsername: null,
        authPassword: null,
        priority: null,
        updateTime: null,
        register: 0,
        configs: null,
        purpose: 0,
        remoteGatewayId: null
      };
      this.configItems = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加aiSIP外呼网关";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAiSipCallGateway(id).then(response => {
        this.form = response.data;
        // 解析配置项 JSON 字符串
        if (this.form.configs) {
          try {
            const parsedConfigs = JSON.parse(this.form.configs);
            if (Array.isArray(parsedConfigs)) {
              this.configItems = parsedConfigs.map(item => ({ key: item.key, value: item.value }));
            } else if (typeof parsedConfigs === 'object') {
              this.configItems = Object.entries(parsedConfigs).map(([key, value]) => ({ key, value }));
            }
          } catch (e) {
            console.error('解析配置项失败:', e);
            this.configItems = [];
          }
        }
        this.open = true;
        this.title = "修改 aiSIP 外呼网关";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 将配置项转换为 JSON 字符串
          if (this.configItems.length > 0) {
            const configsObj = {};
            this.configItems.forEach(item => {
              if (item.key && item.value !== undefined && item.value !== null) {
                configsObj[item.key] = item.value;
              }
            });
            this.form.configs = Object.keys(configsObj).length > 0 ? JSON.stringify(configsObj) : null;
          } else {
            this.form.configs = null;
          }

          if (this.form.id != null) {
            updateAiSipCallGateway(this.form).then(() => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAiSipCallGateway(this.form).then(() => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除aiSIP外呼网关编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delAiSipCallGateway(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有 aiSIP 外呼网关数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportAiSipCallGateway(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },
    /** 网关用途格式化 */
    purposeFormat(value) {
      if (value === null || value === undefined || value === '') {
        return '';
      }
      const purposeMap = {
        0: '已废弃',
        1: '电话条',
        2: '外呼任务',
        3: '无限制'
      };
      return purposeMap[value] || '未知';
    },
    /** 认证注册方式格式化 */
    registerFormat(value) {
      if (value === null || value === undefined || value === '') {
        return '';
      }
      const registerMap = {
        0: '对接模式',
        1: '注册模式'
      };
      return registerMap[value] || '未知';
    },
    /** 增加配置项 */
    addConfigItem() {
      this.configItems.push({ key: '', value: '' });
    },
    /** 删除配置项 */
    removeConfigItem(index) {
      this.configItems.splice(index, 1);
    }
  }
};
</script>

<style scoped>
.config-item-row {
  display: flex;
  align-items: center;
  margin-top: 10px;
}
</style>
