<template>
  <div class="wrap">
    <div class="btn">
      <div class="chunk">
        <el-button
          icon="el-icon-back"
          @click="
            $router.replace({ path: '/applicationList/applicationListAdmin' })
          "
        >返回
        </el-button
        >
      </div>
      <div class="chunk"></div>
    </div>
    <div class="main">
      <div class="exploitSetting formChunk">
        <div class="title">
          <div class="text">三方调用系统配置</div>
          <div class="btn">
            <el-button icon="el-icon-first-aid-kit" type="primary" @click="saveHandle"
            >保存
            </el-button
            >
            <el-button type="primary" icon="el-icon-plus" @click="addRow"
            >新增
            </el-button
            >
          </div>
        </div>
        <div class="list" v-for="(item, index) in formList" :key="index">
          <div class="form">
            <div class="left">
              <baseNewForm
                ref="mainForm"
                :spanNumber="24"
                :isFunBtn="false"
                :lookFlag="lookFlag"
                :formRule="!lookFlag"
                :formRow="authorityFormRow"
                :ruleForm="formList[index]"
                @onSubmit="onSubmit"
              >
                <template v-slot:name="{row}">
                  <baseNewSelect :ruleForm="row.ruleForm" v-model="row.ruleForm['name']"
                                 @onSelect="(val,tempObj)=>onSelectHanlde(val,row.ruleForm,tempObj)"></baseNewSelect>
                </template>
              </baseNewForm>
            </div>
            <div class="right">
              <el-switch
                active-value="1"
                inactive-value="2"
                v-model="formList[index].systemStatus"
                active-color="#60c958"
                active-text="开启"
              ></el-switch>
            </div>
          </div>
          <div class="btn">
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              @click="delectList(index)"
            ></el-button>
          </div>
        </div>
      </div>
      <div class="authorityAdmin formChunk">
        <div class="title">
          <div class="text">权限管理</div>
        </div>
        <div class="btn">
          <el-input
            placeholder="接口名称、API描述"
            v-model="searchForm.nameOrRemark"
            @keyup.enter.native="getApiModuleHandle(searchForm)"
          >
            <i slot="suffix" class="el-input__icon el-icon-search" @click="getApiModuleHandle(searchForm)"></i>
          </el-input>
        </div>
        <div class="table">
          <div class="tree">
            <div class="title">
              <div class="text">业务模块</div>
            </div>
            <div class="item"
                 v-for="(item, index) in treeList" :key="item.catalogueId" @click="treeCLick(item)"
                 :class="{actived:searchForm.catalogueId===item.id}"
            >
              <div class="text">{{ item.name }}</div>
            </div>
          </div>
          <div class="left">
            <div class="tablecontent">
              <baseNewTable
                ref="mainTable"
                :tableData="mainTableData"
                :tableColumn="mainTableColumn"
                :showIndex="true"
                :tabLoading="mainTabLoading"
                @onFunc="tableButtonHandle"
                :border="false"
                :tableHeight="'50vh'"
              >
                <template v-slot:operation="{ row }">
                  <div class="checkChunk">
                    <el-checkbox v-model="row[item.id]" v-for="(item,index) in operationList" :label="item.id"
                                 :key="item.id" @change="(val)=>operationListClick(val,row,item)">{{ item.name }}
                    </el-checkbox>
                  </div>
                </template>
              </baseNewTable>
            </div>
            <div class="page">
              <basePage
                :pageModel="pageModel"
                @update:pageModel="currentChangeHandle"
              ></basePage>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import baseNewSelect from "@/views/applicationList/com/baseNewSelect.vue";
import baseDialog from "@/views/integrationOption/compoments/baseDialog";
import basePage from "../apiList/compoments/basePage.vue";
import baseNewTable from "../apiList/compoments/baseTable.vue";
import BaseTable from "@/views/intergrationTask/compoments/baseTable.vue";
import configData from "./configData";
import baseNewForm from "@/views/intergrationTask/compoments/baseNewForm";
import {getApiModuleApi} from "@/api/apiChunks";
import {deepClone} from "@/utils/index.js";
import {getUserModuleApi} from "@/api/integrationOption/integrationOption";

export default {
  data() {
    return {
      operationList: [],
      mainTabLoading: false,
      fileList: [],
      iconBase64: "",
      value1: true,
      authorityRuleForm: [{}],
      lookFlag: false,
      authorityFormRow: configData.authorityFormRow,
      formList: [],
      switchTag: [],
      treeList: [],
      // 页码
      pageModel: {
        pageIndex: 1,
        total: 2,
        limit: 10,
      },
      mainTableData: [{}],
      mainTableColumn: [
        {
          id: "catalogueName",
          title: "业务模块",
        },
        {
          id: "apiName",
          title: "接口名称",
        },
        {
          id: "destinationAddress",
          title: "接口地址",
        },
        {
          id: "apiRemark",
          title: "API描述",
        },
        {
          id: "errorCount",
          title: "异常统计",
        },
        {id: "operation", title: "操作"}
      ],
      checkbox: [],
      // 搜索表单
      searchForm: {},
      // 校验后果的表单
      resultList: []
    };
  },
  methods: {
    // 保存接口
    saveHandle() {
      let pattern = /^http(s)?:\/\/?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\*\+,;=.]+$/
      let allFlag = false
      allFlag = this.formList.some(item => {
        if (item.systemAddress) {
          let tempArr = item.systemAddress.split(',')
          let pattern = /((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}/
          let flag = tempArr.some(item => {
            if (!pattern.test(item)) {
              this.$vmNews(`${item}ip不合法请重新输入`)
              return true
            } else {
              return false
            }
          })
          return flag
        }
      })
      if (allFlag) return
      this.resultList = []
      this.$refs.mainForm.forEach(item => {
        item.submitForm()
      })
    },
    async onSubmit(item) {
      this.resultList.push(item)
      if (this.resultList.length === this.formList.length) {
        const res = await getApiModuleApi({
          tl: "sysApplicationService",
          as: "application",
          dj: "saveAppApiAuth"
        }, {appId: this.$route.query.id, apiAuths: this.resultList})
        console.log(res)
        if (res.status === '200') {
          this.$vmNews("保存成功", 'success')
          this.initQueryAppApiAuth()
        }
      }
    },
    // 操作点击事件
    async operationListClick(val, row, item) {
      let obj = {
        statusType: val ? 2 : 1,
        appId: this.$route.query.id,
        catalogueId: row.catalogueId,
        apiId: row.id,
        tripartiteSystemId: item.id
      }
      const res = await getApiModuleApi({
        tl: "sysApplicationService",
        as: "application",
        dj: "saveAppApiAuthDetail"
      }, obj)
      if (res.status === '200') {
        this.$vmNews(res.msg, 'success')
      }
    },
    // 树的初始化
    async initTreeData() {
      const res = await getApiModuleApi({
        tl: "sysApplicationService",
        as: "application",
        dj: "queryAppApiType"
      }, {appId: this.$route.query.id})
      if (res.status === '200') {
        this.treeList = res.attribute
      }
    },
    treeCLick(item) {
      this.$set(this.searchForm, 'catalogueId', item.id)
      this.$set(this.searchForm, 'name', item.name)
      this.getApiModuleHandle(this.searchForm)
    },
    // 获取api模块
    async getApiModuleHandle(obj = {}) {
      this.mainTabLoading = true;
      const res = await getApiModuleApi(
        {
          tl: "sysApplicationService",
          as: "application",
          dj: "queryAppApi",
        },
        {
          pageNum: this.pageModel.pageIndex,
          pageSize: this.pageModel.limit,
          appId: this.$route.query.id,
          ...obj,
        }
      );
      if (res.status == 200) {
        if (
          this.pageModel.pageIndex * this.pageModel.limit >=
          this.pageModel.total - 1 + this.pageModel.limit
        ) {
          this.pageModel.pageIndex--;
        }
        this.pageModel.total = res.attribute.total;
        res.attribute.list.forEach(item => {
          if (item.authDetails) {
            item.authDetails.forEach(ele => {
              item[ele] = true
            })
          }
        })
        this.mainTableData = res.attribute.list;
        this.$nextTick(() => {
          this.$refs.mainTable.setTableKey();
        });
      }
      this.mainTabLoading = false;
    },
    // 搜索框按钮
    searchBtnHandle() {
      this.pageModel.pageIndex = 1;
      this.$nextTick(() => {
        this.getApiModuleHandle(this.searchForm);
      });
    },
    delectList(index) {
      this.$delConfirm().then(() => {
        this.formList.splice(index, 1);
      })
    },
    tableButtonHandle(index, row) {
      if (this.tableData.length > 1) {
        this.tableData.splice(row.index, 1);
      }
    },
    newRow() {
      this.tableData.push({});
    },
    addRow() {
      this.formList.push({systemStatus: 1});
    },
    // 切页吗
    currentChangeHandle(pageModel) {
      this.pageModel = pageModel;
      this.$nextTick(() => {
        this.getApiModuleHandle(this.searchForm);
      });
    },
    async initQueryAppApiAuth() {
      const res = await getApiModuleApi({
        tl: "sysApplicationService",
        as: "application",
        dj: "queryAppApiAuth"
      }, {appId: this.$route.query.id})
      if (res.status === '200') {
        this.formList = []
        this.operationList = []
        for (let i = 0; i < res.attribute.length; i++) {
          const result = await getUserModuleApi({
            tl: "sysApplicationService",
            as: "application",
            dj: "getApp"
          }, {id: res.attribute[i].name})
          this.formList.push({
            id: res.attribute[i].id,
            name: res.attribute[i].name,
            systemStatus: res.attribute[i].systemStatus,
            systemAddress: res.attribute[i].systemAddress
          })
          console.log(result, 'result')
          this.operationList.push({
            id: res.attribute[i].id,
            name: result.attribute.name,
            systemStatus: res.attribute[i].systemStatus,
            systemAddress: res.attribute[i].systemAddress
          })
        }
      }

    },
    onSelectHanlde(val, ruleForm, item) {
      this.$set(ruleForm, 'systemAddress', item.systemAddress)
    }
  },
  components: {
    baseNewForm,
    BaseTable,
    basePage,
    baseNewTable,
    baseDialog,
    baseNewSelect
  },
  created() {
    this.initQueryAppApiAuth()
    this.getApiModuleHandle()
    this.initTreeData()
    this.$emit("flashActive", 4)
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-button {
  border-radius: 16px;
}

::v-deep .el-form-item {
  display: block !important;
}

.checkChunk {
  display: flex;
  flex-wrap: wrap;
}

.wrap {
  background-color: #fbfbfb;
  width: 100%;

  > .btn {
    display: flex;
    justify-content: flex-end;

    > .chunk {
      margin-left: 10px;
    }
  }

  > .main {
    margin-top: 10px;

    > .formChunk {
      border-radius: 16px;
      background-color: #fff;
      padding: 24px 30px;

      > .title {
        font-size: 18px;
        font-weight: 600;
        display: flex;
        justify-content: space-between;
      }

      .list {
        display: flex;
        align-items: center;

        .form {
          flex: 0.95;
        }

        .btn {
          flex: 0.05;
          display: flex;
          justify-content: center;
        }
      }

      .form {
        margin-top: 30px;
        border: 1px solid #979797;
        padding: 15px;
        border-radius: 6px;
        display: flex;
        align-items: center;

        .left {
          flex: 0.9;
        }

        .right {
          flex: 0.1;
          display: flex;
          justify-content: center;
        }
      }
    }

    > .authorityAdmin {
      margin-top: 20px;

      .btn {
        width: 20vw;
        margin-top: 10px;
      }

      .table {
        display: flex;

        .tree {
          width: 15%;
          background-color: #fff;
          border-radius: 16px;
          margin-right: 1%;
          padding: 0 10px;
          height: 55vh;
          overflow: auto;

          > .title {
            margin-top: 26px;
            padding: 14px;
            border-radius: 16px;
            background-color: #f7f7f7;
            font-weight: 600;
            text-align: center;
            position: relative;

            > i {
              position: absolute;
              top: 14px;
              right: 10px;
              cursor: pointer;
            }
          }

          > .item {
            text-align: left;
            margin: 10px 0;
            border-radius: 16px;
            padding: 10px 15px;
            cursor: pointer;

            &:hover {
              background-color: #f7f7f7;
            }
          }

          .actived {
            background-color: #f7f7f7 !important;
          }
        }

        .left {
          background-color: #fff;
          border-radius: 16px;
          width: 84%;
          padding: 15px;
        }
      }
    }
  }
}
</style>
