<script src="configData.js"></script>
<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">
        <el-button
          icon="el-icon-first-aid-kit"
          type="primary"
          @click="saveHandle"
        >保存
        </el-button
        >
      </div>
    </div>
    <div class="main">
      <div class="exploitSetting formChunk">
        <div class="title">开发设置</div>
        <div class="form">
          <baseNewForm
            ref="exploitSettingForm"
            :spanNumber="24"
            :isFunBtn="false"
            :lookFlag="lookFlag"
            :formRule="!lookFlag"
            :formRow="exploitSettingFormRow"
            :ruleForm="exploitSettingRuleForm"
            @onSubmit="exploitSettingOnSubmit"
            @dblclick="dblclick"
          ></baseNewForm>
        </div>
      </div>
      <div class="apiEnv formChunk">
        <div class="title">
          <div class="text">接口环境</div>
          <div class="btn">
            <el-switch
              active-value="1"
              inactive-value="2"
              v-model="interfaceStatus"
              active-color="#60c958"
              active-text="开启"
            ></el-switch>
          </div>
        </div>
        <div class="form">
          <baseNewForm
            ref="mainForm"
            :spanNumber="24"
            :isFunBtn="false"
            :lookFlag="lookFlag"
            :formRule="!lookFlag"
            :formRow="apiEnvFormRow"
            :ruleForm="apiEnvRuleForm"
          ></baseNewForm>
          <div class="btn">
            <el-button type="primary" @click="newRow">新增行</el-button>
          </div>
          <div class="table">
            <BaseTable
              ref="mainTable"
              :tableData="tableData"
              :tableColumn="tableColumn"
              :showIndex="true"
              :tabLoading="mainTabLoading"
              :funData="funData"
              @onFunc="tableButtonHandle"
              :tableHeight="'30vh'"
              :border="false"
              @newRow="newRow"
            >
              <template v-slot:interfaceKey="{ row }">
                <el-input v-model="row.interfaceKey" placeholder=""></el-input>
              </template>
              <template v-slot:interfaceValue="{ row }">
                <el-input
                  v-model="row.interfaceValue"
                  placeholder=""
                ></el-input>
              </template>
              <template v-slot:interfaceType="{ row }">
                <el-select v-model="row.interfaceType" placeholder="">
                  <el-option
                    v-for="item in locationOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </template>
            </BaseTable>
          </div>
        </div>
      </div>
      <div class="dataSetting formChunk">
        <div class="title">
          <div class="text">数据源设置</div>
          <div class="btn">
            <el-button
              :loading="testLoading"
              @click="testHandle"
              :type="testResult ? 'success' : 'primary'"
              style="margin-right: 10px"
            >{{ testResult ? "测试通过" : "点击测试" }}
              <i v-if="testResult" class="el-icon-check el-icon--right"></i>
            </el-button>
            <el-switch
              v-model="dbStatus"
              active-value="1"
              inactive-value="2"
              active-color="#60c958"
              active-text="开启"
              :disabled="!testResult"
              @click.native="switchCLick"
            ></el-switch>
          </div>
        </div>
        <div class="form">
          <baseNewForm
            ref="dataSettingForm"
            :spanNumber="24"
            :isFunBtn="false"
            :lookFlag="lookFlag"
            :formRule="!lookFlag"
            :formRow="dataSettingFormRow"
            :ruleForm="dataSettingRuleForm"
            @onSubmit="dataSettingOnSubmit"
            @onSelect="dataSettingFormChange"
            @onInput="dataSettingFormChange"
          ></baseNewForm>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import BaseTable from "@/views/intergrationTask/compoments/baseTable.vue";
import configData from "./configData";
import {getApiModuleApi} from "@/api/apiChunks/index.js";
import baseNewForm from "@/views/intergrationTask/compoments/baseNewForm";

