<template>
  <h-modal
    id="SearchAuth-queryModal"
    v-model:visible="visible"
    :title="t('queryConfiguration.common.dataPerTitle')"
    :cancelText="t('platform.common.cancel')"
    :okText="t('platform.common.save')"
    width="1050px"
    wrap-class-name="full-modal"
    :destroyOnClose="true"
    :maskClosable="false"
    @ok="handlePermissionOk"
    @cancel="handlePermissionCancel"
  >
    <div>
      <h-row class="table-title-margin app-custom-edit-form-header">
        <h-col :span="8">{{ t('queryConfiguration.permission.objectType') }}</h-col>
        <h-col :span="12" style="padding-left: 10px">
          {{ t('queryConfiguration.permission.object') }}
        </h-col>
      </h-row>
      <h-row class="app-custom-edit-form-body">
        <h-col :span="8" style="padding-left: 15px">通用查询配置</h-col>
        <h-col :span="12" style="padding-left: 15px">{{ perObjectInfo.ENAME }}</h-col>
      </h-row>
      <h-divider />
      <h-row class="table-title-margin app-custom-edit-form-header">
        <h-col :span="5">{{ t('queryConfiguration.permission.subjectType') }}</h-col>
        <h-col :span="9" style="padding-left: 10px">
          {{ t('queryConfiguration.permission.subject') }}
        </h-col>
        <h-col :span="5" style="padding-left: 10px">
          {{ t('queryConfiguration.permission.operator') }}
        </h-col>
        <h-col :span="2" class="app-custom-edit-form-operation">
          {{ t('platform.common.operate') }}
        </h-col>
      </h-row>
      <h-form
        class="app-custom-edit-form-body"
        ref="formRefSubject"
        name="dynamic_form_nest_item"
        :model="perSubjectSetListForm"
      >
        <h-row v-for="(item, index) in perSubjectSetListForm" :key="index">
          <h-col :span="5">
            <h-form-item
              label=""
              :name="[index, 'perSubjectType']"
              :rules="{
                required: true,
                message: t('queryConfiguration.common.permissionObjectType'),
                trigger: ['change', 'blur'],
              }"
            >
              <h-select
                v-model:value="item.perSubjectType"
                :options="perSubjectTypeList"
                :placeholder="t('queryConfiguration.common.selectPlaceholder')"
                @select="
                  (value, option) => {
                    selectPerSubjectType(index, value, option);
                  }
                "
              ></h-select>
            </h-form-item>
          </h-col>
          <h-col :span="9">
            <h-form-item
              label=""
              :name="[index, 'perSubjectSet']"
              :rules="{
                required: true,
                message: t('queryConfiguration.common.permissionObjectSet'),
                trigger: ['change', 'blur'],
              }"
            >
              <h-select
                v-model:value="item.perSubjectSet"
                :options="item.perSubjectOption"
                :placeholder="t('queryConfiguration.common.selectPlaceholder')"
                @dropdownVisibleChange="
                  open => {
                    dropdownVisibleChange(open, index);
                  }
                "
                :open="false"
              ></h-select>
            </h-form-item>
          </h-col>
          <h-col :span="5">
            <h-form-item
              :name="[index, 'view_auth']"
              :rules="{
                required: true,
                message: t('queryConfiguration.common.permissionOperator'),
                trigger: ['change', 'blur'],
              }"
            >
              <h-b-select
                v-model:value="item.view_auth"
                :options="viewAuthOptions"
                :placeholder="t('queryConfiguration.common.selectPlaceholder')"
                @select="
                  (value, option) => {
                    selectViewAuth(index, value);
                  }
                "
              ></h-b-select>
            </h-form-item>
          </h-col>
          <h-col :span="2" class="app-custom-edit-form-operation">
            <h-form-item>
              <h-popconfirm
                :title="t('queryConfiguration.configCreate.queryConditions.deleteConfirm')"
                placement="topLeft"
                @confirm="removePerSubjectSet(index)"
              >
                <a>{{ t('queryConfiguration.configCreate.queryConditions.delete') }}</a>
              </h-popconfirm>
            </h-form-item>
          </h-col>
        </h-row>
        <h-form-item>
          <h-button type="dashed" block @click="addPerSubjectSet">
            <plus-outlined />
            {{ t('platform.common.add') }}
          </h-button>
        </h-form-item>
      </h-form>
    </div>
    <h-modal
      ref="perSubjectSet"
      id="PerSubjectSet-queryModal"
      v-model:visible="perVisible"
      :title="perSubjectSetTitle"
      :cancelText="t('platform.common.cancel')"
      :okText="t('platform.common.ok')"
      width="1050px"
      wrap-class-name="full-modal"
      :destroyOnClose="true"
      @ok="perSubjectSetHandleOk"
    >
      <permission-pllicy-content
        ref="componentRef"
        :modalParam="modalParam"
        id="AdminMember-queryTransfer"
        @changeAuthVal="changeViewAuthVal"
      />
    </h-modal>
  </h-modal>
