<!-- Dialog.vue -->
<template>
  <el-dialog :visible.sync="visible" @update:visible="handleUpdateVisible"
    :title="isAddOperation == 'add' ? '新增服务目录' : isAddOperation == 'edit' ? '编辑服务目录' : '查看服务目录'" :width="width"
    :before-close="handleClose">
    <div>
      <el-steps :active="activeValue" align-center>
        <el-step title="填写编目信息"></el-step>
        <el-step title="选择服务"></el-step>
        <el-step title="完善归集项"></el-step>
      </el-steps>
    </div>
    <div v-if="activeValue === 1" class="container">
      <div class="t-b">目录信息</div>
      <el-form inline :model="libraryData" label-width :label-position="'right'" ref="firstRef"
        :disabled="isAddOperation == 'view'" class="form-detail-inline" :rules="firstFormRules">
        <el-form-item label="数据目录代码" prop="catalogCode">
          <el-input v-model="libraryData.catalogCode" placeholder="提交后自动生成" disabled />
        </el-form-item>
        <el-form-item label="目录名称" prop="catalogName">
          <el-input v-model="libraryData.catalogName" placeholder="请输入目录名称" />
        </el-form-item>
        <el-form-item label="目录英文名称" prop="catalogNameEn">
          <el-input v-model="libraryData.catalogNameEn" placeholder="请输入目录英文名称" />
        </el-form-item>
        <el-form-item label="提供单位" prop="provideUnit">
          <el-cascader @change="changeProvidedUnit" v-model="libraryData.provideUnit" :options="provideUnitArr"
            :props="{ value: 'id', label: 'directoryName', children: 'list' }" placeholder="请选择提供单位" />
        </el-form-item>
        <el-form-item label="所属信息系统" prop="informationSystem">
          <el-select v-model="libraryData.informationSystem" placeholder="请选择所属信息系统">
            <el-option v-for="item in informationSystemArr" :key="item.misProjectName" :label="item.misProjectName"
              :value="item.misProjectName" />
          </el-select>
        </el-form-item>

        <el-form-item label="目录类型" prop="catalogType">
          <el-input v-model="libraryData.catalogType" placeholder="请输入目录类型" disabled />
        </el-form-item>

        <el-form-item label="更新频率及增量描述" prop="updateSeq">
          <el-input v-model="libraryData.updateSeq" placeholder="请输入更新频率及增量描述" />
        </el-form-item>

        <el-form-item label="是否为空间资源" prop="isSpace">
          <el-radio-group v-model="libraryData.isSpace" class="ml-4">
            <el-radio :label="item.value" :value="item.value" v-for="item in isRadio" :key="item.label">
              {{
                item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="源坐标系" v-if="libraryData.isSpace === 1" prop="coordinate">
          <el-input v-model="libraryData.coordinate" placeholder="请输入源坐标系" />
        </el-form-item>

        <el-form-item label="安全等级" prop="safetyLevel">
          <el-select v-model="libraryData.safetyLevel" placeholder="请选择安全等级">
            <el-option v-for="item in safetyLevelArr" :key="item.id" :label="item.levelName" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="目录描述" class="textarea-row">
          <el-input v-model="libraryData.catalogDes" placeholder="请输入" :rows="4" type="textarea" />
        </el-form-item>
        <div class="t-b">共享管理</div>
        <el-form-item label="共享方式" prop="shareMethod">
          <el-select v-model="libraryData.shareMethod" placeholder="请选择共享方式">
            <el-option v-for="item in dict.type.share_method" :key="item.value" :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="共享范围" prop="shareRange">
          <el-select v-model="libraryData.shareRange" placeholder="请选择共享范围">
            <el-option v-for="item in dict.type.shared_scope" :key="item.value" :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="共享类型" prop="shareType">
          <el-select v-model="libraryData.shareType" placeholder="请选择共享类型">
            <el-option v-for="item in shared_type" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="共享条件" prop="shareCondition" v-if="libraryData.shareType === '有条件共享'">
          <el-input v-model="libraryData.shareCondition" placeholder="请输入共享条件" />
        </el-form-item>
        <el-form-item label="开放属性" prop="isOpen">
          <el-radio-group v-model="libraryData.isOpen" class="ml-4">
            <el-radio :label="item.value" :value="item.value" v-for="item in isOpen" :key="item.label">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>-->
        <el-form-item label="开放条件" v-if="libraryData.isOpen === 1" prop="openCondition">
          <el-input v-model="libraryData.openCondition" placeholder="请输入开放条件" />
        </el-form-item>
        <div class="t-b">分类信息</div>
        <el-form-item label="主题分类" prop="mainClassName">
          <div class="flex-box">
            <el-input v-model="libraryData.mainClassName" placeholder="请选择主题分类" disabled></el-input>
            <el-button type="primary" @click="handelMainClassId" :disabled="isAddOperation == 'view'"
              class="flex-box-btn">选择</el-button>
          </div>
        </el-form-item>
        <el-form-item label="目录分类" prop="departmentClassId">
          <el-select class="select-txt" v-model="libraryData.departmentClassId" placeholder="请选择目录分类"
            :disabled="!libraryData.mainClassName">
            <el-option v-for="item in departmentClassIdTypeArr" :key="item.id" :label="item.directoryName"
              :value="item.id" />
            <template #footer>
              <el-button v-if="!isAdding" size="small" @click="onAddOption" type="primary" plain>新增</el-button>
              <template v-else>
                <el-input v-model="optionName" class="option-input" placeholder="请输入分类名称" size="small" />
                <el-button type="primary" size="small" @click="onConfirm">确认</el-button>
                <el-button size="small" @click="clear">取消</el-button>
              </template>
            </template>
          </el-select>
        </el-form-item>
        <div class="t-b">扩展信息</div>
        <el-form-item label="接入归集方式" prop="inputationMethod">
          <el-select v-model="libraryData.inputationMethod" placeholder="请选择接入归集方式" disabled>
            <el-option v-for="item in dict.type.access_collection_method" :key="item.value" :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="数据归集频率" prop="inputationSequence">
          <el-select v-model="libraryData.inputationSequence" placeholder="请选择数据归集频率">
            <el-option v-for="item in dict.type.data_collection_frequency" :key="item.value" :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="目录摘要" prop="catalogAbstract">
          <el-input v-model="libraryData.catalogAbstract" placeholder="请输入目录摘要" />
        </el-form-item>

        <el-form-item label="标签" prop="inputationLabel">
          <div class="flex-box">
            <el-input v-model="libraryData.inputationLabel" placeholder="请选择标签" disabled></el-input>
            <el-button type="primary" @click="handelSelectTag" :disabled="isAddOperation == 'view'"
              class="flex-box-btn">选择</el-button>
          </div>
        </el-form-item>
        <el-form-item label="底座类型" prop="baseType">
          <el-select v-model="libraryData.baseType" placeholder="请选择底座类型">
            <el-option v-for="item in dict.type.base_type" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="数据更新方式" prop="updateType">
          <el-select v-model="libraryData.updateType" placeholder="请选择数据更新方式">
            <el-option v-for="item in dict.type.data_update_type" :key="item.value" :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="接入归集周期" prop="inputationCron">
          <el-input v-model="libraryData.inputationCron" placeholder="请输入接入归集周期" />
        </el-form-item>
        <el-form-item label="接入归集口径" prop="inputationCalibre">
          <el-select v-model="libraryData.inputationCalibre" placeholder="请选择接入归集口径">
            <el-option v-for="item in dict.type.access_collection_caliber" :key="item.value" :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="归集增量标识字段" prop="identificationField">
          <el-input v-model="libraryData.identificationField" placeholder="请输入归集增量标识字段" />
        </el-form-item>
        <el-form-item label="归集数据量" prop="dataSize">
          <el-input v-model="libraryData.dataSize" placeholder="请输入归集数据量" />
        </el-form-item>
        <el-form-item label="数据起始时间" prop="date">
          <el-date-picker v-model="libraryData.date" type="datetimerange" start-placeholder="开始时间"
            end-placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>

        <div class="t-b">上链信息</div>
        <el-row class="rowForm">
          <el-form-item label="关联本机构职责目录" class="textarea-row" prop="dutyId">
            <div class="flex-box textarea-row">
              <el-select v-model="libraryData.dutyId" placeholder="请选择关联本机构职责目录" disabled>
                <el-option v-for="item in dutyIdTypeArr" :key="item.id" :label="item.agenciesPrsponsibility"
                  :value="item.id" />
              </el-select>
              <el-button type="primary" @click="handelSelectDuty" class="flex-box-btn">选择职责目录</el-button>
            </div>
          </el-form-item>
        </el-row>
        <div class="t-b" v-if="isAddOperation === 'change' || libraryData.changeReason">变更原因</div>
        <el-form-item label=" " class="textarea-row" v-if="isAddOperation === 'change' || libraryData.changeReason">
          <el-input v-model="libraryData.changeReason" type="textarea" :rows="4"></el-input>
        </el-form-item>
      </el-form>

      <SelectTagDialog v-model="isSelectTagDialog" @saveHandle="inputationLabelSelected"></SelectTagDialog>
      <SelectDutyDialog v-model="isSelectDutyDialog" @saveHandle="dutyIdSelected" :selectDutyId="selectDutyId">
      </SelectDutyDialog>
      <MainClassDialog v-model="isMainClassDialog" @saveHandle="MainClassSaveHandle" :mainClassId="mainClassId">
      </MainClassDialog>
    </div>
    <div v-if="activeValue == 2" class="container">
      <div class="t-b">封装API选择</div>
      <div class="box">
        <el-form inline :model="libraryData" label-position="left" :disabled="isEdit">
          <el-form-item label="选择服务来源">
            <el-radio-group v-model="libraryData.apiSourceType" class="ml-4">
              <el-radio :label="item.value" :value="item.value" v-for="item in resourceArr" :key="item.label">
                {{
                  item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <!-- <div class="t-b">接口列表</div>
      <div class="box">
        <el-button type="primary" style="margin: 10px 0">添加</el-button>
        <el-table :data="data1" border ref="selection" @selection-change="checkAll" style="width: 100%">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="name" label="服务名称"></el-table-column>
          <el-table-column prop="date" label="接口名称"></el-table-column>
          <el-table-column prop="date" label="创建时间"></el-table-column>
          <el-table-column label="操作" align="center">
            <template>
              <el-link class="mr10">编辑</el-link>
              <el-link class="mr10">删除</el-link>
            </template>
</el-table-column>
</el-table>
      </div>-->

      <div class="t-b">接口信息</div>
      <div class="box">
        <el-form class="form-detail-inline" inline :model="libraryData" label-position="left" :disabled="isEdit">
          <el-form-item label="接口地址">
            <el-input placeholder="Please Input" v-model="libraryData.apiAddress"></el-input>
          </el-form-item>
          <el-form-item label="接口名称">
            <el-input placeholder="Please Input" v-model="libraryData.apiName"></el-input>
          </el-form-item>
          <el-form-item label="请求方式">
            <el-select v-model="libraryData.method">
              <el-option :label="item.label" :value="item.value" v-for="item in dict.type.method_type"
                :key="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <el-form :model="libraryData" label-width="auto" label-position="left" :disabled="isEdit">
          <el-form-item label="RequestHeader">
            <el-input type="textarea" placeholder="填写json" v-model="libraryData.requestHeader"></el-input>
          </el-form-item>
          <el-form-item label="ResponseHeader">
            <el-input type="textarea" placeholder="填写json" v-model="libraryData.responseHeader"></el-input>
          </el-form-item>
        </el-form>
      </div>

      <div class="t-b">请求参数</div>
      <div class="t-p">parmas</div>
      <div class="box">
        <el-button type="primary" @click="addData1" :disabled="isEdit">新增</el-button>
        <el-table :data="data1" border ref="selection" @selection-change="checkAll" style="width: 100%">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="fieldName" label="参数信息">
            <template #default="{ row }">
              <el-input v-model="row.fieldName" :disabled="isEdit"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="parameterDes" label="参数描述">
            <template #default="{ row }">
              <el-input v-model="row.parameterDes" :disabled="isEdit" type="textarea" rows="4"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="fieldType" label="参数类型">
            <template #default="{ row }">
              <el-input v-model="row.fieldType" :disabled="isEdit"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="isNeed" label="是否必填" v-if="libraryData.apiSourceType == 1">
            <template #default="{ row }">
              <el-switch v-model="row.isNeed" :disabled="isDisabled" active-text="是" inactive-text="否" />
            </template>
          </el-table-column>
          <el-table-column prop="explain" label="说明">
            <template #default="{ row }">
              <el-input v-model="row.explain" :disabled="isEdit"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="isCurrent" label="是否当前页字段" v-if="libraryData.apiSourceType == 1">
            <template #default="{ row }">
              <el-input v-model="row.isCurrent" :disabled="isEdit"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="isPage" label="是否为每页的数据条数" v-if="libraryData.apiSourceType == 1">
            <template #default="{ row }">
              <el-input v-model="row.isPage" :disabled="isEdit"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="t-p">
        body
        <el-button>Json</el-button>
        <el-button>xml</el-button>
        <el-button>Raw</el-button>
        <el-button>x-www-form-urlencoded</el-button>
      </div>
      <el-input type="textarea" v-model="libraryData.body" :rows="2" :disabled="isEdit"></el-input>

      <!-- <el-form-item label="" class="box">
        <el-input type="textarea" v-model="libraryData.body" :rows="2" :disabled="isEdit"></el-input>
      </el-form-item> -->
      <div class="t-p">接口示例出参</div>
      <div class="t-p">
        <div class="box">
          <el-button type="primary">下载模板</el-button>
          <el-button type="primary" :disabled="isEdit">上传接口调用文档</el-button>
        </div>
      </div>
      <el-input type="textarea" v-model="libraryData.apiExample" :rows="2" :disabled="isEdit"></el-input>

      <!-- <el-form-item label="" class="box">
        <el-input type="textarea" v-model="libraryData.apiExample" :rows="2" :disabled="isEdit"></el-input>
      </el-form-item> -->
      <el-button type="primary" class="box" :disabled="isEdit">保存接口</el-button>
    </div>
    <div v-if="activeValue == 3" class="container">
      <div class="t-b">目录信息</div>
      <p>编辑数据信息项</p>
      <el-form class="other-form box" inline :model="libraryData" label-position="left" :disabled="isEdit">
        <el-form-item label="接入归集方式">
          <!-- <el-select>
                  <el-option label="as"></el-option>
          </el-select>-->
          <el-input v-model="libraryData.inputationMethod" placeholder="请输入数据目录代码" />
        </el-form-item>
        <el-form-item label="数据归集频率">
          <!-- <el-select>
                  <el-option label="as"></el-option>
          </el-select>-->
          <el-input v-model="libraryData.inputationSequence" placeholder="请输入数据目录代码" />
        </el-form-item>
        <el-form-item label="接入归集方式">
          <!-- <el-select>
                  <el-option label="as"></el-option>
          </el-select>-->
          <el-input v-model="libraryData.inputationMethod" placeholder="请输入数据目录代码" disabled />
        </el-form-item>
        <el-form-item label="接入归集周期">
          <!-- <el-select>
                  <el-option label="as"></el-option>
          </el-select>-->

          <el-input v-model="libraryData.inputationCron" placeholder="请输入数据目录代码" />
        </el-form-item>
        <el-form-item label="接入归集口径">
          <!-- <el-select>fangdouSaveClick
                  <el-option label="as"></el-option>
          </el-select>-->

          <el-input v-model="libraryData.inputationCalibre" placeholder="请输入数据目录代码" />
        </el-form-item>
        <el-form-item label>
          <el-button>全量需增加分页参数</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" v-if="!isEdit" @click="handleSave('save')">暂存</el-button>
      <el-button type="primary" v-if="activeValue === 3 && !isEdit" @click="handleSubmitSave">保存</el-button>
      <el-button v-if="activeValue !== 1" @click="changeActiveVal('up')">上一步</el-button>
      <el-button v-if="activeValue !== 3" @click="changeActiveVal('next')">下一步</el-button>
      <el-button @click="handleClose">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { mapState, mapActions } from "vuex";
import {
  queryMisList,
  getDirectoryAllLevel,
  queryDirectoryList,
  queryDatabase,
  getEtlTableFields,
  getEtlTableList
} from "@/api/unified-resources/information-system/index.js";
import { queryGovernanceRuleByName, saveCatalog, getCatalogDetail, updateCatalog } from "@/api/unified-resources/data-directory/index.js";
import { getResponsibilityList, updateResponsibility } from "@/api/unified-resources/job-directory/index.js";
import MainClassDialog from "../comp/MainClassDialog.vue";
import SelectTagDialog from "../comp/SelectTagDialog.vue";
import SelectDutyDialog from "../comp/SelectDutyDialog.vue";

export default {
  name: "libraryTable",
  dicts: [
    'method_type',
    "share_method",
    "shared_scope",
    "shared_type",
    "access_collection_method",
    "data_collection_frequency",
    "base_type",
    "data_update_type",
    "access_collection_caliber",
    "datalayer_type"
  ],
  components: {
    MainClassDialog,
    SelectTagDialog,
    SelectDutyDialog
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: "弹窗标题"
    },
    currentOpObj: {
      type: Object,
      default: {}
    },
    width: {
      type: String,
      default: "85%"
    },
    isAddOperation: {}
  },
  data() {
    return {
      visible: this.value,
      dialogTitle: "",
      itemView: {},
      isDisabled: false,
      libraryData: {
        apiSourceType: 1,
        isSpace: 2,
        isOpen: 2,
        catalogType: "服务",
        informationSystem: '',
        mainClassName: '',
        departmentClassId: '',
      },
      data1: {},
      isEdit: false,
      // catalogId: null,
      isAdding: false,
      optionName: "",
      isMainClassDialog: false,
      mainClassId: "",
      safetyLevelArr: [
        { id: 1, levelName: "安全等级一级" },
        { id: 2, levelName: "安全等级二级" },
        { id: 3, levelName: "安全等级三级" }
      ],
      allInformationSystemArr: [],
      informationSystemArr: [],
      provideUnitArr: [],
      departmentClassIdTypeArr: [],
      selectDutyId: "",
      tagSelectList: {},
      dutyIdTypeArr: [],
      mainClassIdOptions: [],
      isSelectTagDialog: false,
      isSelectDutyDialog: false,

      environmentOtherFormData: {
        env: ""
      },
      selectArr: [],
      options: [],
      data1: [],
      nowSelectData: [],
      nowSelectRightData: [],
      activeValue: 1,
      tableData: [
        {
          id: 10001,
          name: "系统1",
          nickname: "comId",
          role: "VARCHAR2(2",
          sex: "主健",
          sex2: "是",
          num1: "是",
          age: "是",
          address: "是",
          date12: "是",
          date13: "是"
        }
      ],
      resourceArr: [
        { label: "转发API", value: 1 },
        { label: "查询API", value: 2 }
      ],
      isRadio: [
        { label: "是", value: 1 },
        { label: "否", value: 2 }
      ],
      isOpen: [
        { label: "开放", value: 1 },
        { label: "非开放", value: 2 }
      ],

      res1: "",
      firstFormRules: {
        catalogCode: [
          { required: true, message: "请输入数据目录代码", trigger: "blur" }
        ],
        catalogName: [
          { required: true, message: "请输入目录名称", trigger: "blur" }
        ],
        catalogNameEn: [
          { required: true, message: "请输入目录英文名称", trigger: "blur" }
        ],
        provideUnit: [
          { required: true, message: "请选择提供单位", trigger: "change" }
        ],
        informationSystem: [
          { required: true, message: "请选择所属信息系统", trigger: "change" }
        ],
        catalogType: [
          { required: true, message: "请输入目录类型", trigger: "blur" }
        ],
        updateSeq: [
          {
            required: true,
            message: "请输入更新频率及增量描述",
            trigger: "blur"
          }
        ],
        isSpace: [
          { required: true, message: "请选择是否为空间资源", trigger: "change" }
        ],
        coordinate: [
          { required: true, message: "请输入源坐标系", trigger: "blur" }
        ],
        safetyLevel: [
          { required: true, message: "请选择安全等级", trigger: "change" }
        ],
        shareMethod: [
          { required: true, message: "请选择共享方式", trigger: "change" }
        ],
        shareRange: [
          { required: true, message: "请选择共享范围", trigger: "change" }
        ],
        // shareType: [{ required: true, message: '请选择共享类型', trigger: 'change' }],
        // shareCondition: [{ required: true, message: '请输入共享条件', trigger: 'blur' }],
        // isOpen: [{ required: true, message: '请选择开放属性', trigger: 'change' }],
        openCondition: [
          { required: true, message: "请输入开放条件", trigger: "blur" }
        ],
        isOpen: [{ required: true, message: "请选择", trigger: "change" }],
        mainClassName: [
          { required: true, message: "请选择主题分类", trigger: "change" },
        ],
        departmentClassId: [
          { required: true, message: "请选择目录分类", trigger: "change" }
        ],
        inputationMethod: [
          { required: true, message: "请选择接入归集方式", trigger: "change" }
        ],
        dataLayer: [
          { required: true, message: "请选择存储层", trigger: "change" }
        ],
        baseType: [
          { required: true, message: "请选择底座类型", trigger: "change" }
        ],
        updateType: [
          { required: true, message: "请选择数据更新方式", trigger: "change" }
        ],
        inputationCron: [
          { required: true, message: "请输入接入归集周期", trigger: "blur" }
        ],
        inputationCalibre: [
          { required: true, message: "请选择接入归集口径", trigger: "change" }
        ],
        identificationField: [
          { required: true, message: "请输入归集增量标识字段", trigger: "blur" }
        ],
        dutyId: [
          {
            required: true,
            message: "请选择关联本机构职责目录",
            trigger: "change"
          }
        ]
      }
    };
  },
  watch: {
    value(newVal) {
      this.visible = newVal;
    },
    visible(newVal) {
      this.$emit("input", newVal);
    },
    title: {
      handler(newVal) {
        this.dialogTitle = newVal;
      },
      deep: true, // 深入监听
      immediate: true
    },
    currentOpObj: {
      handler(newVal) {
        this.itemView = newVal;
      },
      deep: true, // 深入监听
      immediate: true
    }
  },
  computed: {
    catalogId: {
      get() {
        return this.$store.state.projectManage.catalogId;
      },
      set(newValue) {
        this.$store.commit('projectManage/setCatalogId', newValue);
      }
    }
  },
  mounted() {
    if (this.isAddOperation === "add" && sessionStorage.getItem("fw-form")) {
      this.libraryData = JSON.parse(sessionStorage.getItem("fw-form"));
    }
    this.libraryData.inputationMethod = "接口";
    this.getOrganizationalList();
    this.getTrees();
    this.getList();
    this.getSystemListData();

    if (this.isAddOperation !== "add") {
      if (this.historyId) {
        this.getDirectoryList();
        this.getVerHistory();
      } else {
        this.getDirectoryList();
        this.getDetail();
      }

      if (this.isAddOperation === "view") {
        this.isEdit = true;
      } else {
        this.isEdit = false;
      }
    }
  },

  methods: {

    onAddOption() {
      this.isAdding = true;
    },

    onConfirm() {
      if (this.optionName) {
        let pForm = {};
        pForm.directoryCode = this.createRandomId();
        pForm.directoryName = this.optionName;
        pForm.levelDirectory = this.libraryData.mainClassId;
        pForm.levelDirectoryName = this.libraryData.mainClassName;
        addDireccory(pForm).then(res => {
          if (+res.code === 200) {
            this.getDirectoryList(this.libraryData.mainClassId);
          }
        });
        this.clear()
      }
    },

    clear() {
      this.optionName = "";
      this.isAdding = false;
    },

    handelMainClassId() {
      this.mainClassId = this.libraryData.mainClassId;
      this.isMainClassDialog = true;
    },

    MainClassSaveHandle(value) {
      this.clear();
      this.libraryData.mainClassId = value.levelDirectory;
      this.libraryData.mainClassName = value.levelDirectoryName;
      this.libraryData.departmentClassId = "";
      this.getDirectoryList(value.levelDirectory);
    },

    getOrganizationalList() {
      getDirectoryAllLevel({ type: "组织机构" }).then(res => {
        if (+res.code === 200) {
          if (res.data === null) {
            this.provideUnitArr = [];
          } else {
            this.removeListForLevel4(res.data[0].list);
            this.provideUnitArr = res.data[0].list;
          }
        }
      });
    },
    removeListForLevel4(data) {
      data.forEach(item => {
        // 如果是 level 4 的项，删除 list 属性
        if (item.level === "4") {
          delete item.list;
        }
        // 如果当前项有子项（list），递归调用该函数
        if (item.list && item.list.length > 0) {
          this.removeListForLevel4(item.list);
        }
      });
    },
    getSystemListData() {
      queryMisList({ pageNumber: 1, pageSize: 999 }).then(res => {
        if (+res.code === 200) {
          this.informationSystemArr = res.data;
        }
      });
    },

    changeProvidedUnit(value) {
      this.libraryData.informationSystem = "";
    },

    addData1() {
      this.data1.push({});
    },

    handleMainClassIdChange(value) {
      this.libraryData.mainClassId = value[value.length - 1];
      this.libraryData.departmentClassId = "";
      this.getDirectoryList(this.libraryData.mainClassId);
    },

    getDirectoryList(val) {
      queryDirectoryList({
        pageNumber: 1,
        pageSize: 99999,
        directoryTwoId: val
      }).then(res => {
        if (+res.code === 200) {
          this.departmentClassIdTypeArr = res.data;
        }
      });
    },

    inputationLabelSelected(obj) {
      this.libraryData.inputationLabel = obj.dynamicTags
        ?.map(i => i.directoryName)
        .join(",");
      this.libraryData.column1 = obj.dynamicTags;
    },

    dutyIdSelected(obj) {
      this.libraryData.dutyId = obj.id;
      this.$store.dispatch(
        "projectManage/setsSelectDutyId",
        this.libraryData.dutyId
      );
      this.isSelectDutyDialog=false
    },

    getList() {
      getResponsibilityList({
        pageNumber: 1,
        pageSize: 9999
      }).then(res => {
        if (+res.code === 200) {
          this.dutyIdTypeArr = res.data;
        }
      });
    },

    getTrees() {
      getDirectoryAllLevel({ type: "目录" }).then(res => {
        if (+res.code === 200) {
          this.mainClassIdOptions = res.data;
        }
      });
    },

    handelSelectTag() {
      this.isSelectTagDialog = true;
      this.$store.commit(
        "projectManage/setSelectTagList",
        this.libraryData.column1
      );
    },

    handelSelectDuty() {
      this.isSelectDutyDialog = true;
      this.$store.commit(
        "projectManage/setsSelectDutyId",
        this.libraryData.dutyId
      );
    },

    handleClose() {
      console.log(this.isAddOperation, 'this.isAddOperation');

      if (this.isAddOperation === "add") {
        console.log(this.libraryData, 'this.libraryData');

        console.log(Object.values(this.libraryData).filter(value => value !== null && value !== '').length, 'length');

        if (Object.values(this.libraryData).filter(value => value !== null && value !== '').length > 5) {
          this.$confirm("表单尚未提交，是否暂存已修改的内容？", "提示", {
            confirmButtonText: "暂存",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              sessionStorage.setItem(
                "fw-form",
                JSON.stringify(this.libraryData)
              );
              this.$message({
                type: "success",
                message: "暂存成功"
              });
              this.visible = false;
              this.$emit("cancel"); // 可以在父组件监听 'cancel' 事件
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "取消成功"
              });
              this.libraryData = {};
              sessionStorage.removeItem("fw-form");
              this.visible = false;
              this.$emit("cancel"); // 可以在父组件监听 'cancel' 事件
            });
        } else {
          this.visible = false;
          this.$emit("cancel"); // 可以在父组件监听 'cancel' 事件
        }
      } else {
        this.visible = false;
        this.$emit("cancel"); // 可以在父组件监听 'cancel' 事件
      }
    },

    changeActiveVal(type) {
      if (type === "up") {
        this.activeValue -= 1;
      } else {
        if (this.activeValue === 1) {
          this.libraryData.catalogCode = this.createRandomId();

          this.$refs.firstRef.validate((valid, fields) => {
            if (valid) {
              this.res1 = valid;
              this.activeValue += 1;
              queryDatabase({
                pageNumber: 1,
                pageSize: 999
              }).then(res => { });
            } else {
              this.$message.error("请完整输入表单项");
              return;
            }
          });
        } else if (this.activeValue === 2) {
          this.activeValue += 1;
        } else if (this.activeValue === 3) {
          this.activeValue += 1;
        }
      }
    },
    checkAll(val) {
      this.nowSelectData = val;
    },

    checkRightAll(val) {
      this.nowSelectRightData = val;
    },

    handleConcatArr(selectArr, nowSelectData) {
      let arr = [];
      arr = arr.concat(selectArr, nowSelectData);
      return arr;
    },

    handleRemoveTabList(isNeedArr, originalArr) {
      if (isNeedArr.length && originalArr.length) {
        for (let i = 0; i < isNeedArr.length; i++) {
          for (let k = 0; k < originalArr.length; k++) {
            if (isNeedArr[i]["name"] === originalArr[k]["name"]) {
              originalArr.splice(k, 1);
            }
          }
        }
      }
    },

    getDetail() {
      getCatalogDetail({ catalogId: this.catalogId }).then(res => {
        let catalog = res.data.catalog;
        let catalogDuty = res.data.catalogDuty;
        let catalogExtend = res.data.catalogExtend;
        let catalogApi = res.data.catalogApi;
        let newObj = {
          ...catalog,
          ...catalogDuty,
          ...catalogExtend,
          ...catalogApi
        };
        this.libraryData = newObj;
        this.catalogId = catalog.catalogId;
        this.libraryData.date = [
          catalogExtend.startTime,
          catalogExtend.endTime
        ];
        this.libraryData.apiSourceType = Number(catalogApi.apiSourceType);
        this.libraryData.catalogType = "服务";
        this.libraryData.safetyLevel = +this.libraryData.safetyLevel;
        this.libraryData.provideUnit = this.libraryData.provideUnit.split(",");
        if (catalogApi.params) {
          this.data1 = JSON.parse(catalogApi.params);
        }

        if (this.libraryData.column1) {
          this.libraryData.column1 = JSON.parse(this.libraryData.column1);
        }

        if (newObj.params) {
          this.libraryData.params = JSON.parse(newObj.params);
        }
        if (newObj.body) {
          this.libraryData.body = JSON.parse(newObj.body);
        }
        if (newObj.apiExample) {
          this.libraryData.apiExample = JSON.parse(newObj.apiExample);
        }

        if (catalog?.catalogChange?.changeReason) {
          this.libraryData.changeReason = catalog.catalogChange.changeReason;
        }
      });
    },

    handleSave(type) {
      this.libraryData.column1 = JSON.stringify(
        this.libraryData.column1,
        null,
        ""
      );

      let params = {
        catalog: {
          catalogCode: this.libraryData.catalogCode,
          catalogName: this.libraryData.catalogName,
          catalogNameEn: this.libraryData.catalogNameEn,
          provideUnit: this.libraryData.provideUnit.join(","),
          informationSystem: this.libraryData.informationSystem,
          catalogType: 2,
          updateSeq: this.libraryData.updateSeq,
          isSpace: this.libraryData.isSpace,
          coordinate: this.libraryData.coordinate,
          shareMethod: this.libraryData.shareMethod,
          shareRange: this.libraryData.shareRange,
          openCondition: this.libraryData.openCondition,
          mainClassId: this.libraryData.mainClassId,
          mainClassName: this.libraryData.mainClassName,
          departmentClassId: this.libraryData.departmentClassId,
          catalogStatus: this.libraryData.catalogStatus,
          safetyLevel: this.libraryData.safetyLevel,
          catalogDes: this.libraryData.catalogDes
        },
        catalogExtend: {
          inputationMethod: this.libraryData.inputationMethod,
          inputationSequence: this.libraryData.inputationSequence,
          catalogAbstract: this.libraryData.catalogAbstract,
          inputationLabel: this.libraryData.inputationLabel,
          column1: this.libraryData.column1,
          baseType: this.libraryData.baseType,
          updateType: this.libraryData.updateType,
          inputationCron: this.libraryData.inputationCron,
          inputationCalibre: this.libraryData.inputationCalibre,
          identificationField: this.libraryData.identificationField,
          dataSize: this.libraryData.dataSize,
          startTime: this.libraryData.date?.[0],
          endTime: this.libraryData.date?.[1]
        },
        catalogDuty: {
          dutyId: this.libraryData.dutyId
        },
        catalogApi: {
          apiAddress: this.libraryData.apiAddress,
          apiName: this.libraryData.apiName,
          method: this.libraryData.method,
          requestHeader: this.libraryData.requestHeader,
          responseHeader: this.libraryData.responseHeader,
          params: JSON.stringify(this.data1),
          body: JSON.stringify(this.libraryData.body),
          apiExample: JSON.stringify(this.libraryData.apiExample),
          apiSourceType: this.libraryData.apiSourceType
        },
        catalogChange: {
          changeReason: this.libraryData.changeReason
        }
      };

      if (type === "save") {
        params.catalog.catalogStatus = 1;
      } else {
        params.catalog.catalogStatus = 2;
      }

      if (this.isAddOperation === "change") {
        params.catalog.catalogId = this.catalogId;
        params.catalogExtend.catalogId = this.catalogId;
        params.catalogDuty.catalogId = this.catalogId;
        params.catalogApi.catalogId = this.catalogId;
        changeFeedbackList({
          catalogDTO: params,
          queryType: 1,
          registerFlag: true,
          assertId: this.catalogId
        }).then(res => {
          if (+res.code === 200) {
        
            // this.$emit("saveHandle");
            this.$message.success("更新成功");
            this.handleCancel()
            // this.$bus.emit("libraryTable", params);
            sessionStorage.removeItem("kb-form");
          }
        });
      } else {
        if (this.catalogId) {
          params.catalog.catalogId = this.catalogId;
          params.catalogExtend.catalogId = this.catalogId;
          params.catalogDuty.catalogId = this.catalogId;
          params.catalogApi.catalogId = this.catalogId;
          updateCatalog(params).then(res => {
            if (+res.code === 200) {
              this.$message.success("更新成功");
              this.handleCancel()
              sessionStorage.removeItem("fw-form");
            }
          });
        } else {
          saveCatalog(params).then(res => {
            if (+res.code === 200) {
              this.$message.success("新增成功");
              this.handleCancel()
              sessionStorage.removeItem("fw-form");
            }
          });
        }
      }
    },


    handleSubmitSave() {
      this.handleSave("submit");
    },

    handleUpdateVisible(val) {
      this.visible = val;
    },
    beforeClose(done) {
      this.visible = false;
      this.$emit("before-close", done);
    },
    // 取消按钮处理方法
    handleCancel() {
      this.visible = false;
      this.$emit("confirm"); // 可以在父组件监听 'cancel' 事件
    },

    // 确定按钮处理方法
    async handleConfirm() {
      if (this.title === "新增") {
        this.formData.code = this.createRandomId();
      }
      // this.$refs.myFormComponent.validateForm();
      await this.$refs.ruleFormRef.validate((valid, fields) => {
        if (valid) {
          // 校验通过，进行后续操作
          console.log("表单校验通过，进行后续操作");
          this.handleSave();
        } else {
          this.$message.error("请完整填写表单");
          console.log("表单校验失败");
        }
      });
    },


    createRandomId() {
      let min = Math.pow(10, 14);
      let max = Math.pow(10, 15) - 1;
      return Math.floor(Math.random() * (max - min + 1)) + min;
    }
  }
};
</script>

<style scoped lang="scss">
.op-btn {
  text-align: center;
  margin-top: 15px;
}

.container {
  min-height: 60vh;
}

.other-form {
  .el-form-item {
    width: 27%;
  }
}

.two-form {
  .el-form-item {
    width: 47%;
  }
}

.w100 {
  width: 100% !important;
}

.t-b {
  font-size: 18px;
  margin: 20px 0;
}

.t-p {
  font-size: 15px;
  margin: 20px 0;
}

.rowForm {
  // justify-content: center;
}

.box {
  margin-left: 50px;
}

.list {
  display: flex;
  justify-content: center;

  table {
    width: 100%;
    border-collapse: collapse;
    font-size: 12px;
    color: #606266;

    td,
    thead {
      padding: 0 10px;
      width: 177px;
      height: 34px;
      line-height: 34px;
      border: 1px solid #e4e4e4;
      box-sizing: border-box;
    }

    thead {
      text-align: center;
    }

    .one-td {
      border-top: none;
    }
  }

  .arrowList {
    td {
      border: 0 !important;
      text-align: center;
    }

    tbody {
      border: 0 !important;
    }
  }
}

.flex-box-btn {
  background-color: #3f8ffe !important;
  color: #fff !important;
  height: 38px !important;
}

.flex-box {
  display: flex;
  width: 100%;

  .el-input {
    width: 100%;
  }
}

.header-title {
  display: block;
  font-size: 16px;
  text-align: center;
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 10px;
}

.border-color {
  border: 1px solid #ebeef5;
}

.option-input {
  width: 100%;
  margin-bottom: 8px;
}
</style>