<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <catalogue-tree @callback="catalogueCallBack" catalogueType="share" />
      </el-col>
      <el-col :span="20" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          :class="showSearch ? '' : ' hide'"
          label-width="68px"
        >
          <el-form-item label="服务名称" prop="serviceName">
            <el-input
              v-model="queryParams.serviceName"
              placeholder="请输入服务名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="" prop="syncFlag">
            <el-checkbox
              label="是否有更新"
              v-model="queryParams.syncFlag"
            ></el-checkbox>
          </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="['system/share:service:add']"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              @click="handleMount"
              v-hasPermi="['system/share:service:add']"
              >挂载</el-button
            >
          </el-col>
          <el-col :span="6">
            <el-alert
              type="warning"
              :title="`有 ${updateCount} 条共享服务有更新`"
              :closable="false"
              v-if="updateCount > 0"
            ></el-alert>
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="serviceList">
          <el-table-column label="编号" align="center" prop="id" width="80" />
          <el-table-column label="服务名称" prop="serviceName" />
          <el-table-column label="请求方法" align="center" prop="requestMethod">
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.sys_request_method"
                :value="scope.row.requestMethod"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="服务地址"
            prop="serviceUrl"
            min-width="120"
            show-overflow-tooltip
          />
          <el-table-column
            label="标签"
            align="center"
            prop="tag"
            show-overflow-tooltip
          />
          <el-table-column
            label="申请数量"
            prop="applyCount"
            align="center"
          ></el-table-column>
          <el-table-column label="审核状态" align="center" prop="status">
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.sys_audit_status"
                :value="scope.row.status"
                v-if="scope.row.status !== '2'"
              />
              <el-tooltip
                :content="'驳回原因：' + scope.row.auditRemark"
                placement="top"
                v-else
              >
                <dict-tag
                  :options="dict.type.sys_audit_status"
                  :value="scope.row.status"
                />
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="有更新" prop="syncFlag" align="center">
            <template slot-scope="scope">
              <el-tooltip
                content="当前共享数据对应的字段有更新，点击修改查看"
                placement="top"
              >
                <el-tag v-if="scope.row.syncFlag === '1'"
                  >是</el-tag
                ></el-tooltip
              >
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system/share:service:edit']"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system/share:service: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-col>
    </el-row>

    <!-- 添加或修改服务共享对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      top="7vh"
      width="1200px"
      append-to-body
      class="service-dialog"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="共享目录" prop="catalogueId">
              <treeselect
                v-model="form.catalogueId"
                :options="treeList"
                :show-count="true"
                placeholder="请选择目录"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="整合服务" prop="serviceId">
              <el-select
                v-model="form.serviceId"
                placeholder="请选择"
                @change="changeData"
                v-if="!form.id"
                filterable
              >
                <el-option
                  :label="`${s.serviceName}`"
                  :value="s.id"
                  v-for="(s, i) in iServiceList"
                  :key="i"
                ></el-option>
              </el-select>
              <span v-else>{{ form.serviceName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="服务名称" prop="serviceName">
              <el-input
                v-model="form.serviceName"
                placeholder="请输入服务名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="服务地址"
              prop="serviceUrl"
              v-if="form.serviceUrl"
            >
              {{ form.serviceUrl }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="开放类型" prop="publishType">
              <el-select
                v-model="form.publishType"
                placeholder="请选择开放类型"
                clearable
              >
                <el-option
                  v-for="dict in dict.type.sys_publish_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8">
            <el-form-item label="增量字段" prop="addField">
              <el-input
                v-model="form.addField"
                placeholder="请填写增量字段"
              ></el-input>
            </el-form-item>
          </el-col> -->
        </el-row>
        <!-- <el-row>
          <el-col :span="8">
            <el-form-item label="页字段" prop="pageField">
              <el-input
                v-model="form.pageField"
                placeholder="请填写页字段"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="页大小字段" prop="pageSizeField">
              <el-input
                v-model="form.pageSizeField"
                placeholder="请填写页大小字段"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="搜索字段字段" prop="searchField">
              <el-input
                v-model="form.searchField"
                placeholder="请填写搜索字段"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-row>
          <el-col :span="8">
            <el-form-item label="信息标识符" prop="infoId">
              <el-input v-model="form.infoId" placeholder="请输入信息标识符" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="提供机构" prop="provideOrganization">
              <el-select
                v-model="form.provideOrganization"
                placeholder="请选择提供机构"
                filterable
              >
                <el-option
                  v-for="dict in dict.type.sys_provide_organization"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="标签" prop="tag">
              <el-select
                v-model="form.tag"
                placeholder="请选择"
                multiple
                style="width: 100%"
                filterable
              >
                <el-option
                  v-for="(tag, i) in tagList"
                  :label="tag.tagName"
                  :value="tag.tagName"
                  :key="i"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="描述" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入描述"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-form :model="form" label-width="100px" class="detail">
        <el-row style="margin-bottom: 20px">
          <el-col :span="24">
            <h3><b>服务请求</b></h3>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="需要鉴权:" prop="needAuth">
              {{ form.needAuth === "Y" ? "需要" : "" }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="鉴权方式:"
              prop="authWay"
              v-if="form.needAuth === 'Y'"
            >
              <dict-tag
                :options="dict.type.sys_auth_way"
                :value="form.authWay"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="请求方法:" prop="requestMethod">
              {{ form.requestMethod }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="参数形式:" prop="paramForm">
              {{ form.paramForm }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="返回格式:" prop="responseForm">
              <dict-tag
                :options="dict.type.sys_response_form"
                :value="form.responseForm"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-row style="margin: 20px 0 10px 0">
        <el-col :span="12">
          <h3>
            <b style="margin-right: 10px">参数配置</b>
            <el-tag
              type="danger"
              v-if="form.id > 0 && form.syncFlag === '1'"
              size="mini"
            >
              有更新
            </el-tag>
            <el-tag
              type="info"
              v-if="form.id > 0 && form.syncFlag !== '1'"
              size="mini"
            >
              无更新
            </el-tag>
          </h3>
        </el-col>
        <el-col :span="12" style="display: flex; justify-content: flex-end">
          <el-button
            type="primary"
            size="mini"
            style="float: right"
            @click="handleBatchConfirm"
            v-if="form.id > 0 && form.syncFlag === '1'"
            >批量确认变更</el-button
          >
        </el-col>
      </el-row>
      <el-table
        :data="columnList"
        height="350"
        :row-class-name="tableRowClassName"
      >
        <el-table-column label="编号" align="center" width="80" type="index" />
        <el-table-column
          label="参数类型"
          align="center"
          prop="paramType"
          width="100"
        >
          <template slot-scope="scope">
            <template v-if="scope.row.isEdit === 1">
              <el-select
                v-model="scope.row.paramType"
                placeholder="请选择"
                size="mini"
                filterable
              >
                <el-option label="入参" value="in"></el-option>
                <el-option label="出参" value="out"></el-option>
              </el-select>
            </template>
            <template v-else>
              <el-tag v-if="scope.row.paramType === 'in'">入参</el-tag>
              <el-tag type="success" v-if="scope.row.paramType === 'out'"
                >出参</el-tag
              >
            </template>
          </template>
        </el-table-column>
        <el-table-column label="参数名" prop="paramName" min-width="150">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.paramName"
              placeholder="必须唯一"
              v-if="scope.row.isEdit"
              size="mini"
            />
            <span v-else>
              <span
                v-if="
                  scope.row.newService &&
                  scope.row.paramName !== scope.row.newService.paramName
                "
              >
                <div>{{ scope.row.paramName }}</div>
                <div>
                  <span style="color: red"
                    >新值：{{ scope.row.newService.paramName }}</span
                  >
                </div>
              </span>
              <span v-else>{{ scope.row.paramName }}</span>
            </span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="参数中文名" prop="paramComment">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.paramComment"
              placeholder="请输入参数中文"
              v-if="scope.row.isEdit"
              size="mini"
            />
            <span v-else>{{ scope.row.paramComment }}</span>
          </template>
        </el-table-column> -->
        <el-table-column
          label="映射字段"
          prop="mapColumnName"
          v-if="form.responseForm === 'standard'"
          min-width="150"
        >
          <template slot="header">
            缓存映射字段
            <el-tooltip
              content="服务数据缓存时，该参数缓存到数据表的字段名，必须符合表字段命名规范"
              placement="bottom"
            >
              <i class="el-icon-question" />
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.mapColumnName"
              placeholder="必须是英文、数字、下划线"
              v-if="scope.row.isEdit && scope.row.paramType === 'out'"
              size="mini"
            />
            <span v-if="!scope.row.isEdit && scope.row.paramType === 'out'">
              <span
                v-if="
                  scope.row.newService &&
                  scope.row.mapColumnName !== scope.row.newService.mapColumnName
                "
              >
                <div>{{ scope.row.mapColumnName }}</div>
                <div>
                  <span style="color: red"
                    >新值：{{ scope.row.newService.mapColumnName }}</span
                  >
                </div>
              </span>
              <span v-else>{{ scope.row.mapColumnName }}</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="数据类型" prop="dataType" width="100">
          <template slot-scope="scope">
            <span v-if="!scope.row.newService">{{ scope.row.dataType }}</span>
            <span
              v-else-if="scope.row.dataType === scope.row.newService.dataType"
              >{{ scope.row.dataType }}</span
            >
            <span v-else>
              <div>{{ scope.row.dataType }}</div>
              <div>
                <span style="color: red"
                  >新值：{{ scope.row.newService.dataType }}</span
                >
              </div>
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="是否必须"
          align="center"
          prop="isRequired"
          width="100"
          v-if="form.responseForm === 'standard'"
        >
          <template slot="header">
            是否必须
            <el-tooltip content="必填表示该入参不能为空" placement="bottom">
              <i class="el-icon-question" />
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <el-checkbox
              label=""
              v-model="scope.row.isRequired"
              v-if="scope.row.paramType === 'in'"
            ></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column
          label="是否可见"
          align="center"
          prop="isVisable"
          width="100"
          v-if="form.responseForm === 'standard'"
        >
          <template slot="header">
            是否可见
            <el-tooltip content="该字段是否对订阅用户可见" placement="bottom">
              <i class="el-icon-question" />
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <el-checkbox
              label=""
              v-model="scope.row.isVisable"
              v-if="scope.row.paramType === 'out'"
            ></el-checkbox>
          </template>
        </el-table-column>
        <!-- <el-table-column
          label="是否可搜索"
          align="center"
          prop="isSearchable"
          width="120"
        >
          <template slot-scope="scope">
            <el-checkbox
              label=""
              v-model="scope.row.isSearchable"
              v-if="scope.row.paramType === 'in'"
            ></el-checkbox>
          </template>
        </el-table-column> -->
        <el-table-column
          label="脱敏"
          align="center"
          prop="desensitizationRuleId"
          width="150"
          v-if="form.responseForm === 'standard'"
        >
          <template slot="header">
            是否脱敏
            <el-tooltip
              content="该字段使用选择的脱敏规则进行脱敏"
              placement="bottom"
            >
              <i class="el-icon-question" />
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.desensitizationRuleId"
              placeholder="请选择规则"
              clearable
              size="mini"
              v-if="scope.row.paramType === 'out'"
              filterable
            >
              <el-option
                :label="rule.ruleName"
                :value="rule.id"
                v-for="(rule, i) in desensitizationRuleList"
                :key="i"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          label="备注"
          prop="remark"
          width="150"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span v-if="!scope.row.newService">{{ scope.row.remark }}</span>
            <span
              v-else-if="scope.row.remark === scope.row.newService.remark"
              >{{ scope.row.dataType }}</span
            >
            <span v-else>
              <div>{{ scope.row.remark }}</div>
              <div>
                <span style="color: red"
                  >新值：{{ scope.row.newService.remark }}</span
                >
              </div>
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="变更类型"
          prop="businessType"
          show-overflow-tooltip=""
          align="center"
          v-if="form.id > 0 && form.syncFlag === '1'"
          width="100"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-tag
              type="info"
              size="mini"
              v-if="
                scope.row.businessType === 'DELETE' && scope.row.confirm === 0
              "
              >移除</el-tag
            >
            <el-tag
              type="success"
              size="mini"
              v-if="
                scope.row.businessType === 'DELETE' && scope.row.confirm === 1
              "
              >确认移除</el-tag
            >
            <el-tag
              size="mini"
              v-if="
                scope.row.businessType === 'UPDATE' && scope.row.confirm === 0
              "
              >变更</el-tag
            >
            <el-tag
              type="success"
              size="mini"
              v-if="
                scope.row.businessType === 'UPDATE' && scope.row.confirm === 1
              "
              >确认变更</el-tag
            >
            <el-tag
              type="danger"
              size="mini"
              v-if="
                scope.row.businessType === 'INSERT' && scope.row.confirm === 0
              "
              >新增</el-tag
            >
            <el-tag
              type="success"
              size="mini"
              v-if="
                scope.row.businessType === 'INSERT' && scope.row.confirm === 1
              "
              >确认新增</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          v-if="form.id > 0 && form.syncFlag === '1'"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              v-if="scope.row.businessType && scope.row.confirm !== 1"
              @click="handleConfirm(scope.row, 1)"
            >
              <span v-if="scope.row.businessType === 'INSERT'">共享</span>
              <span v-if="scope.row.businessType === 'UPDATE'">更新</span>
              <span v-if="scope.row.businessType === 'DELETE'">移除</span>
            </el-button>

            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              v-if="scope.row.businessType && scope.row.confirm === 1"
              @click="handleConfirm(scope.row, 0)"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="submitting"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 挂载 -->
    <el-dialog title="挂载" :visible.sync="mount" width="800px" append-to-body>
      <el-form
        ref="mountForm"
        :model="queryIServiceParam"
        label-width="120px"
        :inline="true"
      >
        <el-form-item label="整合服务名称" prop="serviceName">
          <el-input
            v-model="queryIServiceParam.serviceName"
            placeholder="请输入整合服务名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="未挂载" prop="isBind">
          <el-checkbox
            label=""
            v-model="queryIServiceParam.isBind"
          ></el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleIServiceQuery"
            >搜索</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        :data="iServicePageList"
        @selection-change="handleSelectionChange"
        :height="500"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="服务名称" prop="serviceName"></el-table-column>
        <el-table-column
          label="服务地址"
          prop="serviceUrl"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="描述" prop="remark"></el-table-column>
      </el-table>
      <pagination
        v-show="iServiceTotal > 0"
        :total="iServiceTotal"
        :page.sync="queryIServiceParam.pageNum"
        :limit.sync="queryIServiceParam.pageSize"
        @pagination="getIServicePageList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitMountForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listService,
  getService,
  delService,
  addService,
  updateService,
  mountService,
  getServiceItem,
} from "@/api/system/share/service";

import {
  listService as IlistService,
  getServiceItem as getIServiceItem,
} from "@/api/system/integration/service";

import CatalogueTree from "@/components/CatalogueTree";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listCatalogue } from "@/api/system/integration/catalogue";
import { listTag } from "@/api/system/base/tag";
import { listDesensitization } from "@/api/system/quality/desensitization";
export default {
  name: "Service",
  dicts: [
    "sys_param_form",
    "sys_yes_no",
    "sys_auth_way",
    "sys_audit_status",
    "sys_request_method",
    "sys_publish_type",
    "sys_provide_organization",
    "sys_response_form",
  ],
  components: { CatalogueTree, Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      submitting: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 服务共享表格数据
      serviceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示挂载
      mount: false,
      // 描述时间范围
      daterangeCreateTime: [],
      // 描述时间范围
      daterangeAuditTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        serviceId: null,
        catalogueId: null,
        serviceName: null,
        serviceUrl: null,
        needAuth: null,
        authWay: null,
        requestMethod: null,
        paramForm: null,
        infoId: null,
        tag: null,
        provideOrganization: null,
        status: null,
        viewCount: null,
        applyCount: null,
        remark: null,
        syncFlag: null,
      },
      queryIServiceParam: {
        pageNum: 1,
        pageSize: 10,
        status: "1",
        serviceName: null,
        isBind: null,
      },
      iServicePageList: [],
      iServiceTotal: 0,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        serviceId: [
          {
            required: true,
            message: "所属整合服务id不能为空",
            trigger: "change",
          },
        ],
        catalogueId: [
          { required: true, message: "目录id不能为空", trigger: "change" },
        ],
        serviceName: [
          { required: true, message: "服务名称不能为空", trigger: "change" },
        ],
        publishType: [
          { required: true, message: "请选择开放类型", trigger: "change" },
        ],
        addField: [
          { required: true, message: "请填写增量字段", trigger: "change" },
        ],
      },
      // 所有整合服务
      iServiceList: [],
      desensitizationRuleList: [], // 脱敏规则
      treeList: [], // 共享目录
      tagList: [],
      columnList: [], // 参数
      updateCount: 0,
    };
  },
  created() {
    this.getList();
    this.getCatalogueList();
    this.getIServiceList();
    this.getTagList();
    this.getUpdateCount();
    this.getDesensitizationRuleList();
  },
  methods: {
    tableRowClassName(row, rowIndex) {
      if (row.row.confirm !== 1) {
        return "warning-row";
      }
    },
    catalogueCallBack(data) {
      this.queryParams.catalogueId = data.id;
      this.handleQuery();
    },
    getDesensitizationRuleList() {
      listDesensitization({ pageNum: 1, pageSize: 10000 }).then((response) => {
        this.desensitizationRuleList = response.rows;
      });
    },
    getUpdateCount() {
      listService({ pageNum: 1, pageSize: 10000, syncFlag: 1 }).then(
        (response) => {
          this.updateCount = response.total;
        }
      );
    },
    /** 查询目录列表 */
    getCatalogueList() {
      listCatalogue({
        pageNum: 1,
        pageSize: 100000,
        catalogueType: "share",
      }).then((response) => {
        let treeList = [];
        if (response.rows && response.rows.length > 0) {
          response.rows.forEach((p) => {
            treeList.push({
              id: p.id,
              parentId: p.parentId,
              label: p.catalogueName,
              children: [],
            });
          });
        }
        this.treeList = this.handleTree(treeList);
      });
    },
    getTagList() {
      listTag({}).then((response) => {
        this.tagList = response.rows;
      });
    },
    /** 查询服务共享列表 */
    getList() {
      this.loading = true;
      const params = JSON.parse(JSON.stringify(this.queryParams));
      if (this.queryParams.syncFlag) {
        params.syncFlag = 1;
      } else {
        params.syncFlag = null;
      }
      listService(params).then((response) => {
        this.serviceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getIServicePageList() {
      IlistService(this.queryIServiceParam).then((response) => {
        this.iServicePageList = response.rows;
      });
    },
    getIServiceList() {
      IlistService({ status: "1", isBind: true }).then((response) => {
        this.iServiceList = response.rows;
      });
    },
    handleIServiceQuery() {
      this.queryIServiceParam.pageNum = 1;
      this.getIServicePageList();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.mount = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        serviceId: null,
        catalogueId: null,
        serviceName: null,
        serviceUrl: null,
        needAuth: null,
        authWay: null,
        requestMethod: null,
        paramForm: null,
        infoId: null,
        tag: null,
        provideOrganization: null,
        status: "0",
        viewCount: null,
        applyCount: null,
        remark: null,
      };
      this.resetForm("form");
      this.columnList = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.daterangeAuditTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    changeData(e) {
      //   console.log(e);
      const iService = this.iServiceList.find((p) => p.id === e);
      console.log(iService);
      this.form.needAuth = iService.needAuth;
      this.form.authWay = iService.authWay;
      this.form.requestMethod = iService.requestMethod;
      this.form.paramForm = iService.paramForm;
      this.form.responseForm = iService.responseForm;
      this.form.serviceUrl = iService.serviceUrl;
      // 查询整合数据对应的数据字段
      getIServiceItem(e).then((response) => {
        // 新增的数据全部确认
        if (response.data) {
          response.data.forEach((p) => {
            p.confirm = 1;
            p.isRequired = p.isRequired === "Y";
            if (p.isVisable === "N") {
              p.isVisable = false;
            } else {
              p.isVisable = true;
            }

            p.isSearchable = p.isSearchable === "Y";
          });
        }
        this.columnList = response.data;
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加服务共享";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getService(id).then((response) => {
        if (response.data.tag && response.data.tag.length > 0) {
          response.data.tag = response.data.tag.split(",");
        }
        this.form = response.data;

        // 查询共享服务明细（包含变化项）
        if (this.form.syncFlag) {
          getServiceItem(id, 1).then((res) => {
            if (res.data.serviceItems) {
              res.data.serviceItems.forEach((p) => {
                if (!p.businessType) {
                  p.confirm = 1;
                } else {
                  p.confirm = 0;
                  if (!p.relationId) {
                    p.relationId = p.id;
                    p.id = "tmp_" + Math.ceil(Math.random() * 100000);
                  }
                }
              });
            }

            // 排序
            res.data.serviceItems.sort(function (a, b) {
              const aV = a.businessType ? a.businessType.length : 0;
              const bV = b.businessType ? b.businessType.length : 0;
              return bV - aV;
            });
            this.columnList = res.data.serviceItems;
            if (this.columnList && this.columnList.length > 0) {
              this.columnList.forEach((p) => {
                p.isRequired = p.isRequired === "Y";
                if (p.isVisable === "N") {
                  p.isVisable = false;
                } else {
                  p.isVisable = true;
                }
                p.isSearchable = p.isSearchable === "Y";
              });
            }
          });
        } else {
          getServiceItem(id, 0).then((res) => {
            if (res.data) {
              res.data.forEach((p) => {
                p.confirm = 1;
              });
            }

            this.columnList = res.data;
            if (this.columnList && this.columnList.length > 0) {
              this.columnList.forEach((p) => {
                p.isRequired = p.isRequired === "Y";
                if (p.isVisable === "N") {
                  p.isVisable = false;
                } else {
                  p.isVisable = true;
                }
                p.isSearchable = p.isSearchable === "Y";
              });
            }
          });
        }

        this.open = true;
        this.title = "修改服务共享";
      });
    },
    /** 挂载 */
    handleMount() {
      this.getIServicePageList();
      this.mount = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const form = JSON.parse(JSON.stringify(this.form));
          if (form.tag && form.tag.length > 0) {
            form.tag = form.tag.join(",");
          } else {
            form.tag = null;
          }

          if (!this.columnList || this.columnList.length === 0) {
            this.$modal.msgError("服务参数不能为空");
            return;
          }

          const serviceItems = JSON.parse(JSON.stringify(this.columnList));
          const submitServiceItems = [];
          // console.log(serviceItems);
          serviceItems.forEach((p) => {
            if (p.isRequired) {
              p.isRequired = "Y";
            } else {
              p.isRequired = "N";
            }
            if (p.isVisable) {
              p.isVisable = "Y";
            } else {
              p.isVisable = "N";
            }
            if (p.isSearchable) {
              p.isSearchable = "Y";
            } else {
              p.isSearchable = "N";
            }
            if (form.syncFlag === "1") {
              if (!p.confirm) {
                // 未确认的新增不加入提交数据
                if (p.businessType !== "INSERT") {
                  submitServiceItems.push(p);
                }
              } else {
                // 确认后，编辑使用新数据
                if (p.businessType === "UPDATE") {
                  p = p.newService;
                  delete p.newService;
                }

                // 确认后，非删除加入
                if (p.businessType !== "DELETE") {
                  submitServiceItems.push(p);
                }
              }
            } else {
              submitServiceItems.push(p);
            }

            if (typeof p.id != "number") {
              delete p.id;
            }
          });
          form.serviceItems = submitServiceItems;
          // return;
          this.submitting = true;
          if (form.id != null) {
            updateService(form)
              .then((response) => {
                this.submitting = false;
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
                this.getUpdateCount();
              })
              .catch(() => {
                this.submitting = false;
              });
          } else {
            addService(form)
              .then((response) => {
                this.submitting = false;
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
                this.getUpdateCount();
              })
              .catch(() => {
                this.submitting = false;
              });
          }
        }
      });
    },
    submitMountForm() {
      if (!this.ids || this.ids.length === 0) {
        this.$modal.msgError("请勾选挂载的服务");
        return;
      }
      mountService({ ids: this.ids }).then((response) => {
        this.getList();
        this.getList();
        this.$modal.msgSuccess("挂载成功");
        this.cancel();
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除服务共享编号为"' + ids + '"的数据项？')
        .then(function () {
          return delService(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/share/service/export",
        {
          ...this.queryParams,
        },
        `service_${new Date().getTime()}.xlsx`
      );
    },
    handleConfirm(row, confirm) {
      row.confirm = confirm;
    },
    handleBatchConfirm() {
      this.columnList.forEach((p) => {
        p.confirm = 1;
      });
    },
  },
};
</script>
