<template>
  <div :class="$style.wrapHeight">
    <div :class="$style.rowHeight">
      <AuditPermissionTree
        :key="key"
        :checkable="false"
        :draggable="false"
        :is-search="true"
        :show-line="true"
        :top-node-text="topNodeText"
        :treeparams="{
          configId: '1',
          type: this.libCategory,
        }"
        :default-expanded-keys="['1']"
        :is-select-dep="false"
        :dep-options="[]"
        @treeSelect="treeSelect"
        @depChanged="depChanged"
      ></AuditPermissionTree>
      <div :class="$style.rightcard">
        <sd-form v-if="parentId !== 0" ref="form" :init-values="valuesdemo">
          <table v-if="!refresh" ref="table">
            <tr
              ><td width="140px">分级授权管理员:</td
              ><td>
                <sd-user-picker
                  v-model="values.hierarchyManager"
                  :single="false"
                  :read-only="false"
                />
                <a-tooltip
                  slot="suffix"
                  title="说明：一、配置了分级授权管理员即开启了分级授权，反之清空了分级授权管理员就关闭了分级授权。二、分级授权只能一级一级开启，不可跨级开启。"
                >
                  <a-icon type="info-circle" />
                </a-tooltip> </td
            ></tr>
            <tr v-for="(item, index) in values.moduleEditPermissionList" :key="index"
              ><td colspan="2">
                <table :class="$style.moduletable">
                  <tr
                    ><td width="140px">模&ensp;&ensp;&ensp;&ensp;块:</td
                    ><td
                      ><span>{{ item.moduleName }}</span></td
                    ></tr
                  >
                  <tr
                    ><td>模块管理员:</td
                    ><td><sd-user-picker v-model="item.manager" :read-only="false"/></td
                  ></tr>
                  <tr
                    ><td>维护范围:</td
                    ><td>
                      <a-radio-group v-model="item.editScope">
                        <a-radio :style="radioStyle" :value="'本机构'">
                          本机构
                        </a-radio>
                        <a-radio :style="radioStyle" :value="'本机构及下级机构'">
                          本机构及下级机构
                        </a-radio>
                      </a-radio-group>
                    </td></tr
                  >
                </table>
              </td></tr
            >
            <tr
              ><td colspan="2" :class="$style.buttonstyle">
                <a-button type="primary" :class="$style.buttonStyle" @click="saveedit"
                  >保存</a-button
                >
              </td></tr
            >
          </table>
        </sd-form>
        <div v-else>当前节点为空组织</div>
      </div>
    </div>
    <div :class="$style.loading">
      <a-spin v-if="parentId !== 0 && refresh" />
    </div>
  </div>
</template>

<script>
import loginService from '@/login/login-service'
import { Modal } from 'ant-design-vue'
import TableActionTypes from '@/common/services/table-action-types'
// import { getUserPerms } from '@/common/store-mixin'
import AuditPermissionTree from '../../components/audit-permission-tree.vue'
import PermissionService from './permission-service'
import components from './_import-components/iam-audit-editpermission-import'