export default {
  data() {
    return {
      // loading
      mainTabLoading: false,
      // 文件list
      fileList: [],
      // 头像转base
      iconBase64: "",
      // 状态
      lookFlag: false,
      // 开发设置表单
      exploitSettingFormRow: configData.exploitSettingFormRow,
      exploitSettingRuleForm: {
        sourceType: []
      },
      // 接口环境
      apiEnvFormRow: configData.apiEnvFormRow,
      apiEnvRuleForm: {interfaceAddress: ""},
      tableData: [],
      tableColumn: configData.tableColumn,
      funData: [
        {
          text: "删除",
          color: "#e47470",
        },
      ],
      apiEnvOpen: 2,
      // 数据源
      dataSettingFormRow: configData.dataSettingFormRow,
      dataSettingRuleForm: {},
      locationOptions: [
        {
          value: "1",
          label: "Header",
        },
        {
          value: "2",
          label: "Body",
        },
      ],
      testResult: false,
      // 测试loading
      testLoading: false,
      // 接口环境开关
      interfaceStatus: 2,
      // 接口环境开关
      dbStatus: 2,
    };
  },
  methods: {
    //双击复制
    dblclick(val) {
      navigator.clipboard.writeText(val)
      this.$vmNews("内容已复制到剪贴板", 'success')
    },
    // 数据源测试改变事件
    dataSettingFormChange() {
      this.testResult = false;
      this.dbStatus = 2;
    },
    // 开关点击事件（需要测试才可以点）
    switchCLick() {
      if (!this.testResult) {
        this.$vmNews("请测试通过后再开启", "warning");
      }
    },
    // 删除行
    tableButtonHandle(index, row) {
      this.tableData.splice(index.index, 1);
    },
    // 新增行
    newRow() {
      this.tableData.push({interfaceType: "1"});
    },
    // 测试按钮
    testHandle() {
      this.$refs.dataSettingForm.submitForm();
    },
    //点击保存后验证
    saveHandle() {
      let pattern = /^http(s)?:\/\/?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\*\+,;=.]+$/
      if (this.apiEnvRuleForm.interfaceAddress && !pattern.test(this.apiEnvRuleForm.interfaceAddress)) {
        this.$vmNews("接口地址不合法，请重新输入！", "warning")
        return
      }
      if (this.interfaceStatus != 2) {
        if (!this.apiEnvRuleForm.interfaceAddress) {
          this.$vmNews("接口环境开启时，接口地址不能为空！", "warning");
          return;
        }
        let flag = this.tableData.some((item, index) => {
          if (item.interfaceKey == "" || !item.interfaceKey) {
            this.$vmNews(`接口环境开启时，接口环境第${index + 1}行Key不能为空!`)
            return true
          } else if (item.interfaceValue == "" || !item.interfaceValue) {
            this.$vmNews(`接口环境开启时，接口环境第${index + 1}行Value不能为空!`)
            return true
          } else if (item.interfaceType == "" || !item.interfaceType) {
            this.$vmNews(`接口环境开启时，接口环境第${index + 1}行位置不能为空!`)
            return true
          } else {
            return false
          }
        })
        if (flag) {
          return
        }
      }
      this.$refs.exploitSettingForm.submitForm();
    },
    async dataSettingOnSubmit() {
      this.testLoading = true;
      //测试成功
      // this.testResult = true;
      try {
        const res = await getApiModuleApi({
          tl: "sysApplicationService",
          as: "application",
          dj: "testDatabase"
        }, {...this.dataSettingRuleForm})
        if (res.status === '200' && res.flag) {
          this.testResult = true;
          this.$vmNews("测试通过开关已开启", "success")
        }
      } catch (err) {
        this.testResult = false
      }
      this.testLoading = false;
    },
    // 验证成功
    async exploitSettingOnSubmit() {
      if (this.exploitSettingRuleForm.systemAddress) {
        let tempArr = this.exploitSettingRuleForm.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
          }
        })
        if (flag) return
      }

      let obj = {
        updateType: 2,
        id: this.$route.query.id,
        interfaceStatus: this.interfaceStatus,
        dbStatus: this.dbStatus,
        ...this.exploitSettingRuleForm,
        ...this.apiEnvRuleForm,
        apiParas: this.tableData,
        databaseEntity: {
          ...this.dataSettingRuleForm,
        }
      }
      const res = await getApiModuleApi({
        tl: "sysApplicationService",
        as: "application",
        dj: "updateApp"
      }, {...obj})
      if (res.status === '200') {
        this.$vmNews("保存成功", "success")
        this.initDataInfo()
      }
    },
    async initDataInfo() {
      const res = await getApiModuleApi({
        tl: 'sysApplicationService',
        as: "application",
        dj: "queryAppAll"
      }, {id: this.$route.query.id})
      if (res.status === '200') {
        if (res.attribute.databaseEntity) {
          this.dataSettingRuleForm = res.attribute.databaseEntity;
          console.log('数据源设置id:' + res.attribute.databaseEntity.id)
        }
        this.tableData = res.attribute.apiParas;
        this.apiEnvRuleForm.interfaceAddress = res.attribute.app.interfaceAddress
        this.dbStatus = res.attribute.app.dbStatus
        if (this.dbStatus == 1) {
          this.testResult = true
        }
        this.interfaceStatus = res.attribute.app.interfaceStatus
        this.exploitSettingRuleForm = {
          accessMode: JSON.parse(res.attribute.app.accessMode),
          clientPath: res.attribute.app.clientPath,
          webPath: res.attribute.app.webPath,
          programPath: res.attribute.app.programPath,
          publicKey: res.attribute.app.publicKey,
          secretKey: res.attribute.app.secretKey,
          appId: res.attribute.app.appId,
          systemAddress: res.attribute.app.systemAddress,
        }
      }
    }
  },
  components: {
    baseNewForm,
    BaseTable,
  },
  created() {
    this.initDataInfo()
    this.$emit("flashActive", 1)
    // if (this.$route.query.id) {
    //   this.lookFlag = true;
    // } else {
    //   this.lookFlag = false;
    // }
  },
  watch: {
    // dataSettingRuleForm: {
    //   deep: true,
    //   handler(newV, oldV) {
    //     this.testResult = false;
    //     this.dbStatus = 2;
    //   },
    // },
  },
};
</script>

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

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

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

  > .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;
      }

      > .form {
        margin-top: 30px;
      }
    }

    > .apiEnv {
      margin-top: 20px;

      .form {
        border: 1px solid #979797;
        border-radius: 8px;
        padding: 16px 0;

        .btn {
          display: flex;
          margin-right: 15px;
          justify-content: flex-end;
        }

        > .table {
          padding: 16px;
        }
      }
    }

    > .dataSetting {
      margin-top: 20px;

      .form {
        border: 1px solid #979797;
        border-radius: 8px;
        padding: 16px 0;

        > .table {
          padding: 16px;
        }
      }
    }
  }
}
</style>
