<template>
  <div class="third-party-system-integration">
    <div class="header-btn" v-if="data.length < 5">
      <el-button type="primary" icon="el-icon-plus" @click="handleCommand({ command: 'add' })">添加</el-button>
    </div>
    <div class="system-integration-main" v-if="data.length > 0">
      <el-row :gutter="24">
        <el-col :span="8" v-for="item in data" :key="item.id">
          <el-card class="box-card" body-style="margin:0px;padding:0px;min-height:150px;height:222px;">
            <el-row class="card-item">
              <el-col :span="10" class="card-top">
                <template>
                  <img :src="'img/' + item.type + '.png'" class="image" />
                  <div class="divText">{{ item.corpName }}</div>
                </template>
              </el-col>
            </el-row>
            <div class="bottom clearfix" v-if="item.type !== 'weChatWork'">
              <el-button size="small" type="text" @click="handleCommand({ command: 'edit', row: item })">编辑</el-button>
              <el-button size="small" type="text" @click="handleConfig(item)" v-if="item.type == 'dingtalk' ||
                item.type == 'flyBook'
                ">配置</el-button>
              <el-button size="small" type="text" @click="syncContacts(item)" v-if="item.type == 'dingtalk' ||
                item.type == 'flyBook'
                ">通讯录同步</el-button>
              <el-button size="small" type="text" @click="getMenu(item)"
                v-if="item.type == 'weChatOffAcc'">生成菜单</el-button>
              <el-button size="small" type="text" @click="openTempMsgIdDialog(item)"
                v-if="item.type == 'weChatOffAcc'">设置模板消息ID</el-button>
              <el-button size="small" type="text" @click="handleCommand({ command: 'del', row: item })">删除</el-button>
            </div>
            <div class="bottom clearfix" v-if="item.type == 'weChatWork'">
              <el-button size="small" type="text" @click="handleCommand({ command: 'edit', row: item })">编辑</el-button>
              <el-button size="small" type="text" @click="handleConfig(item)">配置</el-button>
              <el-button size="small" type="text" @click="syncContacts(item)">通讯录同步</el-button>
              <el-dropdown>
                <el-button size="small" type="text">
                  更多<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item> <el-button size="small" style="color: #333;" type="text" @click="bindMobile(item)">
                      通过手机号码绑定
                    </el-button></el-dropdown-item>
                  <el-dropdown-item><el-button size="small" type="text" style="color: #333;"
                      @click="handleCommand({ command: 'del', row: item })">删除</el-button></el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <div v-else class="empty_wrap">
      <el-empty :image-size="380" :image="noDataImg" description="暂无第三方集成哦~">
      </el-empty>
    </div>
    <el-dialog width="30%" :title="title" :visible="dialogVisible" v-if="dialogVisible" :before-close="dialogCancle"
      append-to-body :close-on-click-modal="false">
      <el-form :disabled="systemDisabled" v-model="sysExternalUnite" data-vv-scope="sysExternalUniteForm"
        v-form="{ formItemAlign: 'left' }">
        <ht-form-item label="集成类型" prop="type" label-width="120px" class="identity-input-width">
          <ht-select :disabled="sysExternalUnite.id != ''" v-model="sysExternalUnite.type" :options="typeList"
            :validate="{ required: true }" placeholder="请选择集成类型" />
        </ht-form-item>
        <ht-form-item label-width="120px" class="identity-input-width" prop="corpId" v-if="isShowFormItem">
          <template slot="label" v-if="sysExternalUnite.type == 'weChatWork'">
            <el-tooltip placement="top">
              <div slot="content">
                企业ID。第三方平台给予的企业标识。 在
                <a href="https://work.weixin.qq.com/wework_admin/frame#profile" target="_blank"
                  style="color: #90c2f7; text-decoration: underline">企业微信 </a>我的企业-企业信息标签页下的企业ID
              </div>
              <i class="el-icon-info" />
            </el-tooltip>
            <span>corpId</span>
          </template>
          <template slot="label" v-else-if="sysExternalUnite.type == 'dingtalk'">
            <el-tooltip placement="top">
              <div slot="content">
                企业ID。第三方平台给予的企业标识。 在
                <a href="https://open-dev.dingtalk.com/#/corpAuthInfo" target="_blank"
                  style="color: #90c2f7; text-decoration: underline">钉钉开放平台</a>的基本信息-应用信息
              </div>
              <i class="el-icon-info" />
            </el-tooltip>
            <span>AppKey</span>
          </template>
          <template slot="label" v-else-if="sysExternalUnite.type == 'weChatOffAcc'">
            <el-tooltip placement="top">
              <div slot="content">
                开发者ID(AppID)。在微信公众平台-开发-基本配置
              </div>
              <i class="el-icon-info" />
            </el-tooltip>
            <span>AppID</span>
          </template>
          <template slot="label" v-else-if="sysExternalUnite.type == 'flyBook'">
            <el-tooltip placement="top">
              <div slot="content">
                开发者ID(AppID)。在
                <a href="https://open.feishu.cn/app" target="_blank" style="color: #90c2f7; text-decoration: underline">
                  飞书开放平台
                </a>
                开发者后台-进入应用-凭证与基础信息
              </div>
              <i class="el-icon-info" />
            </el-tooltip>
            <span>AppID</span>
          </template>

          <ht-input v-model.trim="sysExternalUnite.corpId" autocomplete="off" :validate="{ required: true }"
            placeholder="请输入"></ht-input>
        </ht-form-item>

        <ht-form-item label-width="120px" class="identity-input-width" prop="corpSecret" v-if="['weChatWork', 'weChatOffAcc', 'flyBook', 'dingtalk'].includes(
          sysExternalUnite.type
        )
          ">
          <template slot="label" v-if="sysExternalUnite.type == 'weChatWork'">
            <el-tooltip placement="top">
              <div slot="content">
                第三方同步通讯录的secret。 在
                <a href="https://work.weixin.qq.com/wework_admin/frame#apps/contactsApi" target="_blank"
                  style="color: #90c2f7; text-decoration: underline">企业微信 </a>的管理工具-通讯录同步页面下的Secret
              </div>
              <i class="el-icon-info" />
            </el-tooltip>
            <span>corpSecret</span>
          </template>
          <template slot="label" v-else>
            <el-tooltip placement="top">
              <div slot="content" v-if="sysExternalUnite.type == 'flyBook'">
                开发者密码(AppSecret)。在
                <a href="https://open.feishu.cn/app" target="_blank" style="color: #90c2f7; text-decoration: underline">
                  飞书开放平台
                </a>
                开发者后台-进入应用-凭证与基础信息
              </div>
              <div slot="content" v-else-if="sysExternalUnite.type == 'dingtalk'">
                开发者密码(AppSecret)。在
                <a href="https://open-dev.dingtalk.com/#/corpAuthInfo" target="_blank"
                  style="color: #90c2f7; text-decoration: underline">钉钉开放平台</a>的基本信息-应用信息
              </div>
              <div slot="content" v-else>开发者密码(AppSecret)。</div>
              <i class="el-icon-info" />
            </el-tooltip>
            <span>AppSecret</span>
          </template>
          <ht-input v-model.trim="sysExternalUnite.corpSecret" autocomplete="off" :validate="{ required: true }"
            placeholder="请输入"></ht-input>
        </ht-form-item>

        <ht-form-item prop="baseUrl" label-width="120px" class="identity-input-width" v-if="isShowFormItem">
          <template slot="label">
            <el-tooltip placement="top">
              <div slot="content">
                格式：【http或https】+【域名】+【端口号】+【根路径】
                如：http://www.hotent.org:8280/mobilevue
              </div>
              <i class="el-icon-info" />
            </el-tooltip>
            <span>移动端地址</span>
          </template>
          <ht-input v-model.trim="sysExternalUnite.baseUrl" autocomplete="off" :validate="{ required: true }"
            placeholder="请输入本系统地址"></ht-input>
        </ht-form-item>

        <ht-form-item label-width="120px" class="identity-input-width" prop="agentId"
          v-if="sysExternalUnite.type == 'dingtalk'">
          <template slot="label">
            <el-tooltip placement="top">
              <div slot="content">
                AgentId。钉钉平台应用标识。 在
                <a href="https://open-dev.dingtalk.com/#/corpAuthInfo" target="_blank"
                  style="color: #90c2f7; text-decoration: underline">钉钉开放平台</a>的基本信息-应用信息
              </div>
              <i class="el-icon-info" />
            </el-tooltip>
            <span>AgentId</span>
          </template>
          <ht-input v-model.trim="sysExternalUnite.agentId" autocomplete="off" :validate="{ required: true }"
            placeholder="请输入AgentId"></ht-input>
        </ht-form-item>

        <ht-form-item label-width="120px" class="identity-input-width" prop="agentId"
          v-if="sysExternalUnite.type == 'miniprogram'">
          <template slot="label">
            <el-tooltip placement="top">
              <div slot="content">
                AppID(小程序ID)：微信小程序管理后台：开发>开发管理>开发设置>开发者ID
              </div>
              <i class="el-icon-info" />
            </el-tooltip>
            <span>AppID</span>
          </template>
          <ht-input v-model.trim="sysExternalUnite.agentId" autocomplete="off" :validate="{ required: true }"
            placeholder="微信小程序管理后台：开发>开发管理>开发设置>开发者ID"></ht-input>
        </ht-form-item>

        <ht-form-item label-width="120px" class="identity-input-width" prop="agentSecret"
          v-if="sysExternalUnite.type == 'miniprogram'">
          <template slot="label">
            <el-tooltip placement="top">
              <div slot="content">
                AppSecret(小程序密钥)：微信小程序管理后台：开发>开发管理>开发设置>开发者ID
              </div>
              <i class="el-icon-info" />
            </el-tooltip>
            <span>AppSecret</span>
          </template>

          <ht-input v-model.trim="sysExternalUnite.agentSecret" autocomplete="off" :validate="{ required: true }"
            placeholder="微信小程序管理后台：开发>开发管理>开发设置>开发者ID"></ht-input>
        </ht-form-item>

        <ht-form-item prop="pcBaseUrl" label-width="120px" class="identity-input-width" v-if="isShowFormItem">
          <template slot="label">
            <el-tooltip placement="top">
              <div slot="content">
                格式：【http或https】+【域名】+【端口号】+【根路径】
                如：http://www.hotent.org:8280/mvue
              </div>
              <i class="el-icon-info" />
            </el-tooltip>
            <span>pc端地址</span>
          </template>

          <ht-input v-model.trim="sysExternalUnite.pcBaseUrl" autocomplete="off" :validate="{ required: true }"
            placeholder="请输入本系统地址"></ht-input>
        </ht-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCancle()">
          {{ $t('eip.common.cancel') }}
        </el-button>
        <ht-submit-button v-show="!systemDisabled" :url="saveSysExternalUnite()" :model="sysExternalUnite"
          :is-submit="isSubmit" request-method="POST" scope-name="sysExternalUniteForm" @before-save-data="beforeSaveData"
          @after-save-data="afterSaveData">{{ $t('eip.common.save') }}</ht-submit-button>
      </div>
    </el-dialog>

    <ht-sidebar-dialog width="33%" title="配置应用" :visible="sysExtUniSetAgentVisible" v-if="sysExtUniSetAgentVisible"
      :before-close="handleClose" append-to-body>
      <el-form v-model="sysExternalUnite" data-vv-scope="sysExtUniSetAgentForm">
        <ht-form-item label-width="120px" class="identity-input-width" prop="agentId">
          <template slot="label">
            <el-tooltip placement="top">
              <div slot="content">
                第三方应用id。
                <span v-if="sysExternalUnite.type == 'weChatWork'">
                  在
                  <a href="https://work.weixin.qq.com/wework_admin/frame#apps" target="_blank"
                    style="color: #90c2f7; text-decoration: underline">企业微信 </a>的应用管理里
                </span>
                <span v-else>
                  在
                  <a href="https://open-dev.dingtalk.com/#/corph5" target="_blank"
                    style="color: #90c2f7; text-decoration: underline">钉钉开放平台</a>企业内部开发-H5微应用里-进入微应用-【应用信息-查看详情】
                </span>
              </div>
              <i class="el-icon-info" />
            </el-tooltip>
            <span>agentId</span>
          </template>

          <ht-input v-model.trim="sysExternalUnite.agentId" autocomplete="off" :validate="{ required: true }"
            placeholder="agentId"></ht-input>
        </ht-form-item>
        <ht-form-item label-width="120px" class="identity-input-width" prop="appKey"
          v-if="sysExternalUnite.type == 'dingtalk'">
          <template slot="label">
            <el-tooltip placement="top">
              <div slot="content">
                第三方应用key。 在
                <a href="https://open-dev.dingtalk.com/#/corph5" target="_blank"
                  style="color: #90c2f7; text-decoration: underline">钉钉开放平台</a>企业内部开发-H5微应用里-进入微应用-【应用信息-查看详情】
              </div>
              <i class="el-icon-info" />
            </el-tooltip>
            <span>appKey</span>
          </template>

          <ht-input v-model.trim="sysExternalUnite.agentKey" autocomplete="off" :validate="{ required: true }"
            placeholder="请输入appKey"></ht-input>
        </ht-form-item>
        <ht-form-item label-width="120px" class="identity-input-width" prop="agentSecret">
          <template slot="label">
            <el-tooltip placement="top">
              <div slot="content">
                第三方应用secret。
                <span v-if="sysExternalUnite.type == 'weChatWork'">
                  在
                  <a href="https://work.weixin.qq.com/wework_admin/frame#apps" target="_blank"
                    style="color: #90c2f7; text-decoration: underline">企业微信</a>的应用管理里
                </span>
                <span v-else>
                  在
                  <a href="https://open-dev.dingtalk.com/#/corph5" target="_blank"
                    style="color: #90c2f7; text-decoration: underline">钉钉开放平台</a>企业内部开发-H5微应用里-进入微应用-【应用信息-查看详情】
                </span>
              </div>
              <i class="el-icon-info" />
            </el-tooltip>
            <span>应用secret</span>
          </template>

          <ht-input v-model.trim="sysExternalUnite.agentSecret" autocomplete="off" :validate="{ required: true }"
            placeholder="请输入agentSecret"></ht-input>
        </ht-form-item>

        <ht-form-item label="菜单名称" label-width="120px" class="identity-input-width" prop="menuName"
          v-if="sysExternalUnite.type == 'weChatWork'">
          <ht-input v-model.trim="sysExternalUnite.menuName" autocomplete="off" :validate="{ required: true }"
            placeholder="请输入菜单名称"></ht-input>
        </ht-form-item>

        <ht-form-item label-width="120px" prop="menuUrl">
          <template slot="label">
            <el-tooltip placement="top" v-if="sysExternalUnite.type == 'dingtalk'">
              <div slot="content">
                钉钉不支持发布菜单，请自行拷贝并配置在
                <a href="https://open-dev.dingtalk.com/#/corph5" target="_blank"
                  style="color: #90c2f7; text-decoration: underline">钉钉开放平台</a>
                企业内部开发-H5微应用里-进入微应用-【应用信息-查看详情】-应用首页地址
              </div>
              <i class="el-icon-info" />
            </el-tooltip>
            <span>菜单url</span>
          </template>
          <ht-input type="textarea" prop="menuUrl" :rows="5" v-model.trim="sysExternalUnite.menuUrl" autocomplete="off"
            :validate="{ required: true }" placeholder="请输入菜单名称" style="width: 100%"></ht-input>
          <div style="margin-top: 10px"></div>
          <el-button size="mini" type="primary" icon="el-icon-printer"
            @click="generateMenuUrl(sysExternalUnite)">一键生成</el-button>
          <el-button type="primary" size="mini" icon="el-icon-document-copy" v-clipboard:copy="sysExternalUnite.menuUrl"
            v-clipboard:success="() => {
              $message.success('内容已复制到剪切板！')
            }
              " v-clipboard:error="() => {
    $message.error('抱歉，复制失败！')
  }
    ">复 制</el-button>
        </ht-form-item>
        <div v-if="sysExternalUnite.type == 'dingtalk'" style="margin-top: 80px">
          <el-divider content-position="left">
            <el-tooltip>
              <div slot="content">
                以下配置，用于生成PC端登录页的钉钉二维码，钉钉App扫一扫即可完成登录。
              </div>
              <i class="el-icon-info" />
            </el-tooltip>
            <span style="font-size: 16px; margin-left: 10px">扫码登录配置</span>
          </el-divider>
          <ht-form-item label-width="120px" class="identity-input-width" prop="scanAppId">
            <template slot="label">
              <el-tooltip>
                <div slot="content">
                  <a href="https://open-dev.dingtalk.com/#/loginMan" target="_blank"
                    style="color: #90c2f7; text-decoration: underline">钉钉开放平台</a>
                  -应用开发>移动接入应用>登录>appId
                </div>
                <i class="el-icon-info" />
              </el-tooltip>
              appId
            </template>
            <ht-input v-model.trim="sysExternalUnite.scanAppId" autocomplete="off"
              placeholder="用于生成PC端登录页的钉钉二维码"></ht-input>
          </ht-form-item>
          <ht-form-item label-width="120px" class="identity-input-width" prop="scanAppSecret">
            <template slot="label">
              <el-tooltip>
                <div slot="content">
                  <a href="https://open-dev.dingtalk.com/#/loginMan" target="_blank"
                    style="color: #90c2f7; text-decoration: underline">钉钉开放平台</a>
                  -应用开发>移动接入应用>登录>appSecret
                </div>
                <i class="el-icon-info" />
              </el-tooltip>
              appSecret
            </template>
            <ht-input v-model.trim="sysExternalUnite.scanAppSecret" autocomplete="off"
              placeholder="用于根据扫码得到的code来获取用户信息"></ht-input>
          </ht-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">
          {{ $t('eip.common.cancel') }}
        </el-button>
        <ht-submit-button url="/portal/sysExternalUnite/v1/saveAgent" context="portal" :model="sysExternalUnite"
          scope-name="sysExtUniSetAgentForm" @before-save-data="sysExternalUnite.isPublish = 0"
          @after-save-data="afterSaveData">{{ $t('eip.common.save') }}</ht-submit-button>

        <ht-submit-button v-if="sysExternalUnite.type == 'weChatWork'" url="/portal/sysExternalUnite/v1/saveAgent"
          context="portal" :model="sysExternalUnite" scope-name="sysExtUniSetAgentForm" @after-save-data="afterSaveData"
          @before-save-data="sysExternalUnite.isPublish = 1">
          <el-tooltip placement="top">
            <div slot="content">保存数据并且将菜单发布到企业微信应用里</div>
            <i class="el-icon-info" style="color: #606266" />
          </el-tooltip>&nbsp;保存并发布</ht-submit-button>
      </div>
    </ht-sidebar-dialog>

    <ht-load-data :url="loadDataUrl" context="portal" @after-load-data="afterLoadData"></ht-load-data>

    <el-dialog title="公众号菜单" :visible.sync="wcoaMenuDialogViasible" :close-on-click-modal="false" width="33%">
      <el-row>
        <el-col :span="4">
          <el-tooltip placement="top">
            <div slot="content">将右侧URL地址设置在公众号菜单里即可。</div>
            <i class="el-icon-info" />
          </el-tooltip>菜单URL:
        </el-col>
        <el-col :span="20">{{ wcoaMenuUrl }}</el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="wcoaMenuDialogViasible = false" v-clipboard:copy="wcoaMenuUrl"
          v-clipboard:success="() => {
            $message.success('内容已复制到剪切板！')
          }
            " v-clipboard:error="() => {
    $message.error('抱歉，复制失败！')
  }
    ">复 制</el-button>
      </div>
    </el-dialog>
    <el-dialog title="模板消息ID设置" :visible.sync="setTempMsgIdDialogVisible" :close-on-click-modal="false" width="33%">
      <el-form data-vv-scope="setTempMsgIdForm">
        <ht-form-item label="模板消息ID" label-width="120px">
          <template slot="label">
            <el-tooltip placement="top">
              <div slot="content">
                在微信公众号后台-功能-模板消息-我的模板-模板消息ID
              </div>
              <i class="el-icon-info" />
            </el-tooltip>
            <span>模板消息ID</span>
          </template>
          <ht-input width="100%" v-model="sysExternalUnite.tempMsgId" autocomplete="off" :validate="{ required: true }"
            placeholder="请输入模板消息ID"></ht-input>
        </ht-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
           <el-button @click="handleCloseTempMsgId">
          {{ $t('eip.common.cancel') }}
        </el-button>
        <ht-submit-button v-show="!systemDisabled" :url="saveSysExternalUnite()" :model="sysExternalUnite"
          :is-submit="isSubmit" request-method="POST" scope-name="setTempMsgIdForm" @before-save-data="beforeSaveData"
          @after-save-data="() => {
            loadData()
            setTempMsgIdDialogVisible = false
          }
            ">{{ $t('eip.common.save') }}</ht-submit-button>
      </div>
    </el-dialog>
    <configuration v-if="isShowDialog" :isShowDialog.sync="isShowDialog" :appType="sysExternalUnite.type"
      :addressForm="sysExternalUnite" :cancelConfig="cancelConfig" :treeData="treeData"></configuration>
  </div>
