<template>
  <el-tabs type="border-card">
    <el-tab-pane label="我的链属">
      <el-card class="fiche">
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList">收起</right-toolbar>
          <span style="margin-bottom: 10px;color:#333333;font:14px Helvetica Neue, Helvetica, PingFang SC, Tahoma, Arial,sans-serif">所选条件:</span>
         <div  style="float: right;margin-right:1%">
            <el-button type="cyan"  icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"  style="float: ;">重置</el-button>
              <column-setting :checkList="checkList" :tableList="tableList" :selfDom="selfDom" :tableId="tableId" style="margin-left:5px"></column-setting>
         </div>
         <hr  style="margin-top: 16px;">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="企业名称" prop="companyName">
        <el-input
          maxlength="30"
          v-model="queryParams.companyName"
          placeholder="请输入企业名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="社会统一代码" prop="scySocialCode" >
        <el-input
          maxlength="30"
          v-model="queryParams.scySocialCode"
          placeholder="请输入社会统一代码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
        <el-form-item label="链属状态" prop="scrStatus">
            <el-select v-model="queryParams.scrStatus"
                placeholder="链属状态"
                clearable
                size="small"
                style="width: 215px">
                    <el-option
                    v-for="dict in scrStatusOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                    ></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="链属关系" prop="scrType">
            <el-select v-model="queryParams.scrType"
                placeholder="链属关系"
                clearable
                size="small"
                style="width: 215px">
                    <el-option
                    v-for="dict in scrTypeOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                    ></el-option>
            </el-select>
        </el-form-item>
    </el-form>
    </el-card>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['service:rel:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
            <el-button
              type="warning"
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
              v-hasPermi="['service:relImport:importData']"
              style="background-color: #23C6C8;
    border-color:#23C6C8"
            >导入</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="companyRelList" stripe border>
      <el-table-column label="序号" type="index" width="50" align="center">
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="社会统一代码" align="center" prop="companyCode" v-if="uncheckList.companyCode" show-overflow-tooltip>
        <template slot-scope="scope">
            <span v-if="scope.row.launch">{{scope.row.receiveScySocialCode}}</span>
            <span v-else>{{scope.row.launchScySocialCode}}</span>
        </template>
      </el-table-column>
      <el-table-column label="企业名称" align="center" prop="companyName" v-if="uncheckList.companyName" show-overflow-tooltip>
        <template slot-scope="scope">
            <span v-if="scope.row.launch">{{scope.row.receiveScyName}}</span>
            <span v-else>{{scope.row.launchScyName}}</span>
        </template>
      </el-table-column>
      <el-table-column label="链属关系" align="center" prop="companyType" v-if="uncheckList.companyType">
        <template slot-scope="scope">
            <span v-if="scope.row.launch">{{companyTypeFormat(scope.row.launchScrReceiveType)}}</span>
            <span v-else>{{companyTypeFormat(scope.row.launchScrLaunchType)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="联系人" align="center" prop="launchScrContarct" v-if="uncheckList.launchScrContarct">
      </el-table-column>
      <el-table-column label="联系电话" align="center" prop="launchScrContarctPhone" v-if="uncheckList.launchScrContarctPhone">
      </el-table-column>
      <el-table-column label="邮箱" align="center" prop="launchScrContarctEmail" v-if="uncheckList.launchScrContarctEmail" show-overflow-tooltip>
      </el-table-column>
      <el-table-column label="状态" align="center"  prop="launchScrStatus" v-if="uncheckList.launchScrStatus" :formatter="launchScrStatusFormat">
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleCompanyQuery(scope.row)"
            v-hasPermi="['service:rel:query']"
          >详情</el-button>
          <el-button
            v-if="scope.row.launch && scope.row.launchScrReceiveType == '01' && scope.row.launchScrStatus =='01'"
            v-else="scope.row.launchScrLaunchType == '01' && scope.row.launchScrStatus =='01'"
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['service:rel:delete']"
          >解绑</el-button>
          <el-button
            v-if="handleRel && scope.row.launchScrStatus =='00' && scope.row.receive"
            size="mini"
            type="text"
            @click="handleSuccess(scope.row)"
            v-hasPermi="['service:rel:update']"
          >确认链属</el-button>
          <el-button
            v-if="handleRel && scope.row.launchScrStatus =='00' && scope.row.receive"
            size="mini"
            type="text"
            @click="handleRefuse(scope.row)"
            v-hasPermi="['service:rel:update']"
          >拒绝</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-tab-pane>

<el-tab-pane label="链属未认证">
    <!-- 未认证列表 -->
    <el-card class="fiche">
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getSpare">收起</right-toolbar>
          <span style="margin-bottom: 10px;color:#333333;font:14px Helvetica Neue, Helvetica, PingFang SC, Tahoma, Arial,sans-serif">所选条件:</span>
         <div  style="float: right;margin-right:1%">
            <el-button type="cyan"  icon="el-icon-search" size="mini" @click="handleSpareQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetSpareQuery"  style="float: ;">重置</el-button>
         </div>
         <hr  style="margin-top: 16px;">
    <el-form :model="spareParams" ref="querySpareForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="企业名称" prop="companyName">
        <el-input
          maxlength="30"
          v-model="spareParams.companyName"
          placeholder="请输入企业名称"
          clearable
          size="small"
          @keyup.enter.native="handleSpareQuery"
        />
      </el-form-item>
      <el-form-item label="社会统一代码" prop="scySocialCode" >
        <el-input
          maxlength="30"
          style="width: 230px"
          v-model="spareParams.scySocialCode"
          placeholder="请输入社会统一代码"
          clearable
          size="small"
          @keyup.enter.native="handleSpareQuery"
        />
      </el-form-item>
        <el-form-item label="链属关系" prop="scrType">
            <el-select v-model="spareParams.scrType"
                placeholder="请选择链属关系"
                clearable
                size="small"
                style="width: 215px">
                    <el-option
                    v-for="dict in scrTypeOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                    ></el-option>
            </el-select>
        </el-form-item>
    </el-form>
    </el-card>

<el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['service:rel:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
            <el-button
              type="warning"
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
              v-hasPermi="['service:relImport:importData']"
              style="background-color: #23C6C8;
    border-color:#23C6C8"
            >导入</el-button>
      </el-col>
    </el-row>

    <!-- 未认证企业信息列表 -->
    <el-table v-loading="loading" :data="spareOwnlist" stripe border>
      <el-table-column label="序号" type="index" width="50" align="center">
        <template slot-scope="scope">
          <span>{{(spareParams.pageNum - 1) * spareParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="企业名称" align="center" width="202" prop="scpName" show-overflow-tooltip/>
      <el-table-column label="社会统一代码" align="center" width="151" prop="scpSocialCode" show-overflow-tooltip/>
      <el-table-column label="链属关系" align="center" width="91" prop="scpType" :formatter="scpTypeFormat" />
      <el-table-column label="联系人" align="center" width="83" prop="scpContarct" />
      <el-table-column label="联系电话" align="center" width="109" prop="scpContarctPhone" show-overflow-tooltip />
      <el-table-column label="邮箱" align="center" width="187" prop="scpContarctEmail" show-overflow-tooltip/>
      <el-table-column label="状态" align="center" width="80" prop="scpStatus" :formatter="scpStatusFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.scpInvite == '1'"
            size="mini"
            type="text"
            @click="handleInvite(scope.row)"
            v-hasPermi="['service:spare:invite']"
          >重邀</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleSpareDelete(scope.row)"
            v-hasPermi="['service:rel:delete']"
          >解绑</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="spareTitol > 0"
      :total="spareTitol"
      :page.sync="spareParams.pageNum"
      :limit.sync="spareParams.pageSize"
      @pagination="getSpare"
    />
  </el-tab-pane>

    <!-- 添加链属框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px" :inline="true">
        <el-form-item label="企业编号" prop="scyId" style="display:none" >
          <el-input v-model="form.scyId" disabled />
        </el-form-item>
        <el-form-item label="链属关系" prop="scrReceiveType">
            <el-select v-model="form.scrReceiveType"
                placeholder="请选择链属关系"
                clearable
                size="small"
                style="width: 215px">
                    <el-option
                    v-for="dict in scrTypeOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                    ></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="企业名称" prop="scyName">
            <el-select
              v-model="form.scyName"
              filterable
              allow-create
              clearable
              @clear="clearRemote"
              remote
              reserve-keyword
              @change="choice"
              placeholder="请输入关键词"
              :remote-method="remoteMethod"
              >
              <el-option
                v-for="item in companyList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="企业统一代码" prop="scySocialCode">
          <el-input v-model="form.scySocialCode" placeholder="请输入企业统一代码" maxlength="18" show-word-limit />
        </el-form-item>
        <el-form-item label="联系人" prop="scrContarct">
          <el-input v-model="form.scrContarct" placeholder="请输入联系人" maxlength="10" show-word-limit />
        </el-form-item>
        <el-form-item label="联系人手机号" prop="scrContarctPhone">
          <el-input v-model="form.scrContarctPhone"  placeholder="请输入联系人手机号" maxlength="11" show-word-limit />
        </el-form-item>
        <el-form-item label="邮箱" prop="scrContarctEmail">
          <el-input v-model="form.scrContarctEmail" placeholder="请输入邮箱" maxlength="60" show-word-limit />
        </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="titleDetail" :visible.sync="openDetail" width="800px" append-to-body >
      <el-form ref="formDetail" :model="formDetail" label-width="140px" :inline="true">
        <el-form-item label="企业名称" prop="scyName" >
          <el-input v-model="formDetail.scyName" placeholder="请输入企业名称" disabled style="width:560px" maxlength="20" show-word-limit/>
        </el-form-item>
        <el-form-item label="企业统一代码" prop="scySocialCode">
          <el-input v-model="formDetail.scySocialCode" placeholder="请输入企业统一代码" disabled maxlength="18" show-word-limit/>
        </el-form-item>
        <el-form-item label="联系人" prop="scyLegal">
          <el-input v-model="formDetail.scyLegal" placeholder="请输入联系人" disabled maxlength="5" show-word-limit/>
        </el-form-item>
        <el-form-item label="联系人手机号" prop="scyPhone">
          <el-input v-model="formDetail.scyPhone" placeholder="请输入联系人手机号" disabled maxlength="11" show-word-limit/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDetail">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入窗口 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-link type="info" style="font-size:12px" @click="importTemplate" >下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    
  </el-tabs>
</template>

<script>
import {
  listRel, sparelist, listCompany, addRel, updateRel, listAllCompany, 
  delRel, removeSpare, listCompanyQuery, getUser, againInvite
} from "@/api/service/rel/companyRel";
import { uploadFileNew } from "@/api/common/file";
import { getToken } from "@/utils/auth";
import {columnQuery,columnfilter} from "@/api/common/columnSetting";
import ColumnSetting from '../../../components/Table/columnSetting.vue';
import Cookies from 'js-cookie'
export default {
  name: "companyRel",
  components: {
     ColumnSetting 
   },
  data() {
    return {
      //操作员企业Id
      loginId : '',
      userId : "",
      scyTypeNow : '',
      handleRel:false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      rel : true,
      spare : false,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      spareTitol: 0,
      // 公司数据
      companyList: [],
      //链属表格数据
      companyRelList: [],
      //链属未认证列表数据
      spareOwnlist : [],
      // 状态数据字典
      scrStatusOptions: [],
      scrTypeOptions : [],
      scpStatusOptions : [],
      listCom : [],
      comlist : [],
      // 弹出层标题
      title: "",
      templateTitle:'',
      titleDetail:'',
      // 是否显示弹出层
      open: false,
      templateOpen : false,
      openDetail:false,
      idShow: true,
      // 导入参数
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/sc-service/relImport/importData",
      },
      // 链属查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyName: null,
        scySocialCode: null,
        scrStatus: null,
        scrType: null
      },
      //未认证列表查询参数
      spareParams:{
        pageNum: 1,
        pageSize: 10,
        scySocialCode : null,
        companyName : null,
        scrType : null
      },
      //企业列表查询参数
      companyQueryParams: {
        pageNum: 1,
        pageSize: 10,
        scyName: null
      },
      //筛选按钮的数据列表，与table表头的数据一致 --显示隐藏列用
      tableList: [
            {
              label: 'companyCode',
              value: '社会统一代码'
            },
            {
              label: 'companyName',
              value: '企业名称'
            },
            {
              label: 'companyType',
              value: '链属关系'
            },
            {
              label: 'launchScrContarct',
              value: '联系人'
            },
            {
              label: 'launchScrContarctPhone',
              value: '联系电话'
            },
            {
              label: 'launchScrContarctEmail',
              value: '邮箱'
            },
            {
              label: 'launchScrStatus',
              value: '状态'
            },
            ],
      checkList: [],//筛选列选中的数据列表--显示隐藏列用
      uncheckList: {},//控制筛选列显示隐藏--显示隐藏列用
      selfDom : this,
      tableId:"/sc-service/rel/list",
      // 表单参数
      form: {
          scyId : null,
          scrReceiveType : null,
          scyName : null,
          scySocialCode : null,
          scrContarct : null,
          scrContarctPhone : null,
          scrContarctEmail : null
      },
      templateForm:{
        scyId : null
      },
      formDetail:{
        scyName : null,
        scySocialCode : null,
        scyLegal : null,
        scyPhone : null
      },
      companyId:null,
      // 表单校验
      rules: {
        scyName: [
          { required: true, message: "公司名称不能为空", trigger: ["blur", "change"] },
        ],
        scrReceiveType:[
            { required: true, message: "链属关系不能为空", trigger: ["blur", "change"] },
        ],
        scrContarctPhone: [
          {
            pattern: /^((\d{3}-\d{7,8}|\d{4}-\d{7,8})|(1[3465789]\d{9}))$/,
            message: "手机号格式不正确",
            trigger: "blur",
          }
        ],
        scySocialCode: [
          { required: true, message: "企业统一代码不能为空", trigger: ["blur", "change"] },
          {
            pattern: /^([0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}|[1-9]\d{14})||([1-9]\d{15})$/,
            message: "企业统一代码格式不正确",
            trigger: "blur"
          }
        ],
        scrContarctEmail : [
          { 
            pattern:/^([a-z0-9A-Z]+[-|_|\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\.)+[a-zA-Z]{2,}$/,
            message: "邮箱格式不正确",
            trigger: "blur"
          }
        ]
      },
      templateRules: {
        scyId:[
          { required: true, message: "核心企业不能为空", trigger: "blur" }
        ]
      },
    };
  },
  activated() {
    this.getDicts("sys_scr_status").then(response => {
      this.scrStatusOptions = response.data;
    });
    this.getDicts("sys_scr_type").then(response => {
      this.scrTypeOptions = response.data;
    });
    this.getDicts("sys_scp_status").then(response => {
      this.scpStatusOptions = response.data;
    });
    this.getList();
    this.getSpare();
    this.getCompanyList();
    this.getUser();
  },
  mounted() {
    this.columnQuery();
  },
  methods: {
    //获取当前客户是否之前设置过列展示隐藏
    columnQuery(){
        //获取页面路径
        var psfPagePath = window.location.pathname;
        //用请求后台的url作为唯一标识
        var psfTableName = this.tableId;
        var columnForm = {};
        columnForm.psfPagePath = psfPagePath;
        columnForm.psfTableName = psfTableName;
        columnQuery(columnForm).then(response => {
         if(response.data && response.data.psfShowData){
                this.checkList = response.data.psfShowData;
         }
         this.filter();
      })
    },
    //控制隐藏显示的函数
    filter(checkList) {
      if (!!checkList) {
        this.checkList = checkList;
      }
      columnfilter(this.selfDom);
    },

    // 菜单状态字典翻译
    companyTypeFormat(companyType) {
      return this.selectDictLabel(this.scrTypeOptions, companyType);
    },
    scpTypeFormat(row, column) {
      return this.selectDictLabel(this.scrTypeOptions, row.scpType);
    },
    scpStatusFormat(row, column) {
      return this.selectDictLabel(this.scpStatusOptions, row.scpStatus);
    },
    launchScrStatusFormat(row, column) {
      return this.selectDictLabel(this.scrStatusOptions, row.launchScrStatus);
    },
    //平台导出模板
    submitTemplateForm(){
      this.$refs["templateForm"].validate(valid => {
        let fd = new FormData();
          for(var key in self.form){
            fd.append(key, self.form[key]);
          }
          if (valid) {
            this.download('/sc-service/relImport/importTemplate', {
              ...this.templateForm
            }, `链属模板_${new Date().getTime()}.xls`)
            this.cancelTemplateForm();
          }
      })
    },
    //取消导出模板选择企业
    cancelTemplateForm(){
      this.templateOpen = false;
      this.templateForm = {};
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "链属导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('/sc-service/relImport/importTemplate', {
        ...this.queryParams
      }, `链属模板_${new Date().getTime()}.xls`)
    },
    /* 平台下载模板操作 */
    importAdminTemplate(){
      this.templateTitle = "核心企业";
      this.templateOpen = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
      this.getSpare();
      this.getCompanyList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 查询链属列表 */
    getList() {
      this.loading = true;
       listRel(this.queryParams).then(response => {
          let list = response.data.records;
          this.loginId = response.msg;
          for (let i = 0; i < list.length; i++) {
              if (list[i].launchCompanyId == response.msg) {
                    list[i].receive = false;
                    list[i].launch = true;
              }else if(list[i].launchReceiveScrCompanyId == response.msg){
                    list[i].launch = false;
                    list[i].receive = true;
              }
          }
          this.companyRelList = list;
          console.log(12312313123)
          console.log(this.companyRelList)
          this.total = response.data.total;
          this.loading = false;
        }
      );
    },

    // 未认证列表
    getSpare() {
        this.loading = true;
        sparelist(this.spareParams).then(response => {
          this.spareOwnlist = response.data.records;
          this.spareTitol = response.data.total;
          this.loading = false;
        }
      );
    },
    //查询所有企业
    getCompanyList(){
        this.loading = true;
        listAllCompany().then(response => {
          this.comlist = response.data;
          this.listCom = this.comlist.map(item => {
            return { value: item.scyId, label: item.scyName };
          });
        })
    },
    clearRemote(){
      let query = '';
      this.form.scyId = '';
      this.form.scyName = '';
      this.form.scySocialCode = '';
      this.idShow = true;
      this.remoteMethod(query);
    },
    //选择企业
    remoteMethod(query) {
        if (query) {
          this.loading = true;
          setTimeout(() => {
            this.loading = false;
            this.companyList = this.listCom.filter(item => {
              return item.label.toLowerCase()
                .indexOf(query.toLowerCase()) > -1;
            });
          }, 200);
        } else {
          this.companyList = [];
        }
      },

    //选择企业后反显
    choice(item){
      debugger
        let scyId = item;
        if(scyId){
            listCompanyQuery(scyId).then(response => {
                if(response.data.length > 0){
                this.$set(this.form, "scySocialCode", response.data[0].scySocialCode);
                }else{
                this.$set(this.form, "scySocialCode", '');
                }
                if(response.data.length > 0){
                this.$set(this.form, "scyId", response.data[0].scyId);
                this.idShow = true;
                }else{
                this.$set(this.form, "scyId", '');
                this.idShow = false;
                }
            })
        }
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.clearRemote();
      this.reset();
    },
    cancelDetail(){
      this.openDetail = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.clearRemote();
      this.resetForm("form");
      this.resetForm("formDetail");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 未认证搜索按钮操作 */
    handleSpareQuery() {
      this.spareParams.pageNum = 1;
      this.getSpare();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 未认证重置按钮操作 */
    resetSpareQuery() {
      this.resetForm("querySpareForm");
      this.handleSpareQuery();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增链属";
    },
    //查询企业详情
    handleCompanyQuery(row){
      this.reset();
      if(row.receive == true){
      const scyId = row.launchCompanyId;
      listCompanyQuery(scyId).then(response => {
        if(response.data[0].scyStatus == '00'){
          Cookies.set("/rel/detailComPany/" + scyId + '/', this.$route.fullPath)
          this.$router.push("/rel/detailComPany/" + scyId + '/');
        }else{
          this.formDetail = response.data[0];
          this.openDetail = true;
          this.titleDetail = "详情企业信息";
        }
      });
      }else if(row.launch == true){
      const scyId = row.launchReceiveScrCompanyId;
      listCompanyQuery(scyId).then(response => {
        if(response.data[0].scyStatus == '00'){
          Cookies.set("/rel/detailComPany/" + scyId + '/', this.$route.fullPath)
          this.$router.push("/rel/detailComPany/" + scyId + '/');
        }else{
          this.formDetail = response.data[0];
          this.openDetail = true;
          this.titleDetail = "详情企业信息";
        }
      });
      }
    },
      
    /** 提交按钮 */
submitForm() {
    var self = this;
    this.$refs["form"].validate(valid => {
      let fd = new FormData();
      for(var key in self.form){
        fd.append(key, self.form[key]);
      }
      if (valid) {
          const loading = this.$loading({
            lock: true,
            text: "Loading",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          })
          for (var company of this.companyList) {
            if (company.value == self.form.scyId) {
              self.form.scyName = company.label;
              break;
            }
          }
          console.log(self.form,"提交表单")
          addRel(self.form).then(response => {
            this.msgSuccess("新增成功");
            this.open = false;
            this.getList();
            this.getSpare();
            this.getCompanyList();
          });
          loading.close();
          }
        });
      },
    /* 同意链属 */
    handleSuccess(row){
      const launchScrId = row.launchScrId || this.ids;
      if (row.launchCompanyId == this.loginId) {
        const scyName = row.receiveScyName;
      this.$confirm('确认与"' + scyName + '"的链属关系?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          const state = "01";
          return updateRel(launchScrId,state);
        }).then(() => {
          this.msgSuccess("链属成功");
          this.getList();
          this.getSpare();
          this.getCompanyList();
        })
        .catch(() => {
          this.$message({
            type: "warning",
            message: "已取消链属",
          });
        }); 
      }else if(row.launchReceiveScrCompanyId == this.loginId){
        const scyName = row.launchScyName;
        this.$confirm('确认与"' + scyName + '"的链属关系?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          const state = "01";
          return updateRel(launchScrId,state);
        }).then(() => {
          this.msgSuccess("链属成功");
          this.getList();
          this.getSpare();
          this.getCompanyList();
        })
        .catch(() => {
          this.$message({
            type: "warning",
            message: "已取消链属",
           
          });
        }); 
      }
    },
    /* 拒绝链属 */
    handleRefuse(row){
      const launchScrId = row.launchScrId || this.ids;
      if (row.launchCompanyId == this.loginId) {
        const scyName = row.receiveScyName;
      this.$confirm('拒绝与"' + scyName + '"的链属关系?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          const state = "02";
          return updateRel(launchScrId,state);
        }).then(() => {
          this.msgSuccess("拒绝成功");
          this.getList();
          this.getSpare();
          this.getCompanyList();
        })
        .catch(() => {
          this.$message({
            type: "warning",
            message: "已拒绝链属",
           
          });
        }); 
      }else if(row.launchReceiveScrCompanyId == this.loginId){
        const scyName = row.launchScyName;
        this.$confirm('拒绝与"' + scyName + '"的链属关系?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          const state = "02";
          return updateRel(launchScrId,state);
        }).then(() => {
          this.msgSuccess("拒绝成功");
          this.getList();
          this.getSpare();
          this.getCompanyList();
        })
        .catch(() => {
          this.$message({
            type: "warning",
            message: "已拒绝链属",
           
          });
        }); 
      }
    },
    /** 解绑按钮操作 */
    handleDelete(row) {
      const launchScrId = row.launchScrId || this.ids;
      if (row.launchCompanyId == this.loginId) {
        const scyName = row.receiveScyName;
      this.$confirm('是否确认解绑与"' + scyName + '"的链属关系?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delRel(launchScrId);
        }).then(() => {
          this.msgSuccess("解绑成功");
          this.getList();
          this.getSpare();
          this.getCompanyList();
        })
        .catch(() => {
          this.$message({
            type: "warning",
            message: "已取消解绑",
           
          });
        });
        }else if(row.launchReceiveScrCompanyId == this.loginId){
          const scyName = row.launchScyName;
          this.$confirm('是否确认解绑与"' + scyName + '"的链属关系?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delRel(launchScrId);
        }).then(() => {
          this.msgSuccess("解绑成功");
          this.getList();
          this.getSpare();
          this.getCompanyList();
        })
        .catch(() => {
          this.$message({
            type: "warning",
            message: "已取消解绑",
           
          });
        });
        } 
    },
    /* 解绑链属企业信息数据 */
    handleSpareDelete(row) {
      const scpId = row.scpId || this.ids;
      const scpName = row.scpName;
      this.$confirm('是否确认解绑"' + scpName + '"的信息?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return removeSpare(scpId);
        }).then(() => {
          this.getSpare();
          this.msgSuccess("解绑成功");
        })
        .catch(() => {
          this.$message({
            type: "warning",
            message: "已取消解绑",
           
          });
        }); 
    },

    //重邀操作
    handleInvite(row){
      const loading = this.$loading({
            lock: true,
            text: "Loading",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          })
      againInvite(row).then(response => {
          this.getList();
          this.getSpare();
          this.getCompanyList();
        }).then(() => {
          this.msgSuccess("重邀成功");
          this.getList();
          this.getSpare();
          this.getCompanyList();
          loading.close();
        }).catch((e) => {
          loading.close();
      });
    },

    //获取操作员Id
    getUser(){
      getUser().then(response => {
          this.userId = response.data.userId;
          this.scyTypeNow = response.data.scyType;
          if(this.scyTypeNow == '01'){
            this.handleRel = true;
          }else {
            this.handleRel = false;
          }
        })
    }
  }
};
</script>