<template>
  <div>
    <el-drawer
      size="45%"
      :title="(authId ? '编辑' : '添加') + '资源授权'"
      :visible="dialogVisible"
      :before-close="handleClose"
      :destroy-on-close="true"
      :wrapperClosable="false"
      v-if="dialogVisible"
      custom-class="authorization-dialog-wrap"
    >
      <el-form
        v-form
        data-vv-scope="editFlowAuthForm"
        class="drawer-content"
        label-position="left"
        label-width="100px"
      >
        <el-row type="flex">
          <el-col>
            <el-form-item label="权限描述:" required>
              <ht-input
                v-model="flowAuth.authorizeDesc"
                validate="required"
                :maxlength="200"
                :showWordLimit="true"
                type="textarea"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row type="flex">
          <el-col>
            <el-form-item label="授权人员:" required>
              <div style="margin-bottom: 10px">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-plus"
                  @click="showAuthDialog"
                  >选择人员</el-button
                >
              </div>
              <el-table
                :data="calOwnerNameJson"
                border
                :header-cell-style="{backgroundColor: 'rgba(244,244,244,0.39)'}"
              >
                <el-table-column width="200" prop="title">
                  <template slot="header"> 权限分类 </template>
                </el-table-column>
                <el-table-column prop="name" label="授权给"></el-table-column>
              </el-table>
            </el-form-item>
          </el-col>
        </el-row>

        <div v-for="(model,$index) in authModelList" @click="curClickAuthModel = model; curClickModel = models.filter((m)=> m.key == model.authorizeModel)[0]" :key="$index" style="border: solid 1px #e6e6e6; margin-bottom: 10px;"> 
          <div style="padding: 6px;">
            <span style="color: #333;font-weight: bold;font-size:14px;line-height: 28px;display: inline-block;">授权对象配置</span>
            <el-button style="float: right;" icon="el-icon-delete" v-if="authModelList.length > 1"  @click="authModelList.remove(authModelList[$index])" type="text" size="mini">删除</el-button>
          </div>
          <div style="border-top: solid 1px #e6e6e6; padding: 6px;">
            <el-row type="flex">
            <el-col>
                <el-form-item label="权限对象:" required>
                  <div>
                    <ht-select
                      v-model="model.authorizeModel"
                      :options="models.filter(m=> m.key == model.authorizeModel).concat(canSelectModelMap)"
                      validate="required"
                      :clearable = "false"
                      @change="confirmChange('authorizeModel',model)"
                    />
                  </div>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row type="flex">
              <el-col>
                <el-form-item label="对象类型:" required>
                  <ht-radio
                    v-model="model.multiPle"
                    :options="model.typeOptions"
                    validate="required"
                    v-if="model.authorizeModel"
                    @change="confirmChange('multiPle',model)"
                  ></ht-radio>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row type="flex">
              <el-col>
                <el-form-item
                  :label="model.multiPle == '1'?'授权内容:':'授权内容:'"
                >
                  <div style="margin-bottom: 10px">
                    <el-button
                      v-if="model.multiPle == '2'"
                      type="primary"
                      size="mini"
                      icon="el-icon-plus"
                      @click="showFlowDialog"
                      >选择分类</el-button
                    >
                    <el-select style="width: calc(100% - 200px)" v-if="model.multiPle == '1'" multiple  clearable filterable  v-model="model.tempModelKeys" placeholder="请选择">
                      <el-option
                        v-for="(modelItem,index) in model.modelOptions"
                        :key="index"
                        :label="modelItem.name"
                        :value="modelItem.alias">
                        {{modelItem.name}}({{modelItem.alias}})
                      </el-option>
                    </el-select>
                    <el-button v-if="model.multiPle == '1'"  @click="addAuthModel(model)" type="primary" size="mini">添加</el-button>
                    <el-button v-if="model.multiPle == '1' || model.multiPle == '2'" @click="clearAll(model)" size="mini">清除授权内容</el-button >
                  </div>

                  <el-table
                    :data="model.defNameJson"
                    :header-cell-style="{backgroundColor: 'rgba(244,244,244,0.39)'}"
                    size="mini"
                  >
                    <el-table-column prop="modelName" width="240" :show-overflow-tooltip="true">
                      <template slot="header">授权对象{{model.multiPle == '1'?'名称':(model.multiPle == '2'?'分类':'')}} </template>
                      <template v-slot="{row}"> {{row.modelName}}<span v-if="model.multiPle != '3'" >({{row.modelKey}})</span></template>
                    </el-table-column>
                    <el-table-column label="授权内容">
                      <el-table-column >
                        <template slot="header"> 
                          <el-checkbox v-for="item in modelRightType" :key="item.type" @change="updateAllSelectedAll" v-model='model.batchCheckBoxMap[item.type]' :trueLabel="item.type" :falseLabel='"un_"+item.type' >{{item.desc}}
                            <el-tooltip  class="item" effect="dark" :content="contentMap[item.type]" placement="top-start">
                              <i class="el-icon-info"></i>
                            </el-tooltip>
                          </el-checkbox>
                        </template>
                        <template v-slot="{row, column, $index}">
                          <div class="ffssdd" @click="curEditRow = row">
                            <el-checkbox-group v-model="row.right">
                              <el-checkbox @change="changeRowRight(item.type)"  v-for="item in modelRightType" :key="item.type" :label="item.type">{{item.desc}}</el-checkbox>
                            </el-checkbox-group>
                          </div>
                          
                        </template>
                      </el-table-column>
                    </el-table-column>
                    <el-table-column v-if="model.multiPle != '3'" label="操作" width="80">
                      <template v-slot="{row, column, $index}">
                        <el-button
                          type="text"
                          @click="model.defNameJson.remove(model.defNameJson[$index])"
                          >删除</el-button
                        >
                      </template>
                    </el-table-column>
                  </el-table>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
        <div v-if="authModelList.length < models.length" >
          <el-button style="float: right;" icon="el-icon-plus"  @click="authModelList.push(JSON.parse(JSON.stringify(defaultModel)))" type="primary" >添加</el-button>
        </div>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="dialogCancle('dialogVisible')">{{
          $t('eip.common.cancel')
        }}</el-button>
        <ht-submit-button
          url="${form}/formAuthorize/v1/save"
          :model="flowAuthClone"
          :is-submit="isSubmit"
          :loading="buttonLoading"
          :disabled="buttonDisabled"
          scope-name="editFlowAuthForm"
          @before-save-data="beforeSaveData"
          @after-save-data="afterSaveData"
          >{{ $t('eip.common.save') }}</ht-submit-button
        >
      </div>
    </el-drawer>
    <!-- 选择对话框  -->
    <eip-auth-dialog
      ref="eipAuthDialog"
      name="eipAuthDialog"
      @onConfirm="dialogOnConfirm"
      append-to-body
    />

    <!-- 分类对话框  -->
    <eip-sys-type-dialog
      ref="flowTypeDialog"
      name="flowTypeDialog"
      show-checkbox
      :key="curClickModel.key"
      :type-key="curClickModel.typeKey"
      :cat-id="curClickModel.catId"
      @onConfirm="dialogOnConfirm"
    ></eip-sys-type-dialog>

    <ht-load-data ref="htLoadData"></ht-load-data>
  </div>
