<template>
  <div class="fullheight">
    <ht-sidebar-dialog
      width="48%"
      title="外部系统管理"
      class="sp-manager__dialog"
      :visible="dialogVisible"
      v-if="dialogVisible"
      :before-close="beforeCloseDialog"
    >
      <el-form
        v-form
        v-model="PortalBizSystem"
        data-vv-scope="PortalBizSystemForm"
      >
        <ht-form-item label="系统编码" label-width="140px">
          <ht-input
            v-model="PortalBizSystem.sysCode"
            :maxlength="50"
            show-word-limit
            validate="required: true|regex:^[a-zA-Z][a-zA-Z0-9_]*$,只能输入字母、数字、下划线，且以字母开头"
            placeholder="请输入系统编码，系统编码不可重复"
            :width="450"
            :disabled="disabled"
          />
        </ht-form-item>
        <ht-form-item label="系统名称" label-width="140px">
          <ht-input
            v-model="PortalBizSystem.sysName"
            :validate="{required: true}"
            placeholder="请输入系统名称..."
            :width="450"
            :maxlength="50"
            show-word-limit
          />
        </ht-form-item>
        <ht-form-item label="系统密匙" label-width="140px" class="item-width">
          <ht-input
            v-model="PortalBizSystem.secretKey"
            validate="required: true|regex:^[a-zA-Z][a-zA-Z0-9_]*$,只能输入字母、数字、下划线，且以字母开头"
            placeholder="请输入系统密匙..."
            :width="450"
            :maxlength="100"
            show-word-limit
          />
        </ht-form-item>
        <!-- <ht-form-item label="管理员名称"> -->
        <!-- <ht-input v-model="PortalBizSystem.managerName" validate="required" /> -->
        <!-- </ht-form-item> -->

        <ht-form-item label="管理员名称" label-width="140px">
          <ht-user-selector-input
            v-model="PortalBizSystem.users"
            :config="{id: 'userIds', fullname: 'userNames'}"
            :validate="{required: true}"
            :single="false"
            append-to-body
            select-label="id"
            @valueChange="input"
          />
          <!--          <ht-select-->
          <!--              placeholder="请选择管理员"-->
          <!--              v-model="PortalBizSystem.managerId"-->
          <!--              class="m-r"-->
          <!--              :options="options"-->
          <!--              :validate="{required:true}"-->
          <!--          />-->
        </ht-form-item>

        <ht-form-item label="系统根路径" label-width="140px">
          <ht-input
            v-model="PortalBizSystem.rootAddress"
            validate="required: true"
            placeholder="如  http://127.0.0.1"
            :width="450"
            :maxlength="200"
            show-word-limit
          />
        </ht-form-item>
        <ht-form-item label="系统首页地址" label-width="140px">
          <ht-input
            v-model="PortalBizSystem.homeAddress"
            :validate="{required: true}"
            :maxlength="200"
            show-word-limit
            placeholder="如  http://127.0.0.1/index"
            :width="450"
          />
        </ht-form-item>
        <ht-form-item label="流程消息队列" label-width="140px">
          <ht-input
            v-model="PortalBizSystem.bpmMsgQueue"
            validate="regex:^[a-zA-Z][a-zA-Z0-9_]*$,只能输入字母、数字、下划线，且以字母开头"
            :maxlength="50"
            show-word-limit
            placeholder="如  flowQueue"
            :width="450"
          />
        </ht-form-item>
        <ht-form-item label="系统描述" label-width="140px">
          <ht-input
            v-model="PortalBizSystem.description"
            :validate="{required: true}"
            type="textarea"
            placeholder="请输入系统描述..."
            :width="450"
            :maxlength="200"
            show-word-limit
          />
        </ht-form-item>
        <ht-form-item label="接口授权账号" label-width="140px">
          <ht-user-selector-input
            v-model="PortalBizSystem.robotId"
            :config="{id: 'robotId', fullname: 'robotName'}"
            :validate="{required: true}"
            :single="true"
            append-to-body
          />
          <!--          <ht-select-->
          <!--              v-model="PortalBizSystem.robotId"-->
          <!--              class="m-r"-->
          <!--              :options="robotId"-->
          <!--              :validate="{required:true}"-->
          <!--          />-->
        </ht-form-item>
        <ht-form-item label="是否启用" label-width="140px">
          <el-switch
            v-model="PortalBizSystem.enabled"
            active-text="启用"
            inactive-text="关闭"
          >
          </el-switch>
          <!-- <ht-input v-model="PortalBizSystem.enabled" validate="required" /> -->
        </ht-form-item>
        <el-divider>配置认证接口</el-divider>
        <ht-form-item label="入参方式" label-width="140px">
          <ht-radio
            v-model="PortalBizSystem.tokenType"
            class="ht"
            :options="[
              {key: 0, value: '头部参数'},
              {key: 1, value: 'URL参数'}
            ]"
          />
        </ht-form-item>
        <ht-form-item label="票据入参KEY" label-width="140px">
          <ht-input
            v-model="PortalBizSystem.tokenKey"
            validate="regex:^[a-zA-Z][a-zA-Z0-9_]*$,只能输入字母、数字、下划线，且以字母开头"
            :maxlength="50"
            show-word-limit
            placeholder="如  token"
            :width="450"
          />
        </ht-form-item>
        <ht-form-item label="票据入参VALUE" label-width="140px">
          <el-button type="primary" plain @click="showBizAuthDialog"
            >配置认证接口
          </el-button>
          <el-button @click="clearBizAuthDialog" size="small" type="text"
            >清除</el-button
          >
        </ht-form-item>
        <ht-form-item label="票据过期时间" label-width="140px">
          <ht-input
            v-model="PortalBizSystem.tokenExpire"
            validate="regex:^[0-9]*$,只能输入数字"
            :maxlength="6"
            show-word-limit
          />
          <span> 秒</span>
        </ht-form-item>
      </el-form>
      <div slot="footer" style="text-align: right">
        <el-button @click="beforeCloseDialog"
          >{{ $t('eip.common.cancel') }}
        </el-button>
        <el-button type="primary" @click="submitData"
          >{{ $t('eip.common.save') }}
        </el-button>
      </div>
    </ht-sidebar-dialog>
    <!-- 配置认证接口对话框 -->
    <biz-auth-dialog
      v-if="dialogVisible"
      @onConfirm="authDialogConfirm"
      ref="bizAuthDialog"
    />
  </div>
