<template>
  <div class="fullheight">
    <ht-table
      @load="loadData"
      :data="data"
      :pageResult="pageResult"
      :selection="true"
      :defaultSorter="[{property: 'CREATE_TIME_', direction: 'DESC'}]"
      :default-querys="[
        {
          property: 'type_',
          value: 'column',
          operation: 'EQUAL',
          relation: 'AND'
        }
      ]"
      quick-search-props="name,memo"
      :show-export="false"
      ref="layoutTable"
      @row-click="rowClick"
      :header-cell-class-name="headerCellClassName"
      @selection-change="handleSelectionChange"
    >
      <template v-slot:toolbar>
        <!-- <el-button-group> -->
        <el-button
          size="small"
          @click="addLayout(0)"
          icon="el-icon-plus"
          type="primary"
          >添加管理端布局</el-button
        >
        <!-- <el-button size="small" @click="addLayout(1)" icon="el-icon-plus" type="primary" plain
            >添加手机端布局</el-button
          > -->
        <el-button
          size="small"
          @click="addLayout(2)"
          icon="el-icon-plus"
          type="primary"
          plain
          >添加应用端布局</el-button
        >
        <el-button size="small" icon="el-icon-upload2" @click="showUploadDialog"
          >导入</el-button
        >
        <el-button
          size="small"
          icon="el-icon-download"
          @click="exportOrgLayout"
          :disabled="isDisabled"
          >导出</el-button
        >
        <ht-delete-button
          style="margin-left: 10"
          :url="deleteUrl"
          isLayout
          :htTable="$refs.layoutTable"
          :disabled="isDisabled"
          successMessage="删除门户成功"
          >删除</ht-delete-button
        >
        <!-- </el-button-group> -->
      </template>
      <template>
        <ht-table-column type="index" width="50" align="center" label="序号" />
        <ht-table-column prop="id" label="主键" :sortable="true" hidden />
        <ht-table-column
          prop="name"
          label="布局名称"
          :sortable="true"
          :show-overflow-tooltip="true"
        >
          <template v-slot="{row}">
            <el-link
              @click="handleCommand({row: row, command: 'edit'})"
              type="primary"
              title="点击编辑"
              >{{ row.name }}</el-link
            >
          </template>
        </ht-table-column>
        <ht-table-column prop="alias" label="布局别名" :sortable="true" />
        <ht-table-column
          prop="memo"
          label="布局描述"
          :sortable="true"
          :show-overflow-tooltip="true"
        />
        <ht-table-column
          prop="layoutType"
          label="布局类型"
          :render-header="renderHeaderMethod"
          :filters="[
            {text: '管理端', value: 0},
            {text: '应用端', value: 2},
            {text: '手机端', value: 1}
          ]"
        >
          <template v-slot="{row}">
            <el-tag v-if="row.layoutType == 0" type="info">管理端</el-tag>
            <el-tag v-if="row.layoutType == 2" type="warning">应用端</el-tag>
            <el-tag v-if="row.layoutType == 1" type="success">手机端</el-tag>
          </template>
        </ht-table-column>
        <ht-table-column
          prop="isDef"
          label="默认门户"
          :render-header="renderHeaderMethod"
          :filters="[
            {text: '否', value: 0},
            {text: '是', value: 1}
          ]"
        >
          <template v-slot="{row}">
            <el-tag v-if="row.isDef == 0" type="danger">否</el-tag>
            <el-tag v-if="row.isDef == 1" type="primary">是</el-tag>
          </template>
        </ht-table-column>
        <!-- <ht-table-column prop="rank" label="优先级"> </ht-table-column> -->
        <ht-table-column
          prop="enable"
          label="是否启用"
          :render-header="renderHeaderMethod"
          :filters="[
            {text: '已停用', value: 0},
            {text: '已启用', value: 1}
          ]"
        >
          <template v-slot="{row}">
            <el-tag v-if="row.enable == 0" type="danger">已停用</el-tag>
            <el-tag v-if="row.enable == 1" type="primary">已启用</el-tag>
          </template>
        </ht-table-column>
        <ht-table-column label="操作" width="200" align="left">
          <template v-slot="{row}">
            <el-button
              type="text"
              @click="handleCommand({row: row, command: 'preview'})"
              >预览</el-button
            >
            <el-button
              type="text"
              class="copy-btn"
              v-if="row.layoutType != 1"
              @click="handleCommand({row: row, command: 'copy'})"
              >复制</el-button
            >
            <el-dropdown
              size="mini"
              trigger="click"
              class="more-operate-btn__dropdown"
              @command="handleCommand"
              v-if="
                !['default_mobile', 'default_front', 'default_manage'].includes(
                  row.alias
                )
              "
            >
              <span class="more-operate-btn"
                >更多操作<i class="el-icon-caret-bottom"></i>
              </span>
              <el-dropdown-menu
                slot="dropdown"
                class="operate-dropdown__button"
              >
                <el-dropdown-item
                  v-if="row.isDef == 0"
                  :command="{row: row, command: 'auth'}"
                  >授权</el-dropdown-item
                >
                <el-dropdown-item
                  v-if="row.isDef == 0 && row.enable == 0"
                  icon="icon-switch"
                  :command="{row: row, command: 'enable', enable: 1}"
                  >启用</el-dropdown-item
                >
                <el-dropdown-item
                  v-if="row.isDef == 0 && row.enable == 1"
                  :command="{row: row, command: 'enable', enable: 0}"
                  >停用</el-dropdown-item
                >
                <el-dropdown-item
                  v-if="row.layoutType == 2"
                  :command="{row: row, command: 'releaseApp'}"
                  >发布菜单</el-dropdown-item
                >
                <el-dropdown-item
                  v-if="row.isDef == 0 && row.enable == 1"
                  :command="{row: row, command: 'setManager'}"
                  >设置管理员</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </ht-table-column>
      </template>
    </ht-table>
    <el-dialog
      title="选择管理员"
      :visible="choseAdminDialogVisible"
      :before-close="beforeClose"
      name="uploadDialog"
      width="40%"
      top="30vh"
      custom-class="upload-dialog"
      :destroy-on-close="true"
    >
      <ht-user-selector-input
        v-model="layoutRow.managerName"
        :append-to-body="true"
        :config="{id: 'layoutRow.managerId'}"
        validate="required"
        :single="false"
        @select-data="change"
      ></ht-user-selector-input>
      <span slot="footer" class="dialog-footer">
        <el-button type="default" @click="beforeClose">取消</el-button>
        <el-button type="primary" @click="saveManager(layoutRow)"
          >确定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      title="上传文件"
      :visible="uploadDialogVisible"
      :before-close="beforeClose"
      name="uploadDialog"
      width="40%"
      top="30vh"
      custom-class="upload-dialog"
    >
      <el-upload
        :action="uploadUrl"
        :http-request="handleImport"
        accept=".zip"
        :file-list="fileList"
        :limit="1"
        :auto-upload="false"
        :on-exceed="onExceed"
        ref="elUpload"
        class="upload-dialog__content"
      >
        <el-button size="small" icon="el-icon-upload">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传zip文件</div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="uploadSubmit">上传</el-button>
        <el-button type="default" @click="beforeClose">取消</el-button>
      </span>
    </el-dialog>

    <el-dialog
      width="60%"
      title="复制布局"
      :visible="dialogSaveCopyVisible"
      :before-close="handleCloseSaveCopy"
      :destroy-on-close="true"
    >
      <form v-form data-vv-scope="saveCopyLayout">
        <table class="form-table" cellspacing="0" cellpadding="0" border="0">
          <tbody>
            <tr>
              <th width="140px">原布局名称:</th>
              <td>{{ layoutRow.name }}</td>
              <th width="140px" class="is-required">新布局名称</th>
              <td>
                <ht-input
                  v-model="newLayout.name"
                  :validate="{required: true}"
                />
              </td>
            </tr>
            <tr>
              <th width="140px" class="is-required">原布局别名:</th>
              <td>{{ layoutRow.alias }}</td>
              <th width="140px" class="is-required">新布局别名</th>
              <td>
                <ht-input
                  v-model="newLayout.alias"
                  v-pinyin="newLayout.name"
                  autocomplete="off"
                  :validate="{
                    required: true,
                    regex: {
                      exp: '^[a-zA-Z][a-zA-Z0-9_]*$',
                      message: '只能输入字母、数字、下划线，且以字母开头'
                    },
                    isExist:
                      '${portal}/portal/sysIndexLayoutManage/sysIndexLayoutManage/v1/checkKey?key='
                  }"
                  placeholder="请输入别名"
                ></ht-input>
              </td>
            </tr>
            <!-- <tr>
              <th width="140px" class="is-required">原布局优先级:</th>
              <td>{{ layoutRow.rank }}</td>
              <th width="140px" class="is-required">新布局优先级</th>
              <td>
                <ht-input
                  type="number"
                  class="ht"
                  v-model="newLayout.rank"
                  :min="1"
                  :max="10000"
                  autocomplete="off"
                  placeholder="优先级（数字递增优先级递减）"
                ></ht-input>
              </td>
            </tr> -->
          </tbody>
        </table>
      </form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCloseSaveCopy">{{
          $t('eip.common.cancel')
        }}</el-button>
        <ht-submit-button
          url="${portal}/portal/sysIndexLayoutManage/sysIndexLayoutManage/v1/saveCopy"
          :model="newLayout"
          scope-name="saveCopyLayout"
          @after-save-data="afterSaveData"
          >{{ $t('eip.common.save') }}</ht-submit-button
        >
      </div>
    </el-dialog>

    <!-- 发布为前端菜单 dialog -->
    <template-add-to-menu
      ref="templateAddToMenu"
      name="templateAddToMenu"
      :alias="selectAlias"
      :isIndexLayout="true"
      append-to-body
    />

    <PortalDesignerDialog ref="designDialog" @close="designClose" />
    <eip-auth-dialog @onConfirm="layoutAuthConfirm" ref="layoutAuth" />
    <LayoutPreviewDialog ref="previewDialog" />
    <!-- 设置管理员 -->
    <LayoutAuthManager ref="LayoutAuthManager"></LayoutAuthManager>
    <ht-user-dialog
      ref="eipUserDialog"
      name="eipUserDialog"
      :single="false"
      @on-confirm="saveManager"
      append-to-body
    />
  </div>