</template>
<script lang="ts">
import { defineComponent, ref, reactive, computed, nextTick, onBeforeMount } from 'vue';
import { HModal, message } from '@crami/ui';
import { useHttp } from '@crami/http';
import { useI18n } from '@crami/locale';
/* import { getInfo, ICP_CONFIG } from '@/utils/commMethods'; */
import { getInfo, ICP_CONFIG } from '@remote/icpx-platform/utils';
//import PermissionObject from './PermissionObject.vue';
import PermissionPllicyContent from './PermissionPllicyContent.vue';

export default defineComponent({
  name: 'SearchAuthModel',
  components: { HModal, PermissionPllicyContent },
  emits: ['searchAuthModelFunSuccess'],
  setup(_, { emit }) {
    const { t } = useI18n();

    // 授权主体 Subject  授权客体 Object
    let perObjectInfo = ref({ EID: '', ENAME: '' }); // 授权客体信息
    const visible = ref(false);
    const perVisible = ref(false);
    const visibleModal = ref(false);
    const perSubjectSetTitle = ref('');
    const perSubjectSetList: any = ref([]); // 主体授权配置
    const perSubjectTypeList: any = ref([]); // 授权主体类型列表
    // const perSubjectSetListItem = reactive({
    //   permissionID: '',
    //   perSubjectType: '',
    //   perSubjectTypeLabel: '',
    //   perSubjectSet: '',
    //   perSubjectSetLabel: '',
    // });
    const perSubjectSetListForm = ref<Array<any>>([
      {
        permissionID: '',
        perSubjectType: '',
        perSubjectTypeLabel: '',
        perSubjectSet: '',
        perSubjectSetLabel: '',
        perSubjectOption: [],
        view_auth: '1',
      },
    ]);
    const viewAuthOptions = [
      { label: '授予', value: '1' },
      { label: '拒绝', value: '2' },
    ];
    let currentMainExtend: any = reactive({});
    let current_view_auth = ref('1');
    const show = data => {
      visible.value = true;
      perObjectInfo.value.EID = data.EID;
      perObjectInfo.value.ENAME = data.ENAME;
      nextTick(() => {
        //getDataPerObjectPluginItems();
        getObjectPermissionList();
      });
    };

    // 根据客体对象获取主体对象列表
    const getObjectPermissionList = async () => {
      const result = await useHttp({
        url: '/api/dataperservice/dataPerService/getObjPermissionList',
        method: 'post',
        params: {
          viewName: 'P_SYS_OBJPERMISSION_LISTVIEW',
          page: 1,
          pagSize: 50,
          pageNo: 1,
          connect: getInfo(ICP_CONFIG)?.connect,
          lang: getInfo(ICP_CONFIG)?.lang,
          companyId: getInfo(ICP_CONFIG)?.companyId,
          filter: [
            { field: 'PERTYPE', value: '2', operation: '=', andOrFlag: 'AND' },
            {
              field: 'PEROBJECT',
              value: perObjectInfo.value.EID,
              operation: '=',
              andOrFlag: 'AND',
            },
          ],
        },
      });
      console.log('getObjectPermissionList:' + result);
      if (result.code == '200' && result?.data?.data.length > 0) {
        perSubjectSetListForm.value.length = 0;
        let view_auth_map = new Map();
        result.data.rows.forEach(itemW => {
          let view_auth_key = '',
            view_auth_val = '',
            operator_val = '';
          itemW.forEach(item => {
            if (item.colName == 'EID') {
              view_auth_key = item.colValue;
            }

            if (item.colName == 'PERMISSIONS') {
              let valArr = JSON.parse(item.colValue.replaceAll("'", '"'));
              valArr.forEach(itemI => {
                if (typeof itemI.BROWSE === 'string') {
                  view_auth_val = itemI.BROWSE;
                }
              });
              if (typeof item.colText === 'string') {
                let tempArr = item.colText.split(';');
                if (tempArr.length > 0) {
                  tempArr.forEach(aItem => {
                    if (aItem.indexOf('浏览') == 0) {
                      operator_val = aItem;
                      return;
                    }
                  });
                }
              }
            }
          });
          view_auth_map.set(view_auth_key, { view_auth: view_auth_val, operator: operator_val });
        });

        result.data.data.map((item, index) => {
          let permissionObj = {
            permissionID: item.EID,
            perSubjectType: '',
            perSubjectTypeLabel: '',
            perSubjectSet: '',
            perSubjectSetLabel: '',
            view_auth: '1',
            operator: '',
          };
          permissionObj.view_auth = view_auth_map.get(item.EID)?.view_auth;
          current_view_auth.value = view_auth_map.get(item.EID)?.view_auth;
          permissionObj.operator = view_auth_map.get(item.EID)?.operator;
          perSubjectSetListForm.value.push(permissionObj);
          getOneDatPerDetail(item.EID, index);
        });

        //deleteDataPer(result.data.data[0].EID);
      }
      //params?.length && initData(params);
    };

    const getOneDatPerDetail = async (objectID, index) => {
      const result = await useHttp({
        url: '/api/dataperservice/dataPerService/getOneDataPer',
        method: 'post',
        params: {
          connect: getInfo(ICP_CONFIG)?.connect,
          lang: getInfo(ICP_CONFIG)?.lang,
          companyId: getInfo(ICP_CONFIG)?.companyId,
          objectId: objectID,
        },
      });
      console.log('getOneDatPerDetail:' + result);
      if (result.code == '200') {
        perSubjectSetListForm.value[index].perSubjectType =
          result.data.dataPerSubjectVO.subjectType;
        perSubjectSetListForm.value[index].perSubjectSet = result.data.dataPerSubjectVO.subjectEid;
        perSubjectSetListForm.value[index].perSubjectSetLabel =
          result.data.dataPerSubjectVO.subjectLabel;
        //根据id获取显示值，设置授权主体的值，并设置下啦数据源的内容
        const params = {
          connect: getInfo(ICP_CONFIG)?.connect,
          lang: getInfo(ICP_CONFIG)?.lang,
          value: perSubjectSetListForm.value[index].perSubjectSet,
          pluginName: perSubjectSetListForm.value[index].perSubjectType,
          companyId: getInfo(ICP_CONFIG)?.companyId,
        };
        getMainContentData(params).then(result => {
          console.log(params);
          if (result.code == 200) {
            perSubjectSetListForm.value[index].perSubjectOption = result.data;
          }
        });
      }
    };

    // 获取主体授权类型列表
    const getPerSubjectTypeList = async () => {
      const data = await useHttp({
        url: '/api/dataperservice/dataPerService/getDataPerSubjectPluginItems',
        method: 'post',
        params: {
          lang: getInfo(ICP_CONFIG)?.lang,
        },
      });
      perSubjectTypeList.value = [].concat(data?.data).filter(item => {
        if (['PSDS_DEPT', 'PSDS_ROLE', 'PSDS_GROUP', 'PSDS_USER'].includes(item.value)) return item;
      });
      console.log('perSubjectType:' + perSubjectTypeList.value);
    };

    const selectPerSubjectType = (index, value, option) => {
      perSubjectSetListForm.value[index].perSubjectType = value;
      // 根据value获取extend
      let etr = perSubjectTypeList.value.find(item => {
        return item.value === value;
      });
      var evalFun = new Function('return ' + etr.extend);
      perSubjectSetListForm.value[index].perSubjectTypeLabel = etr.extend.label;
      const extend = evalFun();
      currentMainExtend = extend;
      //根据extend的type
      if (extend.type == 'static') {
        getPerSubjectData(value);
      }
      if (extend.type == 'select') {
        console.log(extend.type);
      }
      if (extend.type == 'pop') {
        //调用方法，1.请空置 2.并且可点击 3.清空下拉数据源
        beforeHandlePop();
      }
      perSubjectSetListForm.value[index].perSubjectSet = '';
      perSubjectSetListForm.value[index].perSubjectSetLabel = '';
    };

    const selectViewAuth = (index, value) => {
      perSubjectSetListForm.value[index].view_auth = value;
    };

    const beforeHandlePop = () => {
      console.log('beforeHandlePop');
    };

    //授权主体内容
    const getPerSubjectData = subjectEID => {
      const params = {
        connect: getInfo(ICP_CONFIG)?.connect,
        lang: getInfo(ICP_CONFIG)?.lang,
        value: getInfo(ICP_CONFIG)?.companyId,
        // pluginName: subjectEid.value,
        pluginName: subjectEID,
        companyId: getInfo(ICP_CONFIG)?.companyId,
      };
      getMainContentData(params).then(result => {
        if (result.code == 200) {
          console.log(result);
        }
      });
    };
    const getMainContentData = async (params: any) => {
      const data = await useHttp({
        url: '/api/dataperservice/dataPerService/getSubjectDisplayText',
        method: 'post',
        params: params,
      });
      return data;
    };

    const formRefSubject = ref();

    const hiddenDelete = computed(() => {
      return { display: perSubjectSetListForm.value.length <= 1 ? 'none' : 'block' };
    });

    const removePerSubjectSet = (index: number) => {
      // if (perSubjectSetListForm.attr.length == 1) {
      //   return;
      // }
      //currentMainExtend.value?.splice(index, 1);
      const item = perSubjectSetListForm.value[index];
      if (item.permissionID && item.permissionID != '') {
        deletePermission(item.permissionID, index);
      } else {
        perSubjectSetListForm.value.splice(index, 1);
      }
    };

    const addPerSubjectSet = async () => {
      perSubjectSetListForm.value.push({});
    };

    const handlePermissionCancel = () => {
      visible.value = false;
      perSubjectSetListForm.value.length = 0;
    };

    const perSubjectSetIndex = ref(0); // PerSubjectSet
    //
    const dropdownVisibleChange = (open, index) => {
      if (open) {
        perSubjectSetIndex.value = index;
        getCurrentMainExtend(index);
        current_view_auth.value = perSubjectSetListForm.value[index].view_auth;
        if (currentMainExtend.value?.type == 'select') {
          return;
        }
        if (currentMainExtend?.value?.type == 'pop') {
          handlePop(
            currentMainExtend.value,
            perSubjectSetListForm.value[index].perSubjectSet,
            perSubjectSetListForm.value[index].view_auth || '1',
          );
        }
      }
    };

    const getCurrentMainExtend = index => {
      const perSubjectType = perSubjectSetListForm.value[index].perSubjectType;
      const current: any = perSubjectTypeList.value.find(item => item.value == perSubjectType);
      if (current?.extend) {
        var evalFun = new Function('return ' + current.extend);
        const extend = evalFun();
        currentMainExtend.value = extend;
      } else {
        currentMainExtend.value = [];
      }
    };

    //给弹窗传递参数：
    const modalParam = reactive({
      params: {},
      data: {},
    });

    const handlePop = (currentMainExtend, subjectVal, operatorVal) => {
      modalParam.params = currentMainExtend;
      let subjectArr = [];
      if (typeof subjectVal !== 'undefined' && subjectVal !== '') {
        //根据id获取显示值，设置授权主体的值，并设置下啦数据源的内容
        const params = {
          connect: getInfo(ICP_CONFIG)?.connect,
          lang: getInfo(ICP_CONFIG)?.lang,
          value: subjectVal,
          pluginName: perSubjectSetListForm.value[perSubjectSetIndex.value].perSubjectType,
          companyId: getInfo(ICP_CONFIG)?.companyId,
        };
        getMainContentData(params).then(result => {
          console.log(params);
          if (result.code == 200) {
            let valArr = result.data[0].value.split(';');
            let labelArr = result.data[0].label.split(';');
            for (let idx = 0; idx < labelArr.length; idx++) {
              subjectArr.push({ value: valArr[idx], label: labelArr[idx] });
            }
            modalParam.data = { subject: subjectArr, operator: operatorVal };
            perSubjectSetTitle.value = currentMainExtend.attr.title;
            // 打开弹窗
            openPerSubjectSetModal();
          }
        });
      } else {
        modalParam.data = { subject: subjectArr, operator: operatorVal };
        perSubjectSetTitle.value = currentMainExtend.attr.title;
        // 打开弹窗
        openPerSubjectSetModal();
      }
    };

    const openPerSubjectSetModal = () => {
      perVisible.value = true;
    };

    //数据获取部分
    const componentRef = ref({});

    const savePermission = async perSubjectSet => {
      console.log('view_auth:' + current_view_auth.value);
      let params = {
        connect: getInfo(ICP_CONFIG)?.connect,
        lang: getInfo(ICP_CONFIG)?.lang,
        companyId: getInfo(ICP_CONFIG)?.companyId,
        objectId: perSubjectSet.permissionID,
        dataPermissionVO: {
          perType: '2',
          permissions:
            "[{'CREATE':'1'},{'BROWSE':'" +
            perSubjectSet.view_auth +
            "'},{'EDIT':'1'},{'DELETE':'1'},{'DOWNLOAD':'2'},{'PERMISSION':'2'},{'PASTE':'2'},{'COPY':'2'},{'PRINT':'2'}]",
        },
        dataPerSubjectVO: {
          subjectType: perSubjectSet.perSubjectType,
          subjectEid: perSubjectSet.perSubjectSet,
          EID: '',
          subjectTypeLabel: perSubjectSet.perSubjectTypeLabel,
          subjectLabel: perSubjectSet.perSubjectSetLabel,
        },
        dataPerObjectVO: {
          objectType: 'P_COMMON_QUERY_CONFIG',
          objectEid: [
            {
              field: 'EID',
              operation: '==',
              value: perObjectInfo.value.EID,
              andOrFlag: 'AND',
            },
          ],
        },
      };
      const data = await useHttp({
        url: '/api/dataperservice/dataPerService/saveObjPer',
        method: 'post',
        params: params,
      });
      if (data.code == 200) {
      } else {
        message.warning(data.msg);
      }
    };

    const deletePermission = async (objectID, index) => {
      const result = await useHttp({
        url: '/api/dataperservice/dataPerService/deleteDataPer',
        method: 'post',
        params: {
          connect: getInfo(ICP_CONFIG)?.connect,
          lang: getInfo(ICP_CONFIG)?.lang,
          companyId: getInfo(ICP_CONFIG)?.companyId,
          eidStrs: [objectID],
        },
      });
      if (result.code == 200) {
        perSubjectSetListForm.value.splice(index, 1);
        emit('searchAuthModelFunSuccess');
      } else {
        message.warning(result.msg);
      }
    };

    const handlePermissionOk = () => {
      if (perSubjectSetListForm.value.length > 0) {
        const countMap = new Map();
        let repeating = false;
        perSubjectSetListForm.value.forEach(item => {
          let tempKey = item.perSubjectType + '_' + item.perSubjectSet;
          if (countMap.get(tempKey) === 1) {
            message.error(t('queryConfiguration.common.repeatingDataPer'));
            repeating = true;
            return;
          } else {
            countMap.set(tempKey, 1);
          }
        });
        if (repeating) return;
        formRefSubject.value
          .validate()
          .then(() => {
            Promise.all(
              perSubjectSetListForm.value.map(item => {
                return savePermission(item);
              }),
            )
              .then(() => {
                emit('searchAuthModelFunSuccess');
                visible.value = false;
              })
              .catch(() => {});
          })
          .catch(errorInfo => {
            console.log('校验失败:', errorInfo);
          });
      } else {
        emit('searchAuthModelFunSuccess');
        visible.value = false;
      }
    };
    const perSubjectSetHandleOk = init => {
      let idList = '';
      if (init === 'init') {
        console.log('init');
        //subjectType.value = props.dataPerSubjectVO.subjectType;
        //idList = props.dataPerSubjectVO.subjectEid || '';
      } else {
        const list = (componentRef.value as any).getTableData();
        if (list?.length > 50) {
          message.warning(t('permission.common.selectMaxLen'));
          return;
        }
        for (let selectItem of list) {
          idList = idList + selectItem.value + ';';
        }
        if (idList !== '') {
          if (idList[idList.length - 1] == ';') {
            idList = idList.substring(0, idList.length - 1);
          }
          //根据id获取显示值，设置授权主体的值，并设置下啦数据源的内容
          const params = {
            connect: getInfo(ICP_CONFIG)?.connect,
            lang: getInfo(ICP_CONFIG)?.lang,
            value: idList,
            pluginName: perSubjectSetListForm.value[perSubjectSetIndex.value].perSubjectType,
            companyId: getInfo(ICP_CONFIG)?.companyId,
          };
          getMainContentData(params).then(result => {
            console.log(params);
            if (result.code == 200) {
              perSubjectSetListForm.value[perSubjectSetIndex.value].perSubjectOption = result.data;
            }
          });
        }

        perSubjectSetListForm.value[perSubjectSetIndex.value].perSubjectSet = idList;
        console.log('idList:' + idList);
        perVisible.value = false;
      }
    };

    const changeViewAuthVal = e => {
      console.log('changeViewAuthVal:' + e);
      current_view_auth.value = e;
      perSubjectSetListForm.value[perSubjectSetIndex.value].view_auth = e;
    };
    onBeforeMount(() => {
      getPerSubjectTypeList();
    });

    return {
      t,
      handlePermissionOk,
      visible,
      perVisible,
      show,
      perSubjectSetListForm,
      hiddenDelete,
      removePerSubjectSet,
      addPerSubjectSet,
      formRefSubject,
      handlePermissionCancel,
      dropdownVisibleChange,
      visibleModal,
      perSubjectSetTitle,
      modalParam,
      componentRef,
      perObjectInfo,
      perSubjectTypeList,
      selectPerSubjectType,
      getPerSubjectTypeList,
      getPerSubjectData,
      perSubjectSetList,
      currentMainExtend,
      perSubjectSetHandleOk,
      current_view_auth,
      changeViewAuthVal,
      viewAuthOptions,
      selectViewAuth,
    };
  },
});
</script>
<style lang="less" scoped>
@import '@/theme/default/variables.less';

.platform-perssionsub-title {
  font-size: 16px;
  font-weight: bold;
  &::before {
    content: '';
    width: 4px;
    height: 12px;
    background: @modal-formgroup-color;
    margin-right: 5px;
    display: inline-block;
  }
}
.exclamation-icon {
  color: @normal-color;
  margin-left: 4px;
  &:hover {
    color: @info-color;
  }
}
.desc {
  color: @normal-color;
}
.table-title-margin {
  margin-bottom: 10px;
}
.create-renant-admin-useinfo-title {
  font-weight: bold;
  height: 36px;
  line-height: 35px;
  font-size: 14px;
}
</style>
