<template>
  <div class="main-content-padding margin-bottom">
    <!-- 基本信息 -->
    <h-card
      class="margin-bottom list-query-form list-form-has-card-head"
      :title="t('permission.dataPermissionPolicy.dataPermissionPolicy.baseInfo')"
    >
      <h-b-form ref="formRef" name="use" v-bind="props" :is-query="false"></h-b-form>
    </h-card>
    <!-- 授权主体 -->
    <h-card class="margin-bottom list-query-form list-form-has-card-head">
      <template #title>
        {{ t('permission.common.authorizedBody') }}
        <h-tooltip placement="right">
          <template #title>
            <p
              v-html="t('permission.dataPermissionPolicy.dataPermissionPolicy.authorizedBodyTip')"
            ></p>
          </template>
          <ExclamationCircleOutlined class="exclamation-icon" />
        </h-tooltip>
      </template>
      <h-b-form ref="formRefMain" name="main" v-bind="propsMain" :is-query="false"></h-b-form>
    </h-card>
    <!-- 授权客体 -->
    <h-card class="margin-bottom list-query-form list-form-has-card-head">
      <template #title>
        {{ t('permission.common.authorizedObject') }}
        <h-tooltip placement="right">
          <template #title>
            <p
              v-html="t('permission.dataPermissionPolicy.dataPermissionPolicy.authorizedObjectTip')"
            ></p>
          </template>
          <ExclamationCircleOutlined class="exclamation-icon" />
        </h-tooltip>
      </template>
      <h-b-form ref="formRefSub" name="sub" v-bind="propsSub" :is-query="false"></h-b-form>
    </h-card>
    <!-- 权限配置 -->
    <h-card class="margin-bottom list-table list-table-has-card-head">
      <template #title>
        {{ t('permission.common.authorizationConfig') }}
        <h-tooltip placement="right">
          <template #title>
            <p
              v-html="
                t('permission.dataPermissionPolicy.dataPermissionPolicy.authorizationConfigTip')
              "
            ></p>
          </template>
          <ExclamationCircleOutlined class="exclamation-icon" />
        </h-tooltip>
      </template>
      <h-table
        :data-source="list"
        :columns="columns"
        row-key="key"
        :bordered="true"
        :pagination="false"
        size="small"
      >
        <template #bodyCell="{ record, index, column, text }">
          <template v-if="['allow', 'reject', 'other'].includes(column.dataIndex)">
            <h-radio
              :checked="record.checkStatus === text"
              :value="text"
              :disabled="_.disabled"
              @change="handleChange(index, text)"
            />
          </template>
          <template v-else>
            {{ record.value }}
          </template>
        </template>
      </h-table>
    </h-card>
    <!-- 取消保存按钮实现 -->
    <div v-if="!_.disabled" class="permission-pllicy-btn">
      <h-button :loading="loading" @click="cancelPage">{{ t('platform.common.cancel') }}</h-button>
      <h-button :loading="loading" type="primary" @click="savePermissionData">
        {{ t('platform.common.save') }}
      </h-button>
    </div>
    <div v-if="_.disabled" class="permission-pllicy-btn">
      <h-button type="primary" @click="closePage">{{ t('platform.common.close') }}</h-button>
    </div>

    <h-modal
      ref="mainModal"
      id="AdminMember-queryModal"
      v-model:visible="visible"
      :title="mainModalTitle"
      cancelText="取消"
      okText="保存"
      width="1250px"
      wrap-class-name="full-modal"
      :destroyOnClose="true"
      @ok="handleOk"
    >
      <permission-pllicy-content
        ref="componentRef"
        width="800px"
        :modalParam="modalParam"
        id="AdminMember-queryTransfer"
      />
    </h-modal>
    <permission-sub ref="permissionSubRef" @permissionSubFunSuccess="permissionSubFunSuccess" />
    <!-- 授权客体类型 -->
    <permission-sub-type
      ref="permissionSubTypeRef"
      @permissionSubTypeFunSuccess="permissionSubTypeFunSuccess"
    />
  </div>
</template>