</template>
<script>
import sys from '@/api/portal.js'
import req from '@/request.js'
import Configuration from './Configuration.vue'
export default {
  name: 'executeJobList',
  components: { Configuration },
  data() {
    return {
      typeList: [
        { key: 'weChatWork', value: '企业微信' },
        { key: 'dingtalk', value: '阿里钉钉' },
        { key: 'weChatOffAcc', value: '微信公众号' },
        { key: 'miniprogram', value: '小程序' },
        { key: 'flyBook', value: '飞书' },
      ],
      sysExternalUnite: {
        id: '',
        corpName: '',
        corpId: '',
        corpSecret: '',
        type: '',
        baseUrl: '',
        pcBaseUrl: '',
        agentId: '',
        menuName: '',
        agentKey: '',
        agentSecret: '',
        menuUrl: '',
        tempMsgId: '',
        syncFlag: false,
        syncScope: 0,
        syncOrg: '',
        syncOrgId: '',
        syncDirection: 0,
        autoSync: false,
        syncFrequency: 0,
        syncStartingTime: '',

        agentName: '',
        alias: '',
        menuUrl: '',
      },
      defaultExternalUnite: {},
      loadDataUrl: '',
      title: '',
      isSubmit: true,
      dialogVisible: false,
      sysExtUniSetAgentVisible: false,
      systemDisabled: false,
      data: [],
      wcoaMenuUrl: '',
      wcoaMenuDialogViasible: false,
      setTempMsgIdDialogVisible: false,
      isShowDialog: false,
      noDataImg: require('@/assets/nodata_images/no-data.png'),
      treeData: [],
    }
  },

  computed: {
    isShowFormItem() {
      return ['weChatWork', 'dingtalk', 'weChatOffAcc', 'flyBook'].includes(
        this.sysExternalUnite.type
      )
    },
  },

  mounted() {
    this.loadData()
  },
  methods: {
    handleConfig(item) {
      this.sysExternalUnite = item
      this.defaultExternalUnite = { ...item }

      //获取第三方组织树
      this.treeData = []
      sys.getDepartmentTree(item.type).then((data) => {
        this.treeData = data
      })
      this.isShowDialog = true
    },
    //进入配置页面，点取消按钮时调用
    cancelConfig() {
      for (var i = 0; i < this.data.length; i++) {
        if (this.data[i].id === this.sysExternalUnite.id) {
          this.data[i] = { ...this.defaultExternalUnite }
          break
        }
      }
    },
    dialogCancle() {
      this.loadDataUrl = ''
      this.dialogVisible = false
      setTimeout(() => (this.systemDisabled = false), 500)
    },
    afterSaveData() {
      this.loadData()
      this.dialogVisible = false
      this.sysExtUniSetAgentVisible = false
    },
    beforeSaveData() {
      this.isSubmit = true
    },
    handleCloseTempMsgId() {
   
      this.setTempMsgIdDialogVisible=false
         this.sysExternalUnite = {}
    },
    handleClose() {
      this.sysExtUniSetAgentVisible = false
      this.loadDataUrl = ''
      setTimeout(() => (this.systemDisabled = false), 500)
    },
    saveSysExternalUnite: function () {
      return window.context.portal + '/portal/sysExternalUnite/v1/save'
    },
    afterLoadData(data) {
      // 编辑第三方集成信息
      if (this.dialogVisible) {
        this.sysExternalUnite = data
        setTimeout(() => this.$validator.validateAll('sysExternalUniteForm'))
      }
    },
    showDialog(row) {
      this.dialogVisible = false
      this.$nextTick(() => {
        this.dialogVisible = true
      })
      if (row) {
        this.loadDataUrl = `/portal/sysExternalUnite/v1/getJson?id=${row.id}`
      }
    },
    loadData() {
      sys.getSysExternalUnitePageJson({}).then((response) => {
        this.data = response.rows
      })
    },
    handleCommand(params) {
      switch (params.command) {
        case 'setAgent':
          this.sysExtUniSetAgentVisible = true
          this.sysExternalUnite = params.row
          setTimeout(() => this.$validator.validateAll('sysExtUniSetAgentForm'))
          break
        case 'edit':
          this.title = '编辑第三方集成信息'
          this.showDialog(params.row)
          break
        case 'add':
          this.sysExternalUnite = {
            id: '',
            corpName: '',
            corpId: '',
            corpSecret: '',
            type: '',
            baseUrl: '',
            pcBaseUrl: '',
            agentId: '',
            menuName: '',
            agentKey: '',
            agentSecret: '',
            menuUrl: '',
            tempMsgId: '',
          }
          this.title = '添加第三方集成信息'
          this.showDialog()
          break
        case 'del':
          this.$confirm('是否确认删除？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(() => {
              sys.delSysExternalUniteById(params.row.id).then(
                (data) => {
                  if (data.state) {
                    this.$message.success(data.message)
                    this.loadData()
                  } else {
                    this.$message.error(data.message || '删除失败')
                  }
                },
                (error) => {
                  this.$message.error(error || '删除失败')
                }
              )
            })
            .catch(() => { })
          break
        default:
          break
      }
    },
    arrayBufferToString(arr) {
      if (typeof arr === 'string') {
        return arr
      }
      var dataview = new DataView(arr)
      var ints = new Uint8Array(arr.byteLength)
      for (var i = 0; i < ints.length; i++) {
        ints[i] = dataview.getUint8(i)
      }
      arr = ints
      var str = '',
        _arr = arr
      for (var i = 0; i < _arr.length; i++) {
        var one = _arr[i].toString(2),
          v = one.match(/^1+?(?=0)/)
        if (v && one.length == 8) {
          var bytesLength = v[0].length
          var store = _arr[i].toString(2).slice(7 - bytesLength)
          for (var st = 1; st < bytesLength; st++) {
            store += _arr[st + i].toString(2).slice(2)
          }
          str += String.fromCharCode(parseInt(store, 2))
          i += bytesLength - 1
        } else {
          str += String.fromCharCode(_arr[i])
        }
      }
      return str
    },
    syncContacts(item) {
      this.$confirm('将同步第三方通讯录，确定继续操作？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          const loading = this.$loading({
            lock: true,
            text: '正在同步通讯录，请等待...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)',
          })
          let param = {
            method: 'POST',
            timeout: 30 * 60 * 1000,
            data: item,
            responseType: 'arraybuffer',
          } //前端超时设置成30分钟
          param.url =
            window.context.portal + `/portal/sysExternalUnite/v1/syncContacts`
          req.request(param).then((resp) => {
            loading.close()
            const data = JSON.parse(
              new TextDecoder('utf-8').decode(new Uint8Array(resp.data))
            )
            if (data.state) {
              this.$message({
                type: 'success',
                message: data.message,
                showClose: true,
              })
            } else {
              this.$message.error(data.message || '同步通讯录失败')
            }
          })
        })
        .catch(() => { })
    },
    getMenu(item) {
      sys.generateMenuUrl(item.id).then(
        (data) => {
          if (data.state) {
            this.wcoaMenuDialogViasible = true
            this.wcoaMenuUrl = data.value
            // this.$alert(data.value, "拷贝以下链接并将其设置在公众号菜单里", {
            //   confirmButtonText: "确定"
            // });
          } else {
            this.$message.error(data.message || '获取失败')
          }
        },
        (error) => {
          this.$message.error(error || '获取失败')
        }
      )
    },
    generateMenuUrl(item) {
      sys.generateMenuUrl(item.id).then(
        (data) => {
          if (data.state) {
            this.$set(this.sysExternalUnite, 'menuUrl', data.value)
          } else {
            this.$message.error(data.message || '获取失败')
          }
        },
        (error) => {
          this.$message.error(error || '获取失败')
        }
      )
    },
    openTempMsgIdDialog(item) {
      this.sysExternalUnite = item
      this.setTempMsgIdDialogVisible = true
    },
    saveTempMsgId() { },
    bindMobile(item) {
      this.$confirm(
        "将通过手机号码绑定用户账号至第三方通讯录，确定继续操作？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        const loading = this.$loading({
          lock: true,
          text: "正在通过手机号码绑定用户账号至[" + item.corpName + "]，请等待...",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)"
        });
        sys.bindMobile(item.id).then(
          data => {
            loading.close();
            try {
              let str = this.arrayBufferToString(data)
              let respo = JSON.parse(str || "{}");
              if (respo.state) {
                this.$message({ type: 'success', message: respo.message, showClose: true })
                this.loadData();
              } else {
                this.$message({ type: 'error', message: respo.message || "通过手机号码绑定用户账号失败", showClose: true })
              }
            } catch (error) { }
          },
          error => {
            loading.close();
            this.$message({ type: 'error', message: error || "通过手机号码绑定用户账号失败", showClose: true })
          }
        );
      }).catch(() => { });;
    },
  },
}
</script>