</template>
<script>
import portal from '@/api/portal.js'
import utils from '@/hotent-ui-util.js'
const TemplateAddToMenu = () =>
  import('@/components/form/dataTemplate/TemplateAddToMenu.vue')
const PortalDesignerDialog = () =>
  import('@/components/portal/PortalDesignerDialog.vue')
const LayoutPreviewDialog = () =>
  import('@/views/portal/LayoutPreviewDialog.vue')
const eipAuthDialog = () => import('@/components/dialog/EipAuthDialog.vue')
const LayoutAuthManager = () => import('@/views/portal/LayoutAuthManager.vue')
import tableHeaderFilter from '@/mixins/tableHeaderFilter.js'
import req from '@/request'

let Base64 = require('js-base64').Base64
export default {
  components: {
    PortalDesignerDialog,
    LayoutPreviewDialog,
    eipAuthDialog,
    TemplateAddToMenu,
    LayoutAuthManager
  },
  mixins: [tableHeaderFilter],
  // props: ["orgId"],
  props: {
    orgId: {
      type: String
    },
    orgManagerNow: {
      //传入的组织对象 用于判断用户是否有增删改权限
      type: Object
    }
  },
  mounted() {},
  data() {
    return {
      selectAlias: '',
      designShow: false,
      sidebarTitle: '',
      dialogVisible: false,
      layout: {
        name: '',
        memo: '',
        templateHtml: '',
        templateHtml2: ''
      },
      data: [],
      pageResult: {
        page: 1,
        pageSize: 20,
        total: 0
      },
      loadDataUrl: '',
      uploadDialogVisible: false,
      choseAdminDialogVisible: false,
      fileList: [],
      uploadUrl: '',
      curAuthLayoutId: '',
      layoutRow: {managerId: '', managerName: ''},
      newLayout: {id: '', name: '', alias: '', rank: '', managerId: ''},
      dialogSaveCopyVisible: false,
      // 禁用
      isDisabled: true,
      selectedList: [],
      curId: '',
      currentSelectUsers: []
    }
  },
  watch: {
    selectedList: {
      handler(val) {
        this.isDisabled = val.length < 1 ? true : false
      },
      deep: true
    }
  },
  computed: {
    deleteUrl: function() {
      return (
        window.context.portal +
        '/portal/sysIndexLayoutManage/sysIndexLayoutManage/v1/remove'
      )
    }
  },
  methods: {
    handleSelectionChange(selection) {
      this.selectedList = selection
    },
    rowClick(row, column, event) {
      this.$refs.layoutTable.$refs.htTable.toggleRowSelection(row)
    },
    addLayout(layoutType) {
      if (layoutType == 0) {
        //管理端
        this.$refs.designDialog.showDialog('', layoutType)
      } else if (layoutType == 1) {
        //手机端
        this.$refs.designDialog.showDialog('', layoutType)
      } else if (layoutType == 2) {
        this.$refs.designDialog.showDialog('', layoutType)
        //应用端
      }
    },
    designClose(val) {
      this.$refs.layoutTable.load()
    },
    loadData(param, cb) {
      portal
        .getLayoutManagerPage(param)
        .then(response => {
          this.data = response.rows
          this.pageResult = {
            page: response.page,
            pageSize: response.pageSize,
            total: response.total
          }
        })
        .finally(() => cb && cb())
    },
    handleCommand(params) {
      this.layoutRow = params.row
      switch (params.command) {
        case 'preview':
          this.preview(params.row)
          break
        case 'shareToSub':
          this.shareToSub(params.row.id, params.share)
          break
        case 'enable':
          this.enable(params.row.id, params.enable)
          break
        case 'edit':
          if (params.row.type == 'column') {
            this.$refs.designDialog.showDialog(
              params.row.id,
              params.row.layoutType
            )
          } else {
            this.$refs.datavDialog.showDialog(
              params.row.id,
              params.row.layoutType
            )
          }
          break
        case 'auth':
          this.layoutAuth(params.row)
          break
        case 'copy':
          this.saveCopy()
          break
        case 'releaseApp':
          // this.saveCopy();
          this.selectAlias = params.row.alias
          this.$refs.templateAddToMenu.showDialog(
            'front',
            'addReport',
            params.row.id
          )
          break
        case 'setManager':
          this.layoutRow.managerId = params.row.managerId || ''
          this.layoutRow.managerName = params.row.managerName || ''
          this.setManager(params.row.id, 0)
          break
      }
    },
    saveCopy() {
      this.newLayout.id = this.layoutRow.id
      this.dialogSaveCopyVisible = true
    },
    handleCloseSaveCopy() {
      this.newLayout = {id: '', name: '', alias: '', rank: '', managerId: ''}
      this.dialogSaveCopyVisible = false
    },
    afterSaveData() {
      this.handleCloseSaveCopy()
      this.$refs.layoutTable.load()
    },
    layoutAuth(row) {
      let this_ = this
      this.curAuthLayoutId = row.id
      this.$http
        .get(
          '${portal}/sys/authUser/v1/getRightsAndDefaultRightType?id=' +
            row.id +
            '&objType=layoutManage'
        )
        .then(function(resp) {
          if (resp.data) {
            let conf = {
              right: resp.data.right,
              permissionList: resp.data.type,
              autoClose: false
            }
            this_.$refs.layoutAuth.showDialog(conf)
          }
        })
    },
    layoutAuthConfirm(data) {
      let param = {
        id: this.curAuthLayoutId,
        objType: 'layoutManage',
        ownerNameJson: JSON.stringify(data)
      }
      let this_ = this
      this.$http
        .post('${portal}/sys/authUser/v1/saveRights', param)
        .then(function(resp) {
          if (resp.data) {
            if (resp.data.state) {
              this_.$message.success('授权成功')
              this_.$refs.layoutAuth.closeDialog()
            } else {
              this_.$message.error(resp.data.message)
            }
          }
        })
    },
    shareToSub(id, share) {
      this.$confirm(
        `${share == 1 ? '确认共享给子部门' : '确认取消共享'}吗?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        portal.setlayoutMngShareToSub(id, share).then(data => {
          if (data.state) {
            this.$message({message: data.message, type: 'success'})
            this.$refs.layoutTable.load()
          } else {
            this.$message({message: data.message, type: 'error'})
          }
        })
      })
    },
    enable(id, enable) {
      this.$confirm(`确定${enable == 1 ? '启用' : '停用'}该布局吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        portal.setlayoutMngEnable(id, enable).then(data => {
          if (data.state) {
            this.$message({message: data.message, type: 'success'})
            this.$refs.layoutTable.load()
          } else {
            this.$message({message: data.message, type: 'error'})
          }
        })
      })
    },
    preview(row) {
      if (row.type == 'datav') {
        let previewKey =
          Date.parse(new Date()) + '_' + Math.ceil(Math.random() * 99999)
        const designHtml = Base64.decode(row.designHtml)
        sessionStorage.setItem(previewKey, designHtml)
        let routeData = this.$router.resolve({
          name: 'datavPreview',
          query: {key: previewKey}
        })
        window.open(routeData.href, '_blank')
      } else {
        this.$refs.previewDialog.showDialog(row, 'preview')
      }
    },
    exportOrgLayout() {
      let selection = this.$refs.layoutTable.$refs.htTable.selection
      if (!selection || selection.length == 0) {
        this.$message.warning('请至少选择一条数据')
        return
      }
      let defIds = new Array()
      selection.forEach(item => {
        defIds.push(item.id)
      })
      if (defIds.length > 0) {
        this.$http.request({
          url: `${window.context.portal}/portal/sysIndexLayoutManage/sysIndexLayoutManage/v1/exportDefaultLayout`,
          method: 'POST',
          data: defIds,
          responseType: 'arraybuffer'
        })
      }
    },
    beforeClose() {
      this.uploadDialogVisible = false
      this.choseAdminDialogVisible = false
      this.fileList.splice(0)
    },
    uploadSubmit() {
      if (this.$refs.elUpload.uploadFiles.length == 0) {
        this.$message.warning('请上传文件')
        return
      }
      this.$refs.elUpload.submit()
    },
    handleImport(param) {
      let formData = new FormData()
      formData.append('file', param.file)

      portal.importDefaultLayoutCheck(formData, this.orgId).then(resp => {
        if (resp.state) {
          this.$message.success(resp.message)
          this.fileList.splice(0)
          this.uploadDialogVisible = false
          this.$refs.layoutTable.load()
        } else if (resp.message.includes('覆盖更新')) {
          const height =
            (document.documentElement.clientHeight ||
              document.body.clientHeight) *
              0.85 +
            'px'
          this.$confirm(
            '<div style="overflow-x:hidden;overflow-y:auto ;max-height:' +
              height +
              '">' +
              resp.message +
              '</div>',
            '提示',
            {
              cancelButtonText: '取消',
              dangerouslyUseHTMLString: true,
              confirmButtonText: '确定',
              type: 'warning',
              closeOnClickModal: false
            }
          ).then(() => {
            formData.append('cacheFileId', resp.value)
            portal.importOrgLayout(formData, this.orgId).then(resp2 => {
              if (resp2.state) {
                this.$message.success(resp2.message)
                this.fileList.splice(0)
                this.uploadDialogVisible = false
                this.$refs.layoutTable.load()
              } else {
                this.$message.error(resp2.message)
                this.beforeClose()
              }
            })
          })
        } else {
          // this.$message.error(resp.message);
          this.beforeClose()
        }
      })
    },
    showUploadDialog() {
      this.uploadDialogVisible = true
    },
    onExceed() {
      this.$message.warning('只能选择一个zip文件!')
    },
    setManager(id, typeId) {
      this.curId = id

      this.$refs.LayoutAuthManager.showDialog(typeId, id)
      // this.$refs.eipUserDialog.showDialog({})
    },
    saveManager(data) {
      if (!data.managerId || !data.managerName) {
        this.$message.warning('请选择至少一个用户')
        return
      }
      req
        .get(
          `${window.context.portal}/portal/sysIndexLayoutManage/sysIndexLayoutManage/v1/saveManager?id=${data.id}&userId=${data.managerId}&fullname=${data.managerName}`
        )
        .then(res => {
          if (res.data.state) {
            this.$message.success(res.data.message)
            this.$refs.layoutTable.load()
          }
        })
    },
    //选择用户确认事件
    eipUserDialogOk(data) {
      this.currentSelectUsers = data
    },
    /**
     * 选择用户之后触发
     * @param data
     */
    change(data) {
      const managerId = data && data.map(e => e.id).toString()
      const managerName = data && data.map(e => e.fullname).toString()
      this.layoutRow.managerId = managerId
      this.layoutRow.managerName = managerName
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep {
  .cell > .el-table__column-filter-trigger {
    display: none;
  }
}

div[aria-invalid='true'] >>> .el-input__inner,
div[aria-invalid='true'] >>> .el-input__inner:focus {
  border-color: #f56c6c;
}

a:hover {
  cursor: pointer;
  color: blue;
}

.el-button--primary.is-plain {
  background: #fff;
}

.el-button--primary.is-plain:hover {
  background: #409eff;
}
::v-deep {
    // 数据列表样式
    .ht-data-sheets {
      .no-tabs {
        padding: 16px 12px !important;
      }
      .form-list--header {
        display: none;
      }
      .template-preview-container {
        .template-content {
          display: block;
        }
        .field-wrap {
          padding: 12px;
        }
        .footer-wrap,
        .form-list--footer {
          display: none !important;
        }
        .van-cell__value {
          background: #f9f9f9;
          border-radius: 8px 8px 8px 8px;
        }
        .field-item--title,
        .field-content {
          padding: 0 !important;
        }

        .field-item--title {
          width: 100% !important;
        }
        .form-list--content {
          height: 100% !important;
          min-height: 150px;
        }
        .van-cell {
          padding: 0 !important;
        }
        .van-list > div:nth-last-of-type(2) {
          margin-bottom: 0 !important;
        }

        .van-cell:nth-last-of-type(1) {
        }
      }
    }
  }
</style>