</template>
<script>
import req from '@/request.js'
import {Base64} from 'js-base64'
import utils from '@/hotent-ui-util.js'
const eipAuthDialog = () => import('@/components/dialog/EipAuthDialog.vue')
const eipSysTypeDialog = () => import('@/components/dialog/EipSysTypeDialog.vue')
const defaultBatchCheckBoxMap = {'1':'un_1','2':'un_2','3':'un_3','4':'un_4'}
export default {
  components: {
    eipAuthDialog,
    eipSysTypeDialog
  },
  name: 'form-authorize-edit',
  props:['modelRightType','models'],
  data() {
    return {
      dialogVisible: false,
      dialogVisibleMenuPerm: false,
      flowAuth: {
        authorizeTypes: {start: true},
        defNameJson: [],
        multiPle: '1'
      },
      flowAuthClone:{},
      calOwnerNameJson: [],
      defNameJson: [],
      isSubmit: true,
      data: [],
      pageResult: {
        page: 1,
        pageSize: 50,
        total: 0
      },
      authId: '',
      buttonLoading: false,
      buttonDisabled: false,
      contentMap:{'1':"默认所有人可用，配置后只有配置的人可用",'2':"在管理列表展示，可预览导出复制",'3':"可以编辑，包含显示的权限",'4':"可以删除，包含编辑的权限"},
      defaultRight:['2'],
      modelDataMap:{},
      curEditRow:{},
      authModelList:[],
      defaultModel:{multiPle: '1',authorizeModel:"",defNameJson:[],modelOptions:[],typeOptions:[],tempModelKeys:[], oldConfig:{multiPle:"1"},
                    batchCheckBoxMap:JSON.parse(JSON.stringify(defaultBatchCheckBoxMap))},
      curClickAuthModel:{},
      curClickModel:{},
    }
  },
  computed: {
    canSelectModelMap: function() {
      let selectModels = []
      this.authModelList.forEach(m => {
        selectModels.push(m.authorizeModel)
      });
      const models = this.models.filter(m=> selectModels.indexOf(m.key) < 0)
      return models
    },
  },
  methods: {
    loadTypeOptions(model){
      const curModel = this.models.filter((m)=> m.key == model.authorizeModel)[0]
      let options = [{key: '1', value: '对象'},{key: '2', value: '分类'},{key: '3', value: '全部'}]
      if (!curModel.listUrl) {
        options.splice(0,1)
        model.typeOptions = options
        model.multiPle = '2'
        return
      }
      if (!curModel.catId && !curModel.typeKey) {
        options.splice(1,1)
        model.typeOptions = options
        model.multiPle = '1'
        return
      }
      model.typeOptions = options
    },
    loadModelOptions(model){
      const modelKey = model.authorizeModel
       if (!modelKey) {
        model.modelOptions = []
        return 
      }
      if (this.modelDataMap[modelKey]) {
         model.modelOptions =  this.modelDataMap[modelKey]
      }else{
        const curModel = this.models.filter((m)=> m.key == modelKey)[0]
        this.getCurModelOptions(curModel).then(resp=>{
          let data = resp.data.rows || resp.data
          if (curModel.alias || curModel.name) {
            data.forEach(d => {
              if (curModel.alias) {
                d.alias = d[curModel.alias]
              }
              if (curModel.name) {
                d.name = d[curModel.name]
              }
            });
          }
          model.modelOptions = data
          this.$set(this.modelDataMap,modelKey,data)
        })
      }
    },
    addAuthModel(model){
      model.modelOptions.forEach(mo => {
        if (model.tempModelKeys.indexOf(mo.alias) > -1) {
          let isAdd = false
          model.defNameJson.forEach(item => {
            if (!isAdd && item.modelKey == mo.alias) {
              isAdd = true
            }
          })
          if (!isAdd) {
            model.defNameJson.push({
              modelName: mo.name,
              modelKey: mo.alias,
              right: JSON.parse(JSON.stringify(this.defaultRight))
            })
          }
        }
      });
   },
   getCurModelOptions(curModel) {
      let params = {pageBean: {page: 1, pageSize: -1}}

      if (curModel.querys) {
        params.querys = curModel.querys
      }
      return this.$http.post(curModel.listUrl,params)
    },
    confirmChange(attr,model){
      if (attr == 'authorizeModel') {
        this.loadModelOptions(model)
        this.loadTypeOptions(model)
      }
     if (!model.defNameJson || model.defNameJson.length == 0) {
       model.oldConfig[attr] = model[attr]
       if (model.multiPle==3) {
          model.defNameJson.push({ modelName: '全部', modelKey: '-1',right: JSON.parse(JSON.stringify(this.defaultRight))})
        }
       this.tempModelKeys = []
       return
     }
     this.$confirm('切换对象会清除授权内容，是否确认操作?', '提示', {
        type: 'warning',
        closeOnClickModal: false,
      })
        .then(() => {
          model.defNameJson = []
          if (model.multiPle==3) {
            model.defNameJson.push({ modelName: '全部', modelKey: '-1',right: JSON.parse(JSON.stringify(this.defaultRight))})
          }
          
          model.tempModelKeys = []
        })
        .catch(() => {
           model[attr] = model.oldConfig[attr]
        })
    },

    showDialog(id) {
      this.tempModelKeys = []
      this.authModelList = []
      this.batchCheckBoxMap = {'1':'un_1','2':'un_2','3':'un_3','4':'un_4'}
      const me = this
      if (id) {
        this.authId = id
        this.$refs.htLoadData
          .loadData('${form}/formAuthorize/v1/getDetail?id=' + id)
          .then(data => {
            data = data.value
            me.flowAuth = data
            let defNameJson = JSON.parse(data.authModelJson)
            // right 转为对象
            defNameJson.forEach(item => {
              item.right = item.rightContent.split(',')
            })
            data.authorizeModel.split(',').forEach(m=>{
              let model = JSON.parse(JSON.stringify(this.defaultModel));
              const defNames = defNameJson.filter(j=> j.modelType == m)
              model.defNameJson = defNames
              model.authorizeModel = m
              model.multiPle = defNames[0]&&defNames[0].type
              this.loadModelOptions(model)
              this.loadTypeOptions(model)
              this.authModelList.push(model)
            })
            me.defNameJson = defNameJson
            me.calOwnerNameJson = JSON.parse(data.authUserJson)
            this.dialogVisible = true
          })
      } else {
        this.authModelList.push(JSON.parse(JSON.stringify(this.defaultModel)))
        this.authId = ''
        me.flowAuth = {
          authorizeTypes: {start: true},
          defNameJson: [],
          multiPle: '1'
        }
        me.calOwnerNameJson = []
        this.dialogVisible = true
      }
    },
    dialogCancle(dialogVisible) {
      this[dialogVisible] = false
      this.$emit('onConfirm', false)
    },
   
    updateAllSelectedAll(oValue) {
      let selected = true
      let relRight = []
      if (oValue.indexOf('un_') != -1) {
        selected = false
      }
      if (oValue.replace('un_','') == '4') {
        if (selected) {
          this.curClickAuthModel.batchCheckBoxMap['2'] = '2'
          this.curClickAuthModel.batchCheckBoxMap['3'] = '3'
          relRight = ['2','3','4']
        }else{
          relRight = ['4']
        }
        
      }else if (oValue.replace('un_','') == '3') {
        if (selected) {
          this.curClickAuthModel.batchCheckBoxMap['2'] = '2'
          relRight = ['2','3']
        }else{
          this.curClickAuthModel.batchCheckBoxMap['4'] = 'un_4'
          relRight = ['3','4']
        }
      }else if (oValue.replace('un_','') == '2') {
        if (selected) {
          relRight = ['2']
        }else{
          this.curClickAuthModel.batchCheckBoxMap['3'] = 'un_3'
          this.curClickAuthModel.batchCheckBoxMap['4'] = 'un_4'
          relRight = ['2','3','4']
        }
      }else  {
        relRight.push(oValue.replace('un_',''))
      }

      this.curClickAuthModel.defNameJson.forEach(item => {
        item.right = item.right || []
        relRight.forEach(r => {
          if (selected && item.right.indexOf(r) < 0) {
            item.right.push(r)
          }else if (!selected) {
            item.right.remove(r)
          }
        });
      })
    },
    changeRowRight(right){
      let selected = this.curEditRow.right.indexOf(right) > -1
      if (right == '4') {
        if (selected) {
          this.pushIfNotExist('2')
          this.pushIfNotExist('3')
        }
      }else if (right == '3') {
        if (selected) {
          this.pushIfNotExist('2')
        }else{
          this.curEditRow.right.remove('4')
        }
      }else if (right == '2') {
        if (!selected) {
          this.curEditRow.right.remove('4')
          this.curEditRow.right.remove('3')
        }
      }
    },
    pushIfNotExist(right){
      if(this.curEditRow.right.indexOf(right) < 0) {
         this.curEditRow.right.push(right) 
      }
    },
    showAuthDialog() {
      let conf = {
        right: [],
        permissionList: [
          {type: 'everyone', title: '所有人'},
          {type: 'user', title: '用户'},
          {type: 'org', title: '组织'},
          {type: 'pos', title: '岗位'},
          {type: 'role', title: '角色'}
          // ,{ type: "none", title: "无" }
        ]
      }
      if (this.calOwnerNameJson) {
        conf.right = this.calOwnerNameJson
      }
      this.$refs.eipAuthDialog.showDialog(conf)
    },
    dialogOnConfirm(data, name) {
      if (name == 'eipAuthDialog') {
        this.calOwnerNameJson = data
      }

      if (name == 'flowTypeDialog') {
        data.forEach(element => {
          if (element.parentId == '0') {
            return
          }
          let isEquals = false
          this.curClickAuthModel.defNameJson.forEach(item => {
            if (!isEquals && item.modelKey == element.id) {
              isEquals = true
            }
          })

          if (!isEquals) {
            this.curClickAuthModel.defNameJson.push({
              modelName: element.name,
              modelKey: element.id,
              right: JSON.parse(JSON.stringify(this.defaultRight))
            })
          }
        })
      }
    },
    showFlowDialog() {
      if (!this.curClickAuthModel.authorizeModel) {
        this.$message.error('请先选择权限对象')
        return
      }
      let this_ = this
      setTimeout(() => {
        this_.$refs.flowTypeDialog.showDialog()
      }, 100);
    },
    async beforeSaveData() {
      this.isSubmit = true
      this.buttonLoading = true
      this.buttonDisabled = true

      if (this.calOwnerNameJson.length == 0) {
        this.$message.error('请选择授权人员')
        this.isSubmit = false
        this.buttonLoading = false
        this.buttonDisabled = false
        return
      }

      if (this.authModelList.length == 0) {
        this.$message.error('请选择授权内容')
        this.isSubmit = false
        this.buttonLoading = false
        this.buttonDisabled = false
        return
      }
      const defNameJson = []
      const athModels = []
      this.authModelList.forEach(auth => {
        athModels.push(auth.authorizeModel)
        auth.defNameJson.forEach(d=>{
          d.modelType = auth.authorizeModel
          d.type = auth.multiPle
          defNameJson.push(d)
        })
      });
      let pass = true
      defNameJson.forEach(d => {
        if (!d.right || d.right.length == 0) {
          pass = false
        }else{
          let hasRiht = false
          d.right.forEach(r => {
            if (r) {
              hasRiht = true
            }
          });
          if (!hasRiht) {
             pass = false
          }
        }
      });

      if (!pass) {
        this.$message.error('请选择授权内容')
        this.isSubmit = false
        this.buttonLoading = false
        this.buttonDisabled = false
        return
      }

      this.flowAuth.authUserJson = JSON.stringify(this.calOwnerNameJson)
      this.flowAuth.authModelJson = JSON.stringify(defNameJson)
      this.flowAuth.authorizeModel = athModels.join()
      this.flowAuthClone =  _.cloneDeep(this.flowAuth)
      delete this.flowAuthClone.authorizeTypes
      delete this.flowAuthClone.defNameJson
    },
    afterSaveData() {
      this.dialogVisible = false
      this.$emit('onConfirm', true)
      setTimeout(() => {
        this.buttonLoading = false
        this.buttonDisabled = false
      }, 1000)
    },
    handleClose() {
      this.dialogVisible = false
      this.$emit('onConfirm', false)
    },
    clearAll(model) {
      this.$confirm('确认删除下面的授权内容吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          model.defNameJson = []
          model.batchCheckBoxMap = JSON.parse(JSON.stringify(defaultBatchCheckBoxMap))
          this.$message({
            type: 'success',
            message: '清除成功'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消清除'
          })
        })
    }
  }
}
</script>

