<template>
  <div class="fullheight" style="padding:0 20px;">
    <el-tabs v-model="currentTabName" class="fullheight">
      <el-tab-pane label="基本信息" name="basic">
        <div class="fullheight" style="overflow-y: auto;">
          <el-form
            v-form
            data-vv-scope="tenantManageForm"
            class="tenant-form"
            label-position="left"
          >
            <ht-form-item label="类型" label-width="120px" v-if="tenantId">
              <ht-select
                class="ht"
                v-model="tenantManage.typeId"
                :options="tenantTypeList"
                :props="{key: 'id', value: 'name'}"
                validate="required"
              />
            </ht-form-item>
            <ht-form-item label="管理端名称" label-width="120px">
              <ht-input
                v-model="tenantManage.name"
                :validate="{required: true}"
                autocomplete="off"
                :maxlength="20"
                :showWordLimit="true"
              />
              <el-tooltip
                class="item"
                effect="dark"
                content="管理端名称会作为登录页的公司名称"
                placement="right-start"
              >
                <span
                  class="icon-my-todo-comment"
                  style="margin-left: 10px"
                ></span>
              </el-tooltip>
            </ht-form-item>
            <ht-form-item label="别名" label-width="120px">
              <ht-input
                v-model="tenantManage.code"
                autocomplete="off"
                :validate="{
                  regex: {
                    exp: '^[a-z]{0,10}\\d{0,3}$',
                    message:
                      '别名只能包含小写字母和数字，且必须以小写字母开头，小写字母最多10个，数字最多3个'
                  },
                  required: true,
                }"
                :disabled="tenantManage.id ? true : false"
                v-pinyin="tenantManage.name"
                :maxlength="10"
                :showWordLimit="true"
              />
              <el-tooltip
                class="item"
                effect="dark"
                content="别名只能包含小写字母和数字，且必须以小写字母开头，小写字母最多10个，数字最多3个"
                placement="right-start"
              >
                <span
                  class="icon-my-todo-comment"
                  style="margin-left: 10px"
                ></span>
              </el-tooltip>
            </ht-form-item>
            <ht-form-item label="应用端名称" label-width="120px">
              <ht-input
                v-model="tenantManage.nameFront"
                :validate="{required: true}"
                autocomplete="off"
                :maxlength="20"
                :showWordLimit="true"
              />
              <el-tooltip
                class="item"
                effect="dark"
                content="应用端名称会作为登录页的公司名称"
                placement="right-start"
              >
                <span
                  class="icon-my-todo-comment"
                  style="margin-left: 10px"
                ></span>
              </el-tooltip>
            </ht-form-item>
            <ht-form-item label="简称" label-width="120px">
              <ht-input
                v-model="tenantManage.shorthand"
                validate="required"
                :maxlength="20"
                :showWordLimit="true"
              />
            </ht-form-item>
            <ht-form-item
              v-if="tenantId && tenantId != '-1'"
              label="租户域名"
              label-width="120px"
            >
              <ht-input v-model="tenantManage.baseUrl" autocomplete="off" />
            </ht-form-item>
            <ht-form-item v-if="tenantId" label="状态" label-width="120px">
              <ht-select
                v-model="tenantManage.status"
                :options="
                  tenantManage.status == 'draft' ? draftOptions : statusOpition
                "
                :validate="{
                  required: true,
                  regex: {
                    exp: '^[\\s\\S]{1,30}$',
                    message: '内容超出输入限制'
                  }
                }"
              />
            </ht-form-item>
            <ht-form-item
              label="访问地址"
              label-width="120px"
              v-if="tenantManage.id && tenantManage.id != '-1'"
            >
              <el-link type="primary" @click="showCopyUrl">查看地址</el-link>
            </ht-form-item>
            <!-- <ht-form-item label="域名地址" label-width="120px">
                <ht-input v-model="tenantManage.domain" />
              </ht-form-item> -->
            <ht-form-item label-width="120px">
              <template slot="label">
                <span>管理端LOGO</span>
              </template>
              <FileUpload
                ref="manageLogo"
                model-name="tenantManage.manageLogo"
                :cover="true"
                :accept="`.jpg,.jpeg,.png,.JPG,.JPEG`"
                :multiple="false"
              >
              </FileUpload>
              <div style="position: absolute;right: 5px;top: 0;">
                <el-tooltip placement="right-start">
                  <div slot="content">
                    建议上传的logo宽为215px，高为60px
                  </div>
                  <i class="icon-my-todo-comment" />
                </el-tooltip>
              </div>
            </ht-form-item>

            <ht-form-item label="用户端LOGO" label-width="120px">
              <FileUpload
                ref="frontLogo"
                model-name="tenantManage.frontLogo"
                :cover="true"
                :accept="`.jpg,.jpeg,.png,.JPG,.JPEG`"
                :multiple="false"
              >
              </FileUpload>
            </ht-form-item>
            <ht-form-item label="登录页LOGO" label-width="120px">
              <FileUpload
                ref="ico"
                model-name="tenantManage.ico"
                :cover="true"
                :accept="`.jpg,.jpeg,.png,.JPG,.JPEG`"
                :multiple="false"
              >
              </FileUpload>
            </ht-form-item>
            <ht-form-item label="描述" label-width="120px">
              <ht-input
                type="textarea"
                v-model="tenantManage.desc"
                placeholder="请输入类型说明"
                :maxlength="100"
                :showWordLimit="true"
              />
            </ht-form-item>
            <ht-form-item style="text-align: center;">
              <ht-submit-button
                ref="submitButton"
                url="${uc}/uc/tenantManage/v1/save"
                :model="tenantManage"
                scope-name="tenantManageForm"
                :is-submit="isSubmit"
                :loading="savaLoading"
                @before-save-data="beforeSaveData"
                @after-response-value="afterResponseValue"
              >保存</ht-submit-button
              >
            </ht-form-item>
          </el-form>
        </div>
      </el-tab-pane>
      <el-tab-pane
        label="扩展信息"
        v-if="tenantManage.id && tenantManage.status != 'draft'"
        name="params"
      >
        <div class="fullheight" v-if="tenantParams && tenantParams.length">
          <el-form
            v-form
            data-vv-scope="tenantParam"
            class="user-param-form"
            label-position="left"
          >
            <template v-for="param in tenantParams">
              <ht-form-item
                :label="param.name"
                prop="name"
                label-width="150px"
                :key="param.name"
              >
                <el-date-picker
                  v-model="tenantParam[param.code]"
                  type="datetime"
                  placeholder="选择日期时间"
                  v-if="param.ctlType === 'date'"
                ></el-date-picker>
                <ht-input
                  v-model="tenantParam[param.code]"
                  v-if="param.ctlType === 'input'"
                  :maxlength="200"
                  :showWordLimit="true"
                />
                <ht-input
                  type="number"
                  v-model="tenantParam[param.code]"
                  v-if="param.ctlType === 'number'"
                  :maxlength="200"
                  :showWordLimit="true"
                />
                <ht-select
                  v-model="tenantParam[param.code]"
                  v-if="param.ctlType === 'select'"
                  :options="JSON.parse(param.json)"
                />
                <ht-radio
                  v-model="tenantParam[param.code]"
                  v-if="param.ctlType === 'radio'"
                  :options="JSON.parse(param.json)"
                />
                <ht-checkbox
                  v-model="tenantParam[param.code]"
                  v-if="param.ctlType === 'checkbox'"
                  :options="JSON.parse(param.json)"
                />
              </ht-form-item>
            </template>
            <ht-form-item style="text-align: center;">
              <el-button type="primary" @click="tenantParamSubmit"
              >保存</el-button
              >
            </ht-form-item>
          </el-form>
        </div>
        <el-empty
          v-else
          class="fullheight"
          :image-size="380"
          :image="noDataImg"
          description="暂无扩展信息~"
        >
        </el-empty>
      </el-tab-pane>
      <el-tab-pane
        label="邮件设置"
        name="mailService"
        v-if="tenantManage.id && tenantManage.status != 'draft'"
        class="fullheight"
      >
        <tenant-mail-server-manager
          ref="tenantMailServerManager"
          :tenantId="curSelectTenantId"
        ></tenant-mail-server-manager>
      </el-tab-pane>
      <el-tab-pane
        label="印章管理"
        name="signetService"
        v-if="tenantManage.id && tenantManage.status != 'draft'"
        class="fullheight"
      >
        <sys-signet-manager
          v-if="currentTabName === 'signetService'"
          ref="signetManager"
          :tenantId="curSelectTenantId"
        ></sys-signet-manager>
      </el-tab-pane>
      <el-tab-pane label="安全设置" name="SecuritySetting" :lazy="true" v-if="$route.name !=='tenant'">
        <security-setting ref="securitySetting"></security-setting>
      </el-tab-pane>
      <!--      <el-tab-pane-->
      <!--        label="授权信息"-->
      <!--        name="authorizationInformation"-->
      <!--        :lazy="true"-->
      <!--        v-if="-->
      <!--          currentUser.userAttrs && currentUser.userAttrs.tenantId == '-1' &&-->
      <!--            tenantManage.id &&-->
      <!--            tenantManage.status != 'draft'-->
      <!--        "-->
      <!--      >-->
      <!--        <div class="authorization-information">-->
      <!--          <div class="information-header">-->
      <!--            <h3 class="title">授权基础信息</h3>-->
      <!--            <ul class="header-items">-->
      <!--              <li-->
      <!--                class="header-item"-->
      <!--                v-for="(item, index) in cardList"-->
      <!--                :key="index"-->
      <!--              >-->
      <!--                <h4 class="second-title">{{ item.title || '无限制' }}</h4>-->
      <!--                <p class="header-content">{{ item.content || '无限制' }}</p>-->
      <!--              </li>-->
      <!--            </ul>-->
      <!--          </div>-->
      <!--          <div class="information-content">-->
      <!--            <template v-if="isShowPie">-->
      <!--              <h3 class="title">月活跃用户</h3>-->
      <!--              <pie-echart-->
      <!--                chartId="pie-chart"-->
      <!--                :option="pieOption"-->
      <!--                :chartStyle="chartStyle"-->
      <!--              ></pie-echart>-->
      <!--            </template>-->
      <!--            <el-empty-->
      <!--              v-else-->
      <!--              :image-size="380"-->
      <!--              :image="noDataImg"-->
      <!--              description="无权限限制"-->
      <!--            >-->
      <!--            </el-empty>-->
      <!--          </div>-->
      <!--        </div>-->
      <!--      </el-tab-pane>-->
    </el-tabs>
    <!-- 租户访问地址 -->
    <tenant-access-address
      ref="tenantAccessAddress"
      :baseUrl="tenantManage.baseUrl"
    ></tenant-access-address>
  </div>
