<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="企业CorpID" prop="corpId">
        <el-input
          v-model="queryParams.corpId"
          placeholder="请输入企业CorpID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="企业名称" prop="corpName">
        <el-input
          v-model="queryParams.corpName"
          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
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </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="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['qw:qwCompany: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="['qw:qwCompany: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="['qw:qwCompany: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="['qw:qwCompany:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-s-grid"
          size="mini"
          :disabled="single"
          @click="handleSelectArea"
          v-hasPermi="['qw:qwCompany:edit']"
        >选择区域</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="qwCompanyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="企业CorpID" align="center" prop="corpId" />
      <el-table-column label="企业名称" align="center" prop="corpName" />
      <el-table-column label="关联公司" align="center" prop="companyIds" >
        <template slot-scope="scope">
          <div v-for="company in (scope.row.companyIds).split(',') ">
            <span v-for="com in companys" v-if="com.companyId==company">{{com.companyName }} </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="关联区域" align="center" prop="addressBindIp">
        <template slot-scope="scope">
          <span v-if="scope.row.addressBindIp">{{ getAddressLabels(scope.row.addressBindIp) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="statusOptions" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180"/>
      <el-table-column label="更改时间" align="center" prop="updateTime" width="180"/>
      <el-table-column label="所属服务器" align="center" prop="companyServerNum" />
      <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="['qw:qwCompany:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['qw:qwCompany: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"
    />

    <!-- 添加或修改企微主体对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="200px">
        <el-form-item label="企业CorpID" prop="corpId">
          <el-input v-model="form.corpId" placeholder="请输入企业CorpID" />
        </el-form-item>
        <el-form-item label="企业名称" prop="corpName">
          <el-input v-model="form.corpName" placeholder="请输入企业名称" />
        </el-form-item>
        <el-form-item label="服通讯录Secret" prop="serverBookSecret">
          <el-input v-model="form.serverBookSecret" placeholder="请输入服务商的通讯录Secret" />
        </el-form-item>
       <el-form-item label="应用Secret" prop="openSecret">
          <el-input v-model="form.openSecret" placeholder="请输入服务商应用的Secret" />
        </el-form-item>
        <!-- <el-form-item label="服务商应用的企业id" prop="openCorpId">
          <el-input v-model="form.openCorpId" placeholder="请输入服务商应用的企业id" />
        </el-form-item>
        <el-form-item label="服务商应用serverAgentId" prop="serverAgentId">
          <el-input v-model="form.serverAgentId" placeholder="请输入服务商应用serverAgentId" />
        </el-form-item>
        <el-form-item label="服务商通讯录企业id" prop="serverBookCorpId">
          <el-input v-model="form.serverBookCorpId" placeholder="请输入服务商通讯录企业id" />
        </el-form-item>

        <el-form-item label="通用开发参数" prop="providerSecret">
          <el-input v-model="form.providerSecret" placeholder="请输入通用开发参数" />
        </el-form-item> -->
        <el-form-item label="Token" prop="token" >
          <el-input v-model="form.token" placeholder="请输入Token" :readonly="true"/>
        </el-form-item>
        <el-form-item label="EncodingAESKey" prop="encodingAesKey" >
          <el-input v-model="form.encodingAesKey" placeholder="请输入EncodingAESKey" :readonly="true"/>
        </el-form-item>

        <el-form-item label="域名地址" prop="realmNameUrl">
          <el-input v-model="form.realmNameUrl" placeholder="请输入域名地址" />
        </el-form-item>

        <el-form-item label="应用回调地接" prop="notifyUrl" >
          <el-input v-model="form.notifyUrl" placeholder="请输入应用回调地接" :readonly="true"/>
        </el-form-item>
        <el-form-item label="应用id" prop="serverAgentId" >
          <el-input v-model="form.serverAgentId" placeholder="请输入serverAgentId" />
        </el-form-item>
        <el-form-item label="小程序id" prop="miniAppId" >
          <el-select
            v-model="form.miniAppId"
            placeholder="请选择"
            size="small"
          >
            <el-option
              v-for="item in miniAppList"
              :key="item.appId"
              :label="item.appName"
              :value="item.appId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客服服务器" prop="companyServerNum" >
          <el-input-number
            v-model="form.companyServerNum"
            :min="1"
            :max="20"
            placeholder="客服服务器"
          >
          </el-input-number>
        </el-form-item>
        <el-form-item label="企业可信IP" >
          <div>42.194.245.189;119.29.195.254;129.204.130.233;43.138.187.210;129.204.76.229;159.75.239.132119.29.249.66;122.152.230.82</div>
        </el-form-item>
        <el-form-item label="聊天工具栏跳转地址" prop="chatToolbar">
          <el-input v-model="form.chatToolbar" placeholder="请输入聊天工具栏跳转地址" />
        </el-form-item>
        <el-form-item label="聊天工具栏实际运用地址" prop="chatToolbarOauth">
          <el-input v-model="form.chatToolbarOauth" placeholder="请输入聊天工具栏实际运用地址" />
        </el-form-item>
        <el-form-item label="app分享小程序原始id" prop="shareAppId">
          <el-input v-model="form.shareAppId" placeholder="app分享小程序原始id" />
        </el-form-item>
        <el-form-item label="app分享小程序应用id" prop="shareAgentId">
          <el-input v-model="form.shareAgentId" placeholder="app分享小程序应用id" />
        </el-form-item>
        <el-form-item label="app分享小程序schma" prop="shareSchema">
          <el-input v-model="form.shareSchema" placeholder="app分享小程序schema" />
        </el-form-item>
        <el-form-item label="关联公司" prop="companyIds">

          <el-select filterable  v-model="form.companyIds" remote multiple placeholder="请选择公司名"  clearable style="width: 50%;">
                <el-option
                  v-for="item in companys"
                  :key="item.companyId"
                  :label="item.companyName"
                  :value="item.companyId"
                />
          </el-select>


        </el-form-item>
        <el-form-item label="关联区域" prop="addressBindIp">
          <el-select filterable v-model="form.addressIds" multiple placeholder="请选择区域" clearable style="width: 50%;">
            <el-option
              v-for="item in availableAddressList"
              :key="item.ip"
              :label="item.title +(item.ip)"
              :value="item.ip"
              :disabled="item.disabled"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)"
            >{{dict.dictLabel}}</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>

    <!-- 选择区域弹窗 -->
    <el-dialog :title="areaDialogTitle" :visible.sync="areaDialogVisible" width="800px" append-to-body>
      <el-form :inline="true">
        <el-form-item label="筛选区域">
          <el-input v-model="areaFilter" placeholder="输入区域名称筛选" clearable size="small" style="width: 200px;" />
        </el-form-item>
      </el-form>
      <el-table
        :data="filteredAddressList"
        @selection-change="handleAreaSelectionChange"
        ref="areaTable"
        max-height="400"
      >
        <el-table-column type="selection" width="55" align="center" :selectable="checkSelectable" />
        <el-table-column label="区域IP" align="center" prop="ip" />
        <el-table-column label="标题" align="center" prop="title" />
        <el-table-column label="地址ID" align="center" prop="addressId" />
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <el-tag v-if="boundAddrIds.indexOf(scope.row.ip) > -1" type="danger">已被其他主体绑定</el-tag>
            <el-tag v-else-if="currentAreaSelection.indexOf(scope.row.ip) > -1" type="success">当前选中</el-tag>
            <el-tag v-else type="info">未绑定</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAreaSelection">确 定</el-button>
        <el-button @click="areaDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listQwCompany, getQwCompany, delQwCompany, addQwCompany, updateQwCompany, exportQwCompany, allCorp } from "@/api/qw/qwCompany";
import { getCompanyList } from "@/api/company/company";
import { listAll } from '@/api/course/coursePlaySourceConfig'
import { listDisQwIpadServer } from '@/api/qw/qwIpadServer'
export default {
  name: "QwCompany",
  watch: {
      'form.realmNameUrl': function(newVal) {
        if(newVal==null){
          this.form.notifyUrl="输入域名地址生成";
        }else{
           this.form.notifyUrl = "http://"+newVal+"/qw/data/"+this.form.corpId;
        }

      },
      'form.corpId': function(newVal) {
          if (this.form.realmNameUrl !== null) {
            this.form.notifyUrl = this.form.realmNameUrl + "/qw/data/" + newVal;
          }
        }
    },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 企微主体表格数据
      qwCompanyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        corpId: null,
        corpName: null,
        openSecret: null,
        openCorpId: null,
        serverAgentId: null,
        serverBookCorpId: null,
        serverBookSecret: null,
        token: null,
        encodingAesKey: null,
        providerSecret: null,
        realmNameUrl: null,
        notifyUrl: null,
        chatToolbar: null,
        chatToolbarOauth: null,
        companyIds: null,
        status: null,
      },
      // 表单参数
      form: {},
      companys:[],
      maAppList:[],
      miniAppList:[],
      customAppList:[],
      // 区域选择相关
      areaDialogVisible: false,
      areaDialogTitle: "",
      areaList: [],
      areaFilter: "",
      currentAreaSelection: [],
      currentCompanyForArea: null,
      boundAddrIds: [],
      currentAddrIdsForForm: [],
      // 表单校验
      rules: {
        corpId: [{ required: true, message: '请输入企业CorpID', trigger: 'blur' }],
        realmNameUrl: [{ required: true, message: '请输入域名地址', trigger: 'blur' }],
        corpName: [{ required: true, message: '请输入名称', trigger: 'blur' }],

      }
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_company_status").then(response => {
      this.statusOptions = response.data;
    });
    getCompanyList().then(response => {
        this.companys = response.data;

    });
    // 加载区域列表用于表格展示
    listDisQwIpadServer({ pageNum: 1, pageSize: 9999 }).then(response => {
      this.areaList = this.normalizeAreaData(response.rows || response.data || []);
    });
  },
  methods: {
    /** 查询企微主体列表 */
    getList() {
      this.loading = true;
      listQwCompany(this.queryParams).then(response => {
        this.qwCompanyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        corpId: null,
        corpName: null,
        openSecret: null,
        openCorpId: null,
        serverAgentId: null,
        serverBookCorpId: null,
        serverBookSecret: null,
        token: null,
        encodingAesKey: null,
        providerSecret: null,
        realmNameUrl: null,
        notifyUrl: null,
        chatToolbar: null,
        chatToolbarOauth: null,
        companyIds: null,
        addressIds: [],
        status: 0,
        createTime: null,
        updateTime: null,
        createBy: null,
        shareAppId: null,
        shareAgentId: null,
        shareSchema: null,
        companyServerNum:null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    getAppList() {
      this.maAppList = []
      this.miniAppList = []
      this.customAppList = []
      listAll().then(response => {
        const { code, data } = response
        if (code === 200) {
          if (data) {
            this.maAppList = data.filter(v => v.type == 2).map(v => {
              return { appId: v.appid, appName: v.name }
            })
            this.miniAppList = data.filter(v => v.type == 1).map(v => {
              return { appId: v.appid, appName: v.name }
            })
            this.customAppList = data.filter(v => v.type == 3).map(v => {
              return { appId: v.appid, appName: v.name }
            })
          }
        }
      })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getAppList()
      this.loadAddressListForForm(null).then(() => {
        this.open = true;
      });
      this.form.token="1o62d3YxvdHd4LEUiltnu7sK";
      this.form.encodingAesKey="UJfTQ5qKTKlegjkXtp1YuzJzxeHlUKvq5GyFbERN1iU";
      this.title = "添加企微主体";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getAppList()
      const id = row.id || this.ids
      getQwCompany(id).then(response => {
        this.form = response.data;
        this.form.companyIds=((this.form.companyIds).split(",")).map(Number)
        this.$set(this.form, 'addressIds', this.form.addressBindIp ? this.form.addressBindIp.split(",") : []);
        this.loadAddressListForForm(this.form.corpId).then(() => {
          this.open = true;
        });
        this.title = "修改企微主体";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {

           this.form.companyIds = (this.form.companyIds).join(',');
           if (this.form.addressIds && this.form.addressIds.length > 0) {
             this.form.addressBindIp = this.form.addressIds.join(',');
           } else {
             this.form.addressBindIp = '';
           }
          // 提交前校验ip唯一性
          const doSubmit = () => {
            if (this.form.id != null) {
              updateQwCompany(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addQwCompany(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          };
          if (this.form.addressIds && this.form.addressIds.length > 0) {
            allCorp().then(corpRes => {
              const allCorps = corpRes.data || [];
              const boundIps = [];
              allCorps.forEach(corp => {
                if (corp.corpId !== this.form.corpId && corp.addressBindIp) {
                  corp.addressBindIp.split(",").forEach(id => {
                    if (id && boundIps.indexOf(id) === -1) boundIps.push(id);
                  });
                }
              });
              const conflictIps = this.form.addressIds.filter(ip => boundIps.indexOf(ip) > -1);
              if (conflictIps.length > 0) {
                this.$message.error("以下IP已被其他主体绑定，不能重复绑定：" + conflictIps.join(", "));
                return;
              }
              doSubmit();
            });
          } else {
            doSubmit();
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除企微主体编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delQwCompany(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有企微主体数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportQwCompany(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },
    /** 加载表单中可选区域列表 */
    loadAddressListForForm(currentCompanyId) {
      return Promise.all([
        listDisQwIpadServer({ pageNum: 1, pageSize: 9999 }),
        allCorp()
      ]).then(([serverRes, corpRes]) => {
        this.areaList = this.normalizeAreaData(serverRes.rows || serverRes.data || []);
        const allCorps = corpRes.data || [];
        this.boundAddrIds = [];
        this.currentAddrIdsForForm = currentCompanyId
          ? ((allCorps.find(c => c.corpId === currentCompanyId) || {}).addressBindIp || "").split(",").filter(Boolean)
          : [];
        allCorps.forEach(corp => {
          if (corp.corpId !== currentCompanyId && corp.addressBindIp) {
            const ids = corp.addressBindIp.split(",");
            ids.forEach(id => {
              if (id && this.boundAddrIds.indexOf(id) === -1) {
                this.boundAddrIds.push(id);
              }
            });
          }
        });
      });
    },
    /** 打开选择区域弹窗 */
    handleSelectArea() {
      const ids = this.ids;
      if (!ids || ids.length === 0) {
        this.$message.warning("请先选择一条企微主体记录");
        return;
      }
      const currentRow = this.qwCompanyList.find(item => item.id === ids[0]);
      if (!currentRow) {
        return;
      }
      this.currentCompanyForArea = currentRow;
      this.areaDialogTitle = "选择区域 - " + currentRow.corpName;
      this.currentAreaSelection = currentRow.addressBindIp ? currentRow.addressBindIp.split(",") : [];
      const preSelectedIps = [...this.currentAreaSelection];
      this.areaFilter = "";

      // 加载区域列表和已绑定的addressId
      Promise.all([
        listDisQwIpadServer({ pageNum: 1, pageSize: 9999 }),
        allCorp()
      ]).then(([serverRes, corpRes]) => {
        this.areaList = this.normalizeAreaData(serverRes.rows || serverRes.data || []);
        const allCorps = corpRes.data || [];
        // 收集所有已被其他主体绑定的addressId（排除当前主体）
        this.boundAddrIds = [];
        allCorps.forEach(corp => {
          if (corp.corpId !== currentRow.corpId && corp.addressBindIp) {
            const ids = corp.addressBindIp.split(",");
            ids.forEach(id => {
              if (id && this.boundAddrIds.indexOf(id) === -1) {
                this.boundAddrIds.push(id);
              }
            });
          }
        });
        this.areaDialogVisible = true;
        // 在表格中回显已选中的行（延时确保表格渲染完毕）
        this.$nextTick(() => {
          setTimeout(() => {
            if (this.$refs.areaTable) {
              this.areaList.forEach(row => {
                if (preSelectedIps.indexOf(row.ip) > -1 && this.boundAddrIds.indexOf(row.ip) === -1) {
                  this.$refs.areaTable.toggleRowSelection(row, true);
                }
              });
            }
          }, 100);
        });
      });
    },
    /** 区域表格多选变化 */
    handleAreaSelectionChange(selection) {
      // 当前可以被选中的（排除已被其他主体绑定的）
      const validSelection = selection.filter(row => this.boundAddrIds.indexOf(row.ip) === -1);
      this.currentAreaSelection = validSelection.map(row => row.ip);
    },
    /** 控制行是否可选（已被其他主体绑定的不可选） */
    checkSelectable(row) {
      return this.boundAddrIds.indexOf(row.ip) === -1;
    },
    /** 提交区域选择 */
    submitAreaSelection() {
      if (!this.currentCompanyForArea) {
        return;
      }
      // 提交前实时校验：保证选中的ip没有被其他主体绑定
      allCorp().then(corpRes => {
        const allCorps = corpRes.data || [];
        const boundIps = [];
        allCorps.forEach(corp => {
          if (corp.corpId !== this.currentCompanyForArea.corpId && corp.addressBindIp) {
            corp.addressBindIp.split(",").forEach(id => {
              if (id && boundIps.indexOf(id) === -1) boundIps.push(id);
            });
          }
        });
        const conflictIps = this.currentAreaSelection.filter(ip => boundIps.indexOf(ip) > -1);
        if (conflictIps.length > 0) {
          this.$message.error("以下IP已被其他主体绑定，不能重复绑定：" + conflictIps.join(", "));
          return;
        }
        const addressBindIp = this.currentAreaSelection.join(",");
        const data = {
          id: this.currentCompanyForArea.id,
          addressBindIp: addressBindIp
        };
        updateQwCompany(data).then(() => {
          this.msgSuccess("区域选择成功");
          this.areaDialogVisible = false;
          this.getList();
        });
      });
    },
    /** 统一区域数据格式（兼容字符串数组和对象数组） */
    normalizeAreaData(data) {
      return (data || []).map(item => {
        if (typeof item === 'string') {
          return { ip: item, title: '', addressId: '' };
        }
        return item;
      });
    },
    getAddressLabels(addressIdStr) {
      if (!addressIdStr || !this.areaList.length) {
        return addressIdStr || "";
      }
      const ids = addressIdStr.split(",");
      return ids.map(id => {
        const item = this.areaList.find(a => a.ip === id);
        return item ? (item.ip || id) : id;
      }).join("、");
    }
  },
  computed: {
    /** 筛选后的区域列表 */
    filteredAddressList() {
      if (!this.areaFilter) {
        return this.areaList;
      }
      const filter = this.areaFilter.toLowerCase();
      return this.areaList.filter(item =>
        (item.ip && item.ip.toLowerCase().indexOf(filter) > -1) ||
        (item.title && item.title.toLowerCase().indexOf(filter) > -1) ||
        (item.addressId && item.addressId.toLowerCase().indexOf(filter) > -1)
      );
    },
    /** 表单中可选区域列表（排除已被其他主体绑定的） */
    availableAddressList() {
      if (!this.areaList.length) {
        return [];
      }
      const currentFormCorpId = this.form.corpId;
      const result = this.areaList.map(item => {
        const isBoundToOther = this.boundAddrIds.indexOf(item.ip) > -1;
        // 编辑时，当前主体已绑定的地址应该可选
        const isCurrentOwn = currentFormCorpId && this.currentAddrIdsForForm && this.currentAddrIdsForForm.indexOf(item.ip) > -1;
        return {
          ...item,
          disabled: isBoundToOther && !isCurrentOwn
        };
      });
      return result;
    }
  }
};
</script>