export default {
  name: 'IamAuditEditpermission',
  metaInfo: {
    title: '维护权限',
  },
  components: {
    ...components,
    AuditPermissionTree,
  },
  props: {
    libCategory: {
      type: String,
      default: 'SJ',
    },
  },
  data() {
    return {
      type: 'SJ',
      key: 0,
      treeData: [],
      parentId: 0,
      defaultSelectedKeys: [this.orgId],
      columns: [],
      infolist: [],
      values: [],
      valuesdemo: [],
      actions: [
        {
          label: '新建',
          id: 'new',
          type: TableActionTypes.oa.create, // 新建按钮，不需要回调，自动处理
        },
        {
          label: '删除',
          id: 'delete',
          type: TableActionTypes.oa.delete, // 删除按钮，不需要回调，会自动处理
        },
      ],
      radioStyle: {
        height: '30px',
        lineHeight: '30px',
      },
      orgId: null,
      orgName: '',
      rootNode: {},
      selectOrgId: null,
      refresh: true,
    }
  },
  computed: {
    topNodeText() {
      let title = '机构库'
      switch (this.type) {
        case 'SJ':
          title = '审计机构库'
          break
        case 'FK':
          title = '风控机构库'
          break
        default:
          break
      }
      return title
    },
  },
  watch: {
    'values.hierarchyManager': {
      immediate: true,
      handler(val, pre) {
        if (!pre) {
          return
        }
        if (!val) {
          val = []
        }
        console.log(val)
        console.log(pre)
        console.log(this.values.moduleEditPermissionList)
        val.forEach((newE) => {
          const index = pre.findIndex((s) => s.code === newE.code)
          if (index === -1) {
            this.values.moduleEditPermissionList.forEach((moduleEdit) => {
              if (!moduleEdit.manager) {
                moduleEdit.manager = []
              }
              const mangerIndex = moduleEdit.manager.findIndex((s) => s.code === newE.code)
              if (mangerIndex === -1) {
                moduleEdit.manager.push(newE)
              }
            })
          }
        })
        pre.forEach((oldE) => {
          const index = val.findIndex((s) => s.code === oldE.code)
          if (index === -1) {
            this.values.moduleEditPermissionList.forEach((moduleEdit) => {
              if (!moduleEdit.manager) {
                moduleEdit.manager = []
              }
              const mangerIndex = moduleEdit.manager.findIndex((s) => s.code === oldE.code)
              if (mangerIndex !== -1) {
                moduleEdit.manager.splice(mangerIndex, 1)
              }
            })
          }
        })
        console.log(this.values.moduleEditPermissionList)
      },
    },
  },
  created() {
    if (this.$route.query.type !== undefined) {
      this.type = this.$route.query.type
    }
  },
  methods: {
    treeSelect(selectedKeys, info) {
      this.parentId = info.node.dataRef.id // 父级id
      this.parentName = info.node.dataRef.text // 父级名称
      if (info.node.dataRef.props === undefined) {
        this.selectOrgId = this.parentId
      } else {
        this.selectOrgId = Number(info.node.dataRef.props.ORG_ID)
      }
      this.parentObj = [{ id: info.node.dataRef.id, name: info.node.dataRef.text }]
      this.rootNode = {
        id: info.node.dataRef.id,
        code: this.selectOrgId,
        name: info.node.dataRef.text,
      }
      if (this.parentId !== 0) {
        this.getvalues(info.node.dataRef.id)
      }
    },
    // 部门下拉框选择事件
    depChanged(value, info) {
      // console.log(value) // 选中的值
      // console.log(info.data.props) // 选中的下拉json
    },
    getvalues(orgId) {
      this.refresh = true
      setTimeout(() => {
        this.refresh = false
      }, 500)
      const params = {
        type: this.libCategory,
      }
      PermissionService.getEditPermission(orgId, params).then((res) => {
        const value = res.data
        value.hierarchyManager = JSON.parse(value.hierarchyManager)
        value.moduleEditPermissionList.forEach((item) => {
          item.manager = JSON.parse(item.manager)
        })
        this.values = value
      })
    },
    saveedit() {
      const value = this.values
      value.type = this.libCategory
      if (value.hierarchyManager === null) {
        value.hierarchyManager = JSON.stringify([])
      } else {
        value.hierarchyManager = JSON.stringify(value.hierarchyManager)
      }
      value.moduleEditPermissionList.forEach((item) => {
        if (item.manager === null) {
          item.manager = JSON.stringify([])
        } else {
          item.manager = JSON.stringify(item.manager)
        }
      })
      value.type = this.libCategory
      PermissionService.saveEditPermission(value).then((res) => {
        if (res.data === true) {
          Modal.warning({
            title: '提示',
            content: '保存成功!',
          })
          this.getvalues(this.parentId)
          loginService.getUserPerms()
        } else {
          Modal.warning({
            title: '提示',
            content: '保存失败，请联系管理员!',
          })
        }
        // this.getvalues(this.parentId)
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;

.wrap-height {
  height: 100%;
  .row-height {
    display: flex;
    flex: auto;
    height: 100%;
    .rightcard {
      flex: 1;
      width: calc(100% - 20%);
      height: 100%;
    }
  }
}
.moduletable {
  width: 100%;
  border-top: 1px solid grey;
}
.buttonstyle {
  height: 30px;
  line-height: 30px;
  text-align: center;
  border-top: 1px solid grey;
}
.loading {
  position: fixed;
  top: 310px;
  left: 50%;
  text-align: center;
}
</style>
