<template>
  <h-b-form
    ref="formRefMain"
    name="main"
    v-bind="propsMain"
    :class="{ 'hoteam-b-description-form platform-b-description-form': isStatus === 'view' }"
  ></h-b-form>
  <h-modal
    ref="mainModal"
    id="AdminMember-queryModal"
    v-model:visible="visible"
    :title="mainModalTitle"
    :cancelText="t('platform.common.cancel')"
    :okText="t('platform.common.ok')"
    width="1250px"
    wrap-class-name="full-modal"
    :destroyOnClose="true"
    @ok="handleOk"
  >
    <permission-pllicy-content
      ref="componentRef"
      :modalParam="modalParam"
      id="AdminMember-queryTransfer"
    />
  </h-modal>
</template>
<script lang="ts">
import { defineComponent, inject, onMounted, reactive, ref } from 'vue';
import router from '@/router';
import { useHttp } from '@crami/http';
import { useForm } from '@crami/bui-platform';
import { message, HModal } from '@crami/ui';
import { BForm as HBForm } from '@crami/bui';
import { useI18n } from '@crami/locale';
import { getInfo, ICP_CONFIG } from '@remote/icpx-platform/utils';
/* import { getInfo, ICP_CONFIG } from '@/utils/commMethods'; */
import PermissionPllicyContent from './PermissionPllicyContent.vue';
export default defineComponent({
  components: {
    HModal,
    HBForm,
    PermissionPllicyContent,
  },
  props: {
    /**
     * @param {Object} dataPerSubjectVO 查看/编辑：对象授权单条数据
     */
    dataPerSubjectVO: {
      type: Object,
      default: () => {
        return {
          subjectType: '',
          subjectEid: '',
        };
      },
    },
    dataPerSubjectVOObj: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  setup(props) {
    const { t } = useI18n();
    // 表单状态：add|edit|view
    const isStatus = inject('isStatus') || ref('add');
    const _disabled = ref((isStatus as any).value === 'view');
    // 授权主体部分
    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,
      };
      getMainType(params).then(result => {
        if (result.code == 200) {
          mainType.value = result.data;
          methodsMain.updateSchema([
            {
              dataIndex: 'subjectType',
              fieldProps: {
                // placeholder: '请输入',
                options: mainType.value,
              },
            },
          ]);
          // schemasMain[0].fieldProps.options = mainType.value;
          if ((isStatus as any).value === 'view' || (isStatus as any).value === 'edit') {
            assignDataPerSubjectVO(props.dataPerSubjectVO);
          }
        }
      });

      // 给下拉框赋值
    };
    const parentParams: any = ref();
    onMounted(() => {
      getMainTypeData();
      storageParentParams();
      // 查看|编辑表单的时候需要初始化[主体授权]
      if ((isStatus as any).value === 'view' || (isStatus as any).value === 'edit') {
        handleOk('init');
      }
    });

    const storageParentParams = () => {
      // 存储PEID和EID，用于刷新页面可取值
      const routerParams = router.currentRoute.value.params;
      parentParams.value = routerParams;
      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) {
      //   onInit();
      // }
    };
    const assignDataPerSubjectVO = dataPerSubjectVO => {
      // 获取授权主体类型的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.value || currentMainExtend.type == 'static',
        },
      ]);
      methodsMain.setData({
        subjectType: dataPerSubjectVO?.subjectType,
        subjectEid: dataPerSubjectVO?.subjectEid,
      });
      subjectType.value = dataPerSubjectVO?.subjectType;
      subjectEid.value = dataPerSubjectVO?.subjectEid;
    };

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

        formItemProps: {
          labelCol: { span: 20 },
          wrapperCol: { span: 24 },
          rules: [
            {
              required: true,
              pattern: /^\s*(\S+\s*)+$/,
              message: t('permission.productionPermission.formParams.subjectTypeMsg'),
            },
          ],
        },
      },
      {
        dataIndex: 'subjectEid',
        title: t('permission.common.authorizedBody'),
        valueType: 'Select',
        width: '50%',
        formItemProps: {
          labelCol: { span: 20 },
          wrapperCol: { span: 24 },
          rules: [
            {
              required: true,
              pattern: /^\s*(\S+\s*)+$/,
              message: t('permission.productionPermission.formParams.subjectEid'),
            },
          ],
        },
        fieldProps: {
          placeholder: t('permission.common.selectPlaceholder'),
          options: [],
          showSearch: false,
          notFoundContent: null,
          open: false,
          disabled: _disabled.value,
          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;
        }
      });
    };
    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,
              readonly: (isStatus as any).value === 'view',
              // initialValues: {
              //   subjectType: '',
              // },
            };
            console.log('我要设置主题类型数据，触发change方法');
            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) false;
                      // 解析当前的currentMainExtend
                      if (currentMainExtend.type == 'static') {
                        return;
                      }
                      if (currentMainExtend.type == 'select') {
                        return;
                      }
                      if (currentMainExtend.type == 'pop') {
                        handlePop(currentMainExtend, subjectEid.value);
                        // handlePop();
                      }
                    },
                  },
                },
              ],
              props,
            );
            // methodsMain.setData({
            //   subjectType: subjectType.value,
            // });
          }
          return props;
        },
        immediate: true,
      },
      '',
      '',
      {},
    );

    //数据获取部分
    const componentRef = ref({});
    const handleOk = init => {
      let idList = '';
      if (init === '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;
        }
        idList = list.join(';');
      }
      //根据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;
        }
      });
    };
    return {
      //主体
      visible,
      formRefMain,
      methodsMain,
      mainType,
      mainModal,
      propsMain,
      modalParam,
      componentRef,
      mainModalTitle,
      isStatus,
      subjectEid,
      subjectType,
      handleOk,
      assignDataPerSubjectVO,
      // 多语言
      t,
    };
  },
});
</script>