</template>
<script>
const FileUpload = () => import('@/components/common/FileUpload.vue')
const tenantMailServerManager = () =>
  import('@/views/system/TenantMailServerManager.vue')
const sysSignetManager = () => import('@/views/system/SysSignetManager.vue')
const SecuritySetting = () => import('@/views/system/SecuritySetting.vue')
const tenantAccessAddress = () =>
  import('@/components/tenant/TenantAccessAddress.vue')
const PieEchart = () => import('@/components/common/Chart.vue')
import auth from '@/api/auth.js'
import {mapState} from 'vuex'
export default {
  name: 'tenantInfoManager',
  props: ['tenantId'],
  components: {
    FileUpload,
    tenantMailServerManager,
    tenantAccessAddress,
    sysSignetManager,
    SecuritySetting,
    PieEchart
  },
  data() {
    const this_ = this
    return {
      savaLoading:false,
      isSubmit: true,
      noDataImg: require('@/assets/nodata_images/no-data.png'),
      currentTabName: 'basic',
      dialogVisible: false,
      tenantManage: { status: 'enable', code: ''},
      curSelectTenantId: '',
      tenantTypeList: [],
      tenantParam: {}, //当前租户的参数值
      tenantParams: [], //系统的所有组合类型参数
      draftOptions: [
        {key: 'draft', value: '草稿'},
        {key: 'enable', value: '启用'},
        {key: 'disabled', value: '禁用'}
      ],
      statusOpition: [
        {key: 'enable', value: '启用'},
        {key: 'disabled', value: '禁用'}
      ],
      cardList: [
        {
          title: '授权主体',
          key: 'enterpriseName',
          content: '广州宏天软件股份有限公司'
        },
        {
          title: '授权有效期',
          key: 'expireIn',
          content: '2022-08-25'
        },
        {
          title: '副本数量',
          key: 'instanceCount',
          content: '1'
        }
      ],
      pieData: [
        {value: 0, name: '当前已使用', key: 'userCountMonth'},
        {value: 0, name: '当前可使用', key: 'maxUserCountMonth'}
      ],
      isShowPie: false,
      pieOption: {
        tooltip: {
          trigger: 'item'
        },
        color: ['#409EFF', 'rgba(204,204,204,0.4)'],
        series: [
          {
            name: '月活',
            type: 'pie',
            radius: ['70%', '80%'],
            avoidLabelOverlap: false,
            hoverAnimation: false,
            label: {
              normal: {
                show: false
              }
            },
            emphasis: {
              scale: false
            },
            labelLine: {
              show: false
            },
            data: []
          }
        ],
        legend: {
          bottom: '0',
          left: 'center',
          itemWidth: 16,
          itemHeight: 16,
          itemGap: 64,
          borderRadius: 2,
          selectedMode: false,
          formatter: function(name) {
            let value = this_.pieData.find(item => item.name === name).value
            return [`{name|${name}}:`, `{value|${value}}`].join(' ')
          },
          textStyle: {
            rich: {
              name: {
                fontSize: 14,
                color: '#888'
              },
              value: {
                fontSize: 20,
                color: '#333',
                fontWeight: 'bold'
              }
            }
          }
        },
        title: {
          text: [`{value|856}`, '{total|/ 1000}'].join(' '),
          textStyle: {
            rich: {
              total: {
                fontSize: 20,
                color: '#888'
              },
              value: {
                fontSize: 20,
                color: '#333',
                fontWeight: 'bold'
              }
            }
          },
          left: 'center',
          top: 'middle'
        }
      },
      chartStyle: 'width:100%;height:360px'
    }
  },
  watch: {
    'tenantManage.code': {
      handler(val) {
        if (val.length >= 10)
          this.tenantManage.code = val.substring(0, 10)
      }
    }
  },
  computed: {
    ...mapState('login', ['currentUser'])
  },
  created() {
    // this.getAuthorizationMessage()
  },
  mounted() {
    this.$validator = this.$root.$validator
    this.curSelectTenantId = this.tenantId
    if (!this.tenantId) {
      this.curSelectTenantId =
        this.currentUser.userAttrs && this.currentUser.userAttrs.tenantId
    }
    if (this.curSelectTenantId == 'add') {
      this.curSelectTenantId = ''
      this.getTenantTypeList()
    }
    let url = '${uc}/uc/tenantManage/v1/getJson?id=' + this.curSelectTenantId
    if (this.curSelectTenantId) {
      let _this = this
      this.$http.get(url).then(
        resp => {
          _this.tenantManage = resp.data
          setTimeout(function() {
            if (_this.tenantManage.manageLogo) {
              _this.$refs.manageLogo.setFiles(
                JSON.parse(_this.tenantManage.manageLogo)
              )
            }
            if (_this.tenantManage.frontLogo) {
              _this.$refs.frontLogo.setFiles(
                JSON.parse(_this.tenantManage.frontLogo)
              )
            }
            if (_this.tenantManage.ico) {
              _this.$refs.ico.setFiles(JSON.parse(_this.tenantManage.ico))
            }
          }, 1000)
          this.getTenantTypeList()
          this.initTenantParams()
        },
        error => {
          reject(error)
        }
      )
    }
  },
  methods: {
    getAuthorizationMessage() {
      auth.getAuthorizeMessage().then(({data}) => {
        if (data && data.state) {
          const {maxUserCountMonth, userCountMonth} = data.value || {}
          this.isShowPie = maxUserCountMonth > 0
          this.cardList = this.cardList.map(item => {
            return {
              ...item,
              content: data.value[item.key]
            }
          })
          if (maxUserCountMonth && maxUserCountMonth > 0) {
            this.pieData = this.pieData.map(item => {
              const availableNum = maxUserCountMonth - userCountMonth
              return {
                ...item,
                value:
                  item.key === 'maxUserCountMonth'
                    ? availableNum
                    : data.value[item.key]
              }
            })
            this.pieOption.series[0].data = this.pieData
            this.pieOption.title.text = [
              `{value|${userCountMonth}}`,
              `{total|/ ${maxUserCountMonth}}`
            ].join(' ')
          }
        }
      })
    },
    legendFormatter(name) {},
    getTenantTypeList() {
      let that = this
      this.$store.dispatch('tenant/actionTenantId', null)
      this.$http
        .get('${uc}/uc/tenantType/v1/getAll?status=enable')
        .then(
          resp => {
            that.tenantTypeList = resp.data
            that.$store.dispatch('tenant/actionTenantId', that.tenantId)
          },
          error => {
            that.$store.dispatch('tenant/actionTenantId', that.tenantId)
            reject(error)
          }
        )
        .then(() => {
          if (!that.curSelectTenantId) {
            let list = that.tenantTypeList.filter(
              item => item.isDefault === '1'
            )
            that.$set(this.tenantManage, 'typeId', list[0].id)
          }
        })
    },
    //初始化租户扩展参数
    initTenantParams() {
      let that = this
      if (this.tenantManage.id) {
        this.$http
          .get(
            '${uc}/api/params/v1/tenantParams/getTenantParams?tenantTypeId=' +
            this.tenantManage.typeId
          )
          .then(resp => {
            that.tenantParams = resp.data
            return resp.data
          })
          .then(params => {
            if (!params || params.constructor != Array || params.length < 1) {
              return
            }
            this.$http
              .get(
                '${uc}/uc/tenantParams/v1/getParamsValue?tenantId=' +
                that.tenantManage.id
              )
              .then(response => {
                if (response.data && response.data.constructor == Array) {
                  response.data.forEach(r => {
                    that.$set(that.tenantParam, r['code'], r['value'])
                  })
                }
                that.$store.dispatch('tenant/actionTenantId', that.tenantId)
              })
          })
      }
    },
    tenantParamSubmit() {
      var data = []
      let tenantParam = this.tenantParam
      for (let _param in tenantParam) {
        if (tenantParam.hasOwnProperty(_param)) {
          data.push({alias: _param, value: this.tenantParam[_param]})
        }
      }
      let _this = this
      if (data.length > 0) {
        this.$http
          .post(
            '${uc}/uc/tenantParams/v1/saveTenantParams?tenantId=' +
            this.tenantManage.id,
            data
          )
          .then(
            resp => {
              let response = resp.data
              if (!response.state) {
                _this.$message.error(response.message)
              } else {
                _this.$message.success(response.message)
              }
            },
            error => {
              reject(error)
            }
          )
      }

    },
    beforeSaveData() {
      this.savaLoading = true
      if (this.$refs.manageLogo.getFiles() != '') {
        this.tenantManage.manageLogo = JSON.stringify(
          this.$refs.manageLogo.getFiles()
        )
      } else {
        this.tenantManage.manageLogo = ''
      }
      if (this.$refs.frontLogo.getFiles() != '') {
        this.tenantManage.frontLogo = JSON.stringify(
          this.$refs.frontLogo.getFiles()
        )
      } else {
        this.tenantManage.frontLogo = ''
      }
      if (this.$refs.ico.getFiles() != '') {
        this.tenantManage.ico = JSON.stringify(this.$refs.ico.getFiles())
      } else {
        this.tenantManage.ico = ''
      }
      var httpReg = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/
      if (
        this.tenantManage.baseUrl &&
        !httpReg.test(this.tenantManage.baseUrl)
      ) {
        this.$message.error('租户域名输入不合法')
        this.isSubmit = false
        this.savaLoading = false
        return
      }

      if (this.tenantId == 'add') {
        this.isSubmit = false
        this.$http
          .get('${uc}/uc/tenantManage/v1/checkCode?code=' + this.tenantManage.code + '&tenantId=' + this.tenantId)
          .then(res => {
            if (res && res.data) {
              this.savaLoading = false
              this.$message.error('别名已存在')
            } else {
              this.$refs.submitButton.requestSaveData()
            }
          })
      } else {
        this.isSubmit = true
      }

    },
    afterResponseValue(value) {
      this.savaLoading = false
      if (this.tenantId == 'add') {
        this.tenantManage.id = value
        this.$emit('after-add-success', this.tenantManage)
      } else if (this.tenantId) {
        this.$emit('after-add-success', this.tenantManage)
      }
      this.initTenantParams()
      this.$refs.signetManager&&this.$refs.signetManager.loadData()
    },
    showCopyUrl() {
      this.$refs.tenantAccessAddress.showDialog(
        this.tenantManage.code,
        this.tenantManage.baseUrl
      )
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/.el-tabs__content {
  height: calc(100% - 56px);
  .el-tab-pane {
    height: 100%;
    .user-param-form,
    .tenant-form {
      width: 630px;
      margin: 40px auto;
      .inputs.ht-form-inputs__inline {
        width: 480px !important;
      }
      .el-form-item--small.el-form-item {
        margin-bottom: 30px;
      }
    }
  }
}
::v-deep {
  .el-tabs .el-tabs__item {
    height: 56px;
    line-height: 56px;
    .is-active {
      color: #409eff;
      font-weight: 700;
    }
  }
}
.sp-manager__dialog /deep/ > .el-dialog > .el-dialog__body {
  height: calc(100% - 170px);
}
.authorization-information {
  padding: 25px 16px 16px 16px;
  .information-header {
    border: 1px solid #e6e6e6;
    padding: 32px;
  }
  .title {
    font-size: 16px;
    color: #333;
    margin: 0 0 24px 0;
  }
  .header-items {
    display: flex;

    .header-item {
      list-style: none;
      width: calc(33.33% - 64px);
      height: 70px;
      padding: 24px;
      margin-right: 64px;
      background: #f8f8f8;
      border-radius: 2px;
      .second-title {
        font-size: 14px;
        color: #888;
        margin: 0;
        padding-bottom: 15px;
        font-weight: 400;
      }
      .header-content {
        font-size: 16px;
        color: #333;
        margin: 0;
        font-weight: bold;
      }
    }
  }
  .information-content {
    margin-top: 48px;
    border: 1px solid #e6e6e6;
    padding: 32px;
  }
}
</style>