</template>
<script>
import utils from '@/hotent-ui-util.js'
const bizAuthDialog = () => import('@/components/dialog/BizAuthDialog.vue')
export default {
  components: {
    bizAuthDialog
  },
  data() {
    return {
      dialogVisible: false,
      apiInfo: {},
      PortalBizSystem: {users: '', enabled: true},
      saveMethod: 'POST',
      options: [],
      robotId: '',
      managerName: '',
      users: '',
      userIds: '',
      robotName: '',
      deletedUserId: [],
      originUsers: '',
      disabled: false
    }
  },
  mounted() {},
  created() {
    // this.loadMangerName()
    this.$validator = this.$root.$validator
  },
  methods: {
    //显示 配置认证接口对话框
    showBizAuthDialog() {
      this.$refs.bizAuthDialog.showDialog(this.apiInfo)
    },
    //配置认证接口对话框 确认保存
    authDialogConfirm(apiInfo) {
      this.apiInfo = apiInfo
    },
    input(value) {},
    showDialog(id) {
      this.PortalBizSystem.users = ''
      this.userNames = ''
      this.userIds = ''
      if (id) {
        this.saveMethod = 'PUT'
        this.$http
          .get('${portal}/portalBizSystem/v1/searchById?id=' + id)
          .then(resp => {
            this.robotId = resp.data.value.robotId
            this.PortalBizSystem = {...this.PortalBizSystem, ...resp.data.value}
            this.disabled = this.PortalBizSystem.sysCode ? true : false
            for (let item of this.PortalBizSystem.managerList) {
              if (this.userIds && this.userNames) {
                this.userIds = this.userIds + ',' + item.managerId
                this.userNames = this.userNames + ',' + item.managerName
                this.PortalBizSystem.users =
                  this.PortalBizSystem.users + ',' + item.managerName
              } else {
                this.userIds = item.managerId
                this.userNames = item.managerName
                this.PortalBizSystem.users = item.managerName
              }
            }
            this.PortalBizSystem.robotId = this.PortalBizSystem.robotName
            //认证接口
            this.apiInfo = {}
            if (this.PortalBizSystem.tokenApiInfo) {
              this.apiInfo = JSON.parse(this.PortalBizSystem.tokenApiInfo)
            }
            this.dialogVisible = true
            this.originUsers = this.userIds
            if (this.PortalBizSystem) {
              this.PortalBizSystem.enabled =
                this.PortalBizSystem.enabled == '0' ? true : false
            }
          })
      } else {
        this.apiInfo = {}
        this.saveMethod = 'POST'
        this.dialogVisible = true
        this.disabled = false
      }
    },
    clearBizAuthDialog() {
      this.apiInfo = {}
    },
    loadData(param) {
      this.$http.post('${portal}/portalBizSystem/v1/query', param).then(
        resp => {
          let response = resp.data
          this.data = response.rows
          this.pageResult = {
            page: response.page,
            pageSize: response.pageSize,
            total: response.total
          }
        },
        error => {
          reject(error)
        }
      )
    },
    beforeCloseDialog() {
      this.PortalBizSystem = {}
      this.dialogVisible = false
    },
    afterSaveData() {
      setTimeout(() => {
        // ("---")
        this.$emit('loadData', {})
        this.beforeCloseDialog()
      }, 500)
    },
    submitData() {
      if (this.saveMethod == 'POST') {
        utils
          .validateForm(this, 'PortalBizSystemForm')
          .then(valid => {
            let userList = []
            let manageNames = this.userNames.split(',')
            let manageIds = this.userIds.split(',')
            for (let i = 0; i < manageNames.length; i++) {
              let user = {managerId: manageIds[i], managerName: manageNames[i]}
              userList.push(user)
            }
            this.PortalBizSystem.managerList = userList
            this.PortalBizSystem.robotName = this.robotName
            this.PortalBizSystem.robotId = this.robotId
            this.PortalBizSystem.tokenApiInfo = this.apiInfo
              ? JSON.stringify(this.apiInfo)
              : ''
            if (valid) {
              var httpReg = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/
              var queueReg = /^[a-zA-Z][a-zA-Z0-9_]*$/
              if (!httpReg.test(this.PortalBizSystem.rootAddress)) {
                this.$message.error('系统根路径输入不合法')
                return
              }
              if (!httpReg.test(this.PortalBizSystem.homeAddress)) {
                this.$message.error('系统首页地址输入不合法')
                return
              }
              // if (!queueReg.test(this.PortalBizSystem.bpmMsgQueue)) {
              //   this.$message.error(
              //     '流程消息队列输入不合法，只能输入字母、数字、下划线，且以字母开头'
              //   )
              //   return
              // }

              let PortalBizSystemDeep = _.cloneDeep(this.PortalBizSystem)
              delete PortalBizSystemDeep.users
              this.$http
                .post('${portal}/portalBizSystem/v1/save', PortalBizSystemDeep)
                .then(res => {
                  if (res.data.state) {
                    this.$message.success(res.data.message)
                    setTimeout(() => {
                      this.afterSaveData()
                    }, 1000)
                  }
                })
            }
          })
          .catch(items => {
            this.$message.error(`还有内容未填写，无法提交表单。`)
          })
      } else {
        let _this = this
        utils
          .validateForm(this, 'PortalBizSystemForm')
          .then(valid => {
            let userList = []
            let manageNames = this.userNames.split(',')
            let manageIds = this.userIds.split(',')
            for (let i = 0; i < manageNames.length; i++) {
              let user = {managerId: manageIds[i], managerName: manageNames[i]}
              userList.push(user)
            }
            this.PortalBizSystem.managerList = userList
            this.PortalBizSystem.robotId = this.robotId
            this.PortalBizSystem.robotName = this.robotName
            this.PortalBizSystem.tokenApiInfo = this.apiInfo
              ? JSON.stringify(this.apiInfo)
              : ''
            if (valid) {
              var reg = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/
              var queueReg = /^[a-zA-Z][a-zA-Z0-9_]*$/
              if (!reg.test(this.PortalBizSystem.rootAddress)) {
                this.$message.error('系统根路径输入不合法')
                return
              }
              if (!reg.test(this.PortalBizSystem.homeAddress)) {
                this.$message.error('系统首页地址输入不合法')
                return
              }
              // if (!queueReg.test(this.PortalBizSystem.bpmMsgQueue)) {
              //   this.$message.error(
              //     '流程消息队列输入不合法，只能输入字母、数字、下划线，且以字母开头'
              //   )
              //   return
              // }
              let PortalBizSystemDeep = _.cloneDeep(this.PortalBizSystem)
              delete PortalBizSystemDeep.users
              _this.$http
                .post(
                  '${portal}/portalBizSystem/v1/update',
                  PortalBizSystemDeep
                )
                .then(res => {
                  this.$message.success(res.data.message)
                  setTimeout(() => {
                    this.afterSaveData()
                  }, 1000)
                })
            }
          })
          .catch(items => {
            this.$message.error(`还有内容未填写，无法提交表单。`)
          })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.sp-manager__dialog /deep/ > .el-dialog > .el-dialog__body {
  height: calc(100% - 190px);
}
/deep/.item-width .ht-form-inputs__inline {
  width: 240px;
}
.inputs.ht-form-inputs__inline {
  width: 300px;
}
</style>