<script lang="ts">
import { useForm } from '@crami/bui-platform';
import { defineComponent, ref, reactive, onMounted, watch, nextTick } from 'vue';
import { HModal, message } from '@crami/ui';
// import { IModalPageParams } from '@crami/ui-types';
import { getInfo, ICP_CONFIG, bus } from '@remote/icpx-platform/utils';
/* import { getInfo, ICP_CONFIG } from '@/utils/commMethods';
import bus from '@/utils/bus'; */
// import { usePageParams } from '@/utils/usePageData';
import { useHttp } from '@crami/http';
import { cloneDeep } from 'lodash-es';
import PermissionPllicyContent from './Components/PermissionPllicyContent.vue';
import PermissionSub from './PermissionSub.vue';
import PermissionSubType from './PermissionSubType.vue';
import { useRouter } from 'vue-router';
import { useMultiTab } from '@/components/multi-tab';
import { useI18n } from '@crami/locale';
// import {  saveLineData, editLineData  } from './commonApi';
export default defineComponent({
  name: 'DataPermissionParameters',
  components: { PermissionPllicyContent, HModal, PermissionSub, PermissionSubType },
  props: {
    // propsData: {
    //   type: Object,
    //   default: () => {
    //     return {};
    //   },
    // },
    disabled: {
      type: Boolean,
      return: false,
    },
  },
  emits: ['success'],
  setup(_) {
    const { t } = useI18n();
    const router = useRouter();
    const loading: any = ref(false);
    // 通用参数处理
    // const pageParams: any = usePageParams();
    // const commonParams = computed(() => {
    //   return { ...getInfo(), ...pageParams.value };
    // });
    const permissionSubRef = ref();
    const permissionSubTypeRef = ref();
    // 基础信息部分
    const dataPermissionVO = ref({});

    const schemasBasic = reactive([
      {
        dataIndex: 'ename',
        title: t('permission.dataPermissionPolicy.dataPermissionPolicy.ename'),
        valueType: 'Input',
        width: '25%',
        fieldProps: {
          placeholder: t('permission.common.inputPlaceholder'),
          disabled: _.disabled,
          onChange: e => {
            const value = e.target.value;
            dataPermissionVO.value = {
              ename: value,
              peid: parentParams.value?.PEID,
            };
          },
        },
        formItemProps: {
          labelCol: { span: 8 },
          wrapperCol: { span: 18 },
          rules: [
            {
              isUnionCheck: false,
              unique: true,
            },
            {
              pattern: '^([\\s\\S]{0,200})?$',
              message: t('permission.dataPermissionPolicy.dataPermissionPolicy.inputMaxLen'),
              trigger: 'change',
            },
            {
              message: t('permission.dataPermissionPolicy.dataPermissionPolicy.enameMsg'),
              pattern: '^\\s*(\\S+\\s*)+$',
              required: true,
              trigger: 'change',
            },
          ],
        },
      },
      {
        dataIndex: 'statEid',
        title: t('permission.dataPermissionPolicy.dataPermissionPolicy.statEid'),
        valueType: 'Select',
        width: '25%',
        formItemProps: {
          labelCol: { span: 8 },
          wrapperCol: { span: 18 },
          rules: [
            {
              required: true,
              pattern: /^\s*(\S+\s*)+$/,
              message: t('permission.dataPermissionPolicy.dataPermissionPolicy.statEidMsg'),
            },
          ],
          showSearch: false,
        },
        fieldProps: {
          placeholder: t('permission.common.selectPlaceholder'),
          disabled: _.disabled,
          showSearch: false,
          options: [
            {
              label: t('platform.common.enable'),
              value: t('platform.common.enable'),
              disabled: null,
            },
            {
              label: t('platform.common.inactive'),
              value: t('platform.common.inactive'),
              disabled: null,
            },
          ],
        },
      },
      {
        dataIndex: 'perDesc',
        title: t('permission.dataPermissionPolicy.dataPermissionPolicy.perDesc'),
        valueType: 'Input',
        width: '25%',
        fieldProps: {
          placeholder: t('permission.common.inputPlaceholder'),
          disabled: _.disabled,
        },
        formItemProps: {
          labelCol: { span: 8 },
          wrapperCol: { span: 18 },
          rules: [
            {
              pattern: '^([\\s\\S]{0,100})?$',
              message: t('permission.dataPermissionPolicy.dataPermissionPolicy.perDescMaxLen'),
              trigger: 'change',
            },
          ],
        },
      },
    ]);
    const [formRef, props, methods] = useForm(
      {
        beforeSetData: (type, props) => {
          if (type === 'config') {
            const _props: any = {
              submitter: {
                isQuery: true,
                showResetButton: false,
                showSubmitButton: false,
                showAdvancedButton: false,
                showActionButtonGroup: false,
              },
              autoSubmitOnEnter: true,
              column: 4,
              layout: 'vertical',
              labelCol: { span: 8 }, //标签
              wrapperCol: { span: 20 },
              title: '',
              schemas: cloneDeep(schemasBasic),
              model: { statEid: t('platform.common.enable') },
              uniqueParams: {
                url: '/api/dataperservice/dataPerService/checkDataPerEname',
                companyId: getInfo(ICP_CONFIG)?.companyId,
                connect: getInfo(ICP_CONFIG)?.connect,
                lang: getInfo(ICP_CONFIG)?.lang,
                dataPermissionVO: dataPermissionVO,
                objectId: parentParams.value?.EID,
              },
            };
            methods?.setProps(_props, props);
          }
          return props;
        },
        immediate: true,
      },
      '',
      '',
      {},
    );

    //授权主体部分
    const mainTitle = ref('权限计算:' + '按照优先级顺序计算，平级拒绝优先');
    const mainType = ref([]);
    const mainModal = ref();
    //授权主体类型数据获取
    const getMainType = async (params: any) => {
      const data = await useHttp({
        url: '/api/dataperservice/dataPerService/getDataPerSubjectPluginItems',
        method: 'post',
        params: params,
      });
      return data;
    };
    const getMainTypeData = () => {
      const params = {
        lang: getInfo(ICP_CONFIG)?.lang,
      };
      try {
        getMainType(params).then(result => {
          if (result.code == 200) {
            mainType.value = result.data;
            methodsMain.updateSchema([
              {
                dataIndex: 'subjectType',
                fieldProps: {
                  // placeholder: '请输入',
                  options: mainType.value,
                },
              },
            ]);
            isLoad.value = true;
            // schemasMain[0].fieldProps.options = mainType.value;
          }
        });
      } finally {
        storageParentParams();
      }
      // 给下拉框赋值
    };
    const parentParams: any = ref();
    onMounted(() => {
      getMainTypeData();
    });
    const isLoad = ref(false);

    const storageParentParams = () => {
      // 存储PEID和EID，用于刷新页面可取值
      const routerParams = router.currentRoute.value.params;
      parentParams.value = {
        PEID: routerParams.pid,
        EID: routerParams.id || '',
      };
      // if (parentParams.value && JSON.stringify(parentParams.value) != JSON.stringify({})) {
      //   localStorage.setItem('permissionPolicy', JSON.stringify(routerParams));
      // } else {
      //   parentParams.value = JSON.parse(localStorage.getItem('permissionPolicy') || '{}');
      // }
      // 存在EID只许编辑和查看
      if (parentParams.value?.EID && isLoad.value) {
        // onInit();
      } else {
        getTableData();
      }
    };

    watch([isLoad, parentParams], () => {
      if (parentParams.value?.EID && isLoad.value) {
        onInit();
      }
    });

    // 回显时定义权限配置permission
    const permissionData = ref([]);
    const onInit = async () => {
      const res = await useHttp({
        url: '/api/dataperservice/dataPerService/getOneDataPer',
        method: 'post',
        params: {
          objectId: parentParams.value?.EID,
          // objectId: 'P_SYS_DATAPERMISSION_c2aae08393b4432e85264127c248cc6e',
          companyId: getInfo(ICP_CONFIG)?.companyId,
          connect: getInfo(ICP_CONFIG)?.connect,
          lang: getInfo(ICP_CONFIG)?.lang,
        },
      });
      if (res.code == 200 && res?.data) {
        const dataPerObjectVO = res.data?.dataPerObjectVO || {};
        const dataPerSubjectVO = res.data?.dataPerSubjectVO || {};
        const dataPermissionVO = res.data?.dataPermissionVO || {};
        // const data = res?.data?.data;
        // // 回显基础信息
        methods.setData({
          ename: dataPermissionVO.ename,
          statEid: dataPermissionVO.statEid,
          perDesc: dataPermissionVO.perDesc,
        });
        // // 回显权限配置
        if (dataPermissionVO?.permissionList?.length) {
          permissionData.value = dataPermissionVO?.permissionList || [];
        }

        // 获取授权主体类型的extend
        const options = methodsMain.getFormSchemas('subjectType')[0]?.fieldProps?.options || [];
        if (options?.length) {
          const currentData = options.find(item => item.value === dataPerSubjectVO?.subjectType);
          if (currentData?.extend) {
            var evalFun = new Function('return ' + currentData.extend);
            const extend = evalFun();
            currentMainExtend = extend;
          }
        }

        // 授权主体回显
        methodsMain.updateSchema([
          {
            dataIndex: 'subjectEid',
            fieldProps: {
              options: [
                { label: dataPerSubjectVO?.subjectLabel, value: dataPerSubjectVO?.subjectEid },
              ],
            },
            disabled: _.disabled || currentMainExtend.type == 'static',
          },
        ]);
        methodsMain.setData({
          subjectType: dataPerSubjectVO?.subjectType,
          subjectEid: dataPerSubjectVO?.subjectEid,
        });
        subjectType.value = dataPerSubjectVO?.subjectType;
        subjectEid.value = dataPerSubjectVO?.subjectEid;
        // 授权客体回显
        methodsSub.updateSchema([
          {
            dataIndex: 'objectType',
            fieldProps: {
              options: [
                { label: dataPerObjectVO?.objectTypeLabel, value: dataPerObjectVO?.objectType },
              ],
            },
          },
        ]);
        methodsSub.setData({
          objectType: dataPerObjectVO?.objectType,
        });
        objectEid.value = dataPerObjectVO?.objectEid || [];

        // 数据权限配置调用
        getTableData();
      }
    };

    const schemasMain = reactive([
      {
        dataIndex: 'subjectType',
        title: t('permission.dataPermissionPolicy.dataPermissionPolicy.subjectType'),
        valueType: 'Select',
        width: '25%',
        fieldProps: {
          placeholder: t('permission.common.selectPlaceholder'),
          options: mainType.value,
          disabled: _.disabled,
          showSearch: false,
        },

        formItemProps: {
          labelCol: { span: 24, style: { width: '160px' } },
          wrapperCol: { span: 18 },
          rules: [
            {
              required: true,
              pattern: /^\s*(\S+\s*)+$/,
              message: t('permission.dataPermissionPolicy.dataPermissionPolicy.subjectTypeMsg'),
            },
          ],
        },
      },
      {
        dataIndex: 'subjectEid',
        title: t('permission.common.authorizedBody'),
        valueType: 'Select',
        width: '25%',
        formItemProps: {
          labelCol: { span: 8 },
          wrapperCol: { span: 18 },
          rules: [
            {
              required: true,
              pattern: /^\s*(\S+\s*)+$/,
              message: t('permission.dataPermissionPolicy.dataPermissionPolicy.subjectEid'),
            },
          ],
        },
        fieldProps: {
          placeholder: t('permission.common.selectPlaceholder'),
          options: [],
          showSearch: false,
          notFoundContent: null,
          open: false,
          disabled: _.disabled,
          class: 'permission-subject-select',
        },
      },
    ]);
    const subjectEid = ref('');
    const subjectType = ref('');
    //授权主体内容
    const getMainData = () => {
      const params = {
        connect: getInfo(ICP_CONFIG)?.connect,
        lang: getInfo(ICP_CONFIG)?.lang,
        value: getInfo(ICP_CONFIG)?.companyId,
        // pluginName: subjectEid.value,
        pluginName: subjectType.value,
        companyId: getInfo(ICP_CONFIG)?.companyId,
      };
      getMainContentData(params).then(result => {
        if (result.code == 200) {
          methodsMain.updateSchema([
            {
              dataIndex: 'subjectEid',
              fieldProps: {
                // placeholder: '请输入',
                options: result.data,
              },
              disabled: true,
            },
          ]);
          methodsMain.setData({
            subjectEid: result.data[0].value,
          });
          subjectEid.value = result.data[0].value;
          formRefMain.value?.validateFields('subjectEid');
        }
      });
    };
    const getMainContentData = async (params: any) => {
      const data = await useHttp({
        url: '/api/dataperservice/dataPerService/getSubjectDisplayText',
        method: 'post',
        params: params,
      });
      return data;
    };
    //处理pop类型的弹窗
    const visible = ref(false);
    //给弹窗传递参数：
    const modalParam = reactive({
      params: {},
      data: [],
    });
    const mainModalTitle = ref('');
    const handlePop = (currentMainExtend, data) => {
      modalParam.params = currentMainExtend;
      modalParam.data = data;
      mainModalTitle.value = currentMainExtend.attr.title;
      // 打开弹窗
      openModal();
    };
    const openModal = () => {
      visible.value = true;
    };
    const beforeHandlePop = () => {
      methodsMain.updateSchema([
        {
          dataIndex: 'subjectEid',
          fieldProps: {
            options: [],
          },
          disabled: false,
        },
      ]);
      methodsMain.setData({
        subjectEid: '',
      });
      //弹窗销毁
      subjectEid.value = '';
      mainModal.value?.destroyAll();
    };
    let currentMainExtend: any = reactive({});
    const [formRefMain, propsMain, methodsMain] = useForm(
      {
        beforeSetData: (type, props) => {
          if (type === 'config') {
            const _props: any = {
              submitter: {
                isQuery: true,
                showResetButton: false,
                showSubmitButton: false,
                showAdvancedButton: false,
                showActionButtonGroup: false,
              },
              autoSubmitOnEnter: true,
              column: 4,
              layout: 'vertical',
              labelCol: { span: 8 }, //标签
              wrapperCol: { span: 20 },
              title: '',
              schemas: schemasMain,
              //   initialValue: {这里设置查询条件初始值},
            };
            methodsMain?.setProps(_props, props);
            methodsMain.updateSchema(
              [
                {
                  dataIndex: 'subjectType',
                  fieldProps: {
                    onChange: value => {
                      subjectType.value = value;
                      // 根据value获取extend
                      let etr = mainType.value.find(item => {
                        return item.value === value;
                      });
                      var evalFun = new Function('return ' + etr.extend);
                      const extend = evalFun();
                      currentMainExtend = extend;
                      //根据extend的type
                      if (extend.type == 'static') {
                        subjectEid.value = value;
                        getMainData();
                      }
                      if (extend.type == 'select') {
                        console.log(extend.type);
                      }
                      if (extend.type == 'pop') {
                        //调用方法，1.请空置 2.并且可点击 3.清空下拉数据源
                        beforeHandlePop();
                      }
                    },
                  },
                },
                {
                  dataIndex: 'subjectEid',
                  fieldProps: {
                    onDropdownVisibleChange: open => {
                      if (!open) return;
                      // 解析当前的currentMainExtend
                      if (currentMainExtend.type == 'static') {
                        return;
                      }
                      if (currentMainExtend.type == 'select') {
                        return;
                      }
                      if (currentMainExtend.type == 'pop') {
                        handlePop(currentMainExtend, subjectEid.value);
                        // handlePop();
                      }
                    },
                  },
                },
              ],
              props,
            );
          }
          return props;
        },
        immediate: true,
      },
      '',
      '',
      {},
    );

    //数据获取部分
    const componentRef = ref({});
    const handleOk = () => {
      const list = (componentRef.value as any).getTableData();
      if (list?.length > 50) {
        message.warning(t('permission.common.selectMaxLen'));
        return;
      }
      const idList = (componentRef.value as any).getTableData().join(';');

      console.log(idList);
      //根据id获取显示值，设置授权主体的值，并设置下啦数据源的内容
      const params = {
        connect: getInfo(ICP_CONFIG)?.connect,
        lang: getInfo(ICP_CONFIG)?.lang,
        value: idList,
        pluginName: subjectType.value,
        companyId: getInfo(ICP_CONFIG)?.companyId,
      };
      getMainContentData(params).then(result => {
        console.log(params);
        if (result.code == 200) {
          methodsMain.updateSchema([
            {
              dataIndex: 'subjectEid',
              fieldProps: {
                options: result.data,
              },
            },
          ]);
          methodsMain.setData({
            subjectEid: idList,
          });
          subjectEid.value = idList;
          visible.value = false;
          formRefMain.value?.validateFields('subjectEid');
        }
      });
    };

    // 授权客体部分
    const subType = ref([]);
    const subTitle = ref('权限计算:' + '按照优先级顺序计算，平级拒绝优先');
    const getSubTypeData = async () => {
      const params = {
        // companyId: getInfo()?.companyId,
        connect: getInfo(ICP_CONFIG)?.connect,
        lang: getInfo(ICP_CONFIG)?.lang,
        value: '',
        pluginName: 'PSDS_TENANT',
      };
      const result = await getSubType(params);
      if (result.code == 200) {
        subType.value = result.data;
      }

      // 给下拉框赋值
    };
    const getSubType = async (params: any) => {
      const data = await useHttp({
        // url: '/api/dataperservice/dataPerService/getSubjectDisplayText',
        url: '/api/dataperservice/dataPerService/getDataPerSubjectPluginItems',
        method: 'post',
        params: params,
      });
      const resultData = data.data;
      return resultData;
    };
    getSubTypeData();

    console.log(subType.value);
    const schemasSub = reactive([
      {
        dataIndex: 'objectType',
        title: t('permission.dataPermissionPolicy.dataPermissionPolicy.objectType'),
        valueType: 'Select',
        width: '25%',
        fieldProps: {
          placeholder: t('permission.common.selectPlaceholder'),
          notFoundContent: null,
          open: false,
          disabled: _.disabled,
          showSearch: false,
        },
        formItemProps: {
          labelCol: { span: 24, style: { width: '160px' } },
          wrapperCol: { span: 18 },
          rules: [
            {
              required: true,
              pattern: /^\s*(\S+\s*)+$/,
              message: t('permission.dataPermissionPolicy.dataPermissionPolicy.objectTypeMsg'),
              trigger: ['blur', 'change'],
            },
          ],
        },
      },
      {
        dataIndex: 'objectEid',
        title: t('permission.common.authorizedObject'),
        valueType: 'Select',
        width: '25%',
        formItemProps: {
          labelCol: { span: 8 },
          wrapperCol: { span: 18 },
          // rules: [{ required: true, pattern: /^\s*(\S+\s*)+$/, message: '请选择授权客体' }],
        },
        fieldProps: {
          placeholder: t('permission.common.selectPlaceholder'),
          mode: 'multiple',
          showSearch: false,
          options: [],
          notFoundContent: null,
          open: false,
          class: 'permission-pllicy-select-sub',
          // maxTagTextLength: 3,
          // maxTagCount: 3,
          disabled: _.disabled,
        },
      },
    ]);

    const [formRefSub, propsSub, methodsSub] = useForm(
      {
        beforeSetData: (type, props) => {
          if (type === 'config') {
            const _props: any = {
              submitter: {
                isQuery: true,
                showResetButton: false,
                showSubmitButton: false,
                showAdvancedButton: false,
                showActionButtonGroup: false,
              },
              autoSubmitOnEnter: true,
              column: 4,
              layout: 'vertical',
              labelCol: { span: 8 }, //标签
              wrapperCol: { span: 20 },
              title: '',
              schemas: cloneDeep(schemasSub),
              //   initialValue: {这里设置查询条件初始值},
            };
            methodsSub?.setProps(_props, props);
            methodsSub?.updateSchema(
              [
                {
                  dataIndex: 'objectType',
                  fieldProps: {
                    onDropdownVisibleChange: open => {
                      const options =
                        methodsSub.getFormSchemas('objectType')[0]?.fieldProps?.options || [];
                      open && permissionSubTypeRef.value?.show(options[0]);
                    },
                  },
                },
                {
                  dataIndex: 'objectEid',
                  fieldProps: {
                    onDropdownVisibleChange: open => {
                      const objectType = methodsSub.getData()?.objectType;
                      // 授权客体类型已选
                      if (open && objectType) {
                        const options =
                          methodsSub.getFormSchemas('objectType')[0]?.fieldProps?.options || [];
                        permissionSubRef.value?.show(options[0], objectEid.value);
                      }
                    },
                  },
                },
              ],
              props,
            );
          }
          return props;
        },
        immediate: true,
      },
      '',
      '',
      {},
    );

    // 表格配置部分
    const configTitle = ref('权限计算:' + '按照优先级顺序计算，平级拒绝优先');
    const columns = reactive([
      {
        dataIndex: 'value',
        title: t('permission.common.permission'),
        align: 'center',
      },
      {
        dataIndex: 'allow',
        title: t('permission.common.allow'),
        align: 'center',
      },
      {
        dataIndex: 'reject',
        title: t('permission.common.reject'),
        align: 'center',
      },
      {
        dataIndex: 'other',
        title: t('permission.common.nothing'),
        width: '200px',
        align: 'center',
      },
    ]);
    const list = ref();
    const getTableDataFun = async () => {
      const params = {
        connect: getInfo(ICP_CONFIG)?.connect,
        lang: getInfo(ICP_CONFIG)?.lang,
      };
      const data = await useHttp({
        url: '/api/dataperservice/dataPerService/getActionList',
        method: 'post',
        params: params,
      });
      return data;
    };
    const checkStatusAll = ref('');
    const getTableData = () => {
      getTableDataFun().then(result => {
        if (result.code == 200) {
          list.value = result.data;
          checkStatusAll.value = result.data[0]?.checkStatus;
          nextTick(() => {
            if (permissionData.value?.length) {
              permissionData.value.map(item => {
                list.value?.map(i => {
                  if (item.key === i.key) {
                    i.checkStatus = item.checkStatus;
                  }
                });
              });
            }
          });
        }
      });
    };
    const handleChange = (index: number, text: any) => {
      list.value[index].checkStatus = text;
      checkStatusAll.value = list.value[0].checkStatus;
      list.value = [].concat(list.value as any);
      if (index == 0) {
        if (text != '3') {
          list.value.forEach(item => {
            item.checkStatus = text;
          });
        }
      } else {
        let tempData = cloneDeep(list.value).slice(1);
        const result = tempData.some(item => {
          return item.checkStatus != checkStatusAll.value;
        });
        if (result) {
          list.value[0].checkStatus = '3';
        }
      }
    };

    // 授权客体类型选择
    const permissionSubTypeFunSuccess = data => {
      methodsSub.updateSchema([
        {
          dataIndex: 'objectType',
          fieldProps: {
            // placeholder: '请输入',
            options: [data],
          },
        },
      ]);
      objectEid.value = [];
      methodsSub.setData({
        objectType: data.value,
      });
      methodsSub.updateSchema([
        {
          dataIndex: 'objectEid',
          fieldProps: {
            options: [],
          },
        },
      ]);
      methodsSub.setData({
        objectEid: [],
      });
      formRefSub.value?.validateFields('objectType');
    };

    // 授权客体的值
    const objectEid = ref([]);

    // 授权客体保存成功
    const permissionSubFunSuccess = (data = []) => {
      objectEid.value = data;
    };

    // 监听授权客体字段变化进行复制操作
    watch(
      () => objectEid.value,
      () => {
        const data = [...objectEid.value];
        const options = data.map(item => {
          return {
            value: JSON.stringify({ field: item.field, value: item.value }),
            label: item.custom ? `${item.field}:${item.value}` : item.label,
            disabled: true,
          };
        });
        const selectData = options.map(item => item.value) || [];
        methodsSub.updateSchema([
          {
            dataIndex: 'objectEid',
            fieldProps: {
              options: options,
            },
          },
        ]);
        methodsSub.setData({
          objectEid: selectData,
        });
      },
    );
    // watch(
    //   () => list.value,
    //   () => {
    //     if (list.value.length) {
    //       debugger;
    //       //完全控制的值
    //       const checkStatus = list.value[0].checkStatus;
    //       //如果all以外的数据有checkStatus不和all一致的，all的值设置为‘3’

    //       if (list.value[0].checkStatus != '3') {
    //         console.log(list.value);
    //         list.value.forEach(element => {
    //           element.checkStatus = checkStatus;
    //         });
    //       } else {
    //         let tempData = cloneDeep(list.value).slice(1);
    //         const result = tempData.some(item => {
    //           return item.checkStatus != checkStatus;
    //         });
    //         if (result) {
    //           list.value[0].checkStatus = '3';
    //         }
    //       }
    //     }
    //   },
    // );
    //保存按钮实现
    const savePermissionData = async () => {
      if (loading.value) return;
      let data: any = {
        connect: getInfo(ICP_CONFIG)?.connect,
        companyId: getInfo(ICP_CONFIG)?.companyId,
        lang: getInfo(ICP_CONFIG)?.lang,
        dataPermissionVO: {
          ename: '', //名称
          statEid: '', //状态
          perDesc: '', //描述
          peid: '', //树节点
          perType: '1', //
          permissions: [], //表格权限
        },
        //授权主体
        dataPerSubjectVO: {
          subjectType: '',
          subjectTypeLabel: '',
          subjectEid: '',
          subjectLabel: '',
        },
        // 授权客体
        dataPerObjectVO: {
          objectType: '',
          objectTypeLabel: '',
          objectEid: [],
        },
      };
      //数据校验
      await Promise.all([
        formRef.value.validate(),
        formRefMain.value.validate(),
        formRefSub.value.validate(),
      ]);
      //基础数据获取
      data.dataPermissionVO = methods.getData();
      data.dataPermissionVO.peid = parentParams.value.PEID;
      parentParams.value.EID && (data.objectId = parentParams.value.EID);
      data.dataPermissionVO.perType = '1';

      // 授权主体类型当前选中数据，用于获取label
      const currentPerType = mainType.value?.find(
        item => item.value === methodsMain.getData()?.subjectType,
      );
      // 授权主体当前选中数据，用于获取label
      const subjectEidFormSchemas = methodsMain.getFormSchemas('subjectEid') || [];
      const subjectEidOption = subjectEidFormSchemas[0]?.fieldProps?.options || [];
      //授权主体获取
      data.dataPerSubjectVO = {
        ...(methodsMain.getData() || {}),
        subjectTypeLabel: currentPerType?.label,
        subjectLabel: subjectEidOption[0]?.label,
      };

      // 授权客体类型当前选中数据，用于获取label
      const objectTypeFormSchemas = methodsSub.getFormSchemas('objectType') || [];
      const objectTypeOption = objectTypeFormSchemas[0]?.fieldProps?.options || [];
      //授权客体获取
      data.dataPerObjectVO = {
        objectType: methodsSub.getData()?.objectType,
        objectEid: objectEid.value,
        objectTypeLabel: objectTypeOption[0]?.label,
      };
      //表格配置数据获取
      // list.value.filter(item=> item.checkStatus != '3').
      const permissionArr = list.value
        .filter(item => item.checkStatus != '3')
        .map(item => {
          const obj = {};
          obj[item.key] = item.checkStatus;
          return obj;
        });
      let permissionArrTemp = [];
      const result = permissionArr.some(item => {
        return item.hasOwnProperty('ALL');
      });
      if (result) {
        permissionArrTemp = permissionArr.splice(0, 1);
      } else {
        permissionArrTemp = permissionArr;
      }
      data.dataPermissionVO.permissions = permissionArrTemp.length
        ? JSON.stringify(permissionArrTemp)
        : '';
      loading.value = true;
      saveDataRer(data)
        .then(result => {
          if (result.code == 200) {
            message.success(result.msg);
            closePage();
            bus.emit('refreshTable');
            loading.value = false;
            router.push({ name: 'AddPermissionPolicy' });
            // 关闭tab，刷新列表
          } else {
            loading.value = false;
            message.error(result.msg);
          }
        })
        .then(() => {
          loading.value = false;
          // message.error(result.msg);
        });
    };
    const saveDataRer = async (params: any) => {
      const data = await useHttp({
        url: '/api/dataperservice/dataPerService/saveDataPer',
        method: 'post',
        params: params,
      });
      return data;
    };
    //关闭按钮实现
    const [{ close }] = useMultiTab();
    const closePage = () => {
      const path = router.currentRoute.value?.path;
      if (!path) return;
      close(path, '/platform/queryConfiguration/GeneralQueryConfig/GeneralQueryConfigCreate');
    };

    // 取消
    const cancelPage = () => {
      // 点击取消，如果是编辑直接回数据权限策略，如果是新增增进行返回确认
      if (parentParams.value?.EID) {
        closePage();
        return;
      }
      HModal.confirm({
        title: t('platform.common.prompt'),
        content: t('permission.dataPermissionPolicy.dataPermissionPolicy.closeMsg'),
        onOk() {
          closePage();
        },
        class: 'permission-confirm',
      });
    };
    return {
      t,
      formRef,
      props,
      schemasBasic,
      //主体
      mainTitle,
      formRefMain,
      mainModal,
      propsMain,
      modalParam,
      componentRef,
      mainModalTitle,
      handleOk,

      //客体
      subTitle,
      formRefSub,
      propsSub,
      // 表格配置
      list,
      handleChange,
      configTitle,
      // gridRef,
      columns,
      // propsTable,
      visible,
      permissionSubRef,
      permissionSubTypeRef,
      permissionSubTypeFunSuccess,
      permissionSubFunSuccess,
      //群居保存设置
      savePermissionData,
      closePage,
      cancelPage,
      loading,
      _,
    };
  },
});
</script>

<style lang="less" scoped>
.top {
  background: #fff;
  padding: 20px 24px;
  margin-top: 0;
  border-radius: 8px;
}
.exclamation-icon {
  color: @normal-color;
  margin-left: 4px;
  font-size: 16px;
  &:hover {
    color: @info-color;
  }
}
.permission-pllicy-btn {
  text-align: right;
  padding-right: 15px;
  position: fixed;
  background: #fff;
  border: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  box-shadow: 0px -9px 16px 0px rgba(74, 85, 107, 0.07);
  padding: 18px 20px 18px 0;
  button {
    margin-left: 24px;
  }
}
:deep(.permission-pllicy-select-sub .ant-select-selector .ant-select-selection-overflow) {
  flex-wrap: nowrap !important;
  overflow: hidden !important;
}
:deep(.permission-subject-select) {
  .ant-select-arrow {
    display: none;
  }
}
</style>