<style lang="scss" scoped>
.third-party-system-integration {
  height: 100%;

  //padding: 24px;
  .header-btn {
    margin-bottom: 24px;
  }
}

::v-deep {
  .el-dialog__header {
    .el-dialog__title {
      color: #222;
      font-size: 16px;
    }
  }

  .el-dialog__body {
    padding: 20px;

    .el-form-item__label {
      color: #888;
    }
  }

  .dialog-footer {
    text-align: right;
  }

  .el-dialog__footer {
    padding: 20px;
  }
}

.box-card {
  margin-bottom: 24px;
}

imargin {
  margin-right: 20px;
}

.li {
  width: 56px;
  height: 14px;
  font-size: 14px;
  color: rgba(51, 51, 51, 1);
  line-height: 20px;
}

.bottom {
  height: 48px;
  line-height: 48px;
  border-top: 1px solid #EFEFEF;
  display: flex;
  justify-content: space-evenly;
  align-items: center;

  ::v-deep .el-button--small {
    border-right: 1px solid #EBEBEB;
    flex: 1;
    margin: 0;
    padding: 0;
    &:last-child{
      border-right:none;
    }
  }
  ::v-deep .el-dropdown{
    flex: 1;
    text-align: center;
    .el-button--small{
      border-right:none;
    }
  }
}

.divText {
  width: 100px;
  height: 100%;
  font-size: 20px;
  font-weight: bold;
  color: rgba(51, 51, 51, 1);
  /* line-height: 60px; */
  text-align: center;
}

.image {
  height: 64px;
  width: 64px;
  margin-left: 12px;
  margin-right: 12px;
  font-size: 60px;
  display: block;
  margin-bottom: 10px;
}

.fly-book {
  height: 64px;
  width: 64px;
  border-radius: 50%;
  font-size: 40px;
  text-align: center;
  line-height: 64px;
  background: #3370ff;
  color: #fff;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: '';
}

.clearfix:after {
  clear: both;
}

.identity-item-bottom {
  margin-bottom: 5px;
}

.identity-input-width .inputs {
  width: 100%;
}

.card-top {
  white-space: nowrap;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.card-item {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 174px;
  // margin-top: 24px;
}

.empty_wrap {
  height: calc(100% - 82px);

  ::v-deep {
    .el-empty {
      height: 100%;

      .el-empty__description {
        margin-top: -48px;

        p {
          color: #333;
        }
      }
    }
  }
}
</style>