<style lang="scss" scoped>
div[aria-invalid='true'] >>> .el-input__inner,
div[aria-invalid='true'] >>> .el-input__inner:focus {
  border-color: #f56c6c;
}
.second-checkbox {
  margin-left: 48px;
}
/deep/.header-span {
  margin-left: -28px;
}
/deep/.instance-span {
  margin-left: 60px;
  margin-right: 3px;
}
/deep/.last-brackets-span {
  margin-right: 24px;
  margin-left: -28px;
}
/deep/.el-dialog__wrapper {
  overflow: unset !important;
}
/deep/.el-dialog__body {
  height: calc(100% - 170px);
  overflow-y: auto;
}
/deep/.el-dialog {
  height: 90%;
  min-height: 400px;
  margin-top: 3vh !important;
}
/deep/.el-dialog__body .selector-table {
  height: 100% !important;
}
/deep/.el-dialog .el-dialog__body .select-tree-div {
  height: calc(100% - 60px);
  min-height: unset;
}
@media (max-height: 960px) {
  /deep/.el-dialog__body .el-container {
    height: 100% !important;
  }
}
::v-deep .el-drawer__body {
  position: relative;
  padding: 20px 10px 20px 20px;
  border-top: 1px solid #dcdee0;
}
.drawer-content {
  height: calc(100% - 48px);
  overflow-x: hidden;
  .el-table {
    width: calc(100% - 10px);;
  }
}
::v-deep .el-checkbox {
  margin-right: 7px;
}
.process-example {
  margin-left: 59px;
}
.dialog-footer {
  text-align: right;
  line-height: 48px;
}
::v-deep .el-textarea__inner {
  resize: both;
  max-width: 700px;
}
.inputs.ht-form-inputs__inline {
  width: 100%;
}
::v-deep .el-form-item__label {
  color: #888888;
}

::v-deep .el-form-item--small {
  margin-bottom: 10px;
}

</style>
