<template>
  <div class="production-permission">
    <!-- <h2 class="com-border-title">授权客体</h2> -->
    <div class="hoteam-b-form-divider-title">
      <div class="hoteam-b-form-divider-block"></div>
      <div>{{ t('permission.common.authorizedObject') }}</div>
    </div>
    <table-show :permissionObjectInfos="permissionObjectInfosReq"></table-show>
    <h-divider dashed />
    <div class="hoteam-b-form-divider-title">
      <div class="hoteam-b-form-divider-block"></div>
      <div>{{ t('permission.common.authorizedBody') }}</div>
    </div>
    <div class="form-box">
      <permission-object
        ref="PermissionSubRef"
        :dataPerSubjectVO="dataPerSubjectVO"
        v-if="reqFinish"
      ></permission-object>
    </div>
    <h-divider class="divider-custom" dashed />
    <div class="hoteam-b-form-divider-title">
      <div class="hoteam-b-form-divider-block"></div>
      <div>{{ t('permission.productionPermission.formParams.authExpireTime') }}</div>
    </div>
    <h-date-picker
      ref="dateRef"
      v-model:value="dataPermissionVO.expireTime"
      format="YYYY-MM-DD HH:mm"
      value-format="YYYY-MM-DD HH:mm"
      :placeholder="t('permission.productionPermission.formParams.selectTimePlaceholder')"
      :show-time="true"
      :disabled-date="disabledDate"
      :disabled-time="disabledDateTime"
      v-show="isStatus !== 'view'"
    />
    <h-descriptions
      layout="vertical"
      bordered
      v-show="isStatus === 'view'"
      :column="3"
      style="width: 50%"
      size="middle"
    >
      <h-descriptions-item
        :label="t('permission.productionPermission.formParams.expireTime')"
        :span="1"
      >
        <!-- {{ dataPermissionVO.expireTime }} -->
        <h-date-picker
          ref="dateRef"
          v-model:value="dataPermissionVO.expireTime"
          format="YYYY-MM-DD HH:mm"
          value-format="YYYY-MM-DD HH:mm"
          placeholder=""
          :show-time="true"
          :disabled="true"
        />
      </h-descriptions-item>
    </h-descriptions>
    <h-divider dashed />
    <div class="hoteam-b-form-divider-title">
      <div class="hoteam-b-form-divider-block"></div>
      <div>{{ t('permission.common.authorizationConfig') }}</div>
    </div>
    <permission-config
      v-if="reqFinish"
      :permissionData="dataPermissionList"
      @handlePermissions="handlePermissions"
    ></permission-config>
  </div>
</template>
<script lang="ts">
import { defineComponent, inject, reactive, ref, toRefs } from 'vue';
import type { PropType } from 'vue';
import type { Dayjs } from 'dayjs';
import dayjs from 'dayjs';
import type { IObjPerParams, IObjectItem, IModalParam } from './type';
import { getInfo, ICP_CONFIG } from '@remote/icpx-platform/utils';
/* import { getInfo, ICP_CONFIG } from '@/utils/commMethods'; */
import { getObjectPermissionDisplay } from './useMethods';
import { useHttp } from '@crami/http';
import { message, Divider as HDivider, DatePicker as HDatePicker } from '@crami/ui';
import TableShow from './TableShow.vue';
import PermissionConfig from './PermissionConfig.vue';
import PermissionObject from './PermissionObject.vue';
import { useI18n } from '@crami/locale';

export default defineComponent({
  name: 'AddObjectPermission',
  components: {
    HDivider,
    HDatePicker,
    TableShow,
    PermissionConfig,
    PermissionObject,
  },
  props: {
    /**
     * @param {Array} permissionObjectList 【对接数据】客体信息ids
     * @param {Array} permissionObjectInfos 需要展示的客体信息
     * @param {Object} modalParam 查看/编辑：对象授权单条数据
     * @param {Boolean} isSingleData 是否是单条数据
     */
    permissionObjectList: {
      type: Array,
      default: () => [],
    },
    permissionObjectInfos: {
      type: Array as PropType<IObjectItem[]>,
      default: () => [],
    },
    modalParam: {
      type: Object as PropType<IModalParam>,
      default: () => {
        return {
          EID: '',
          ENAME: '',
          EXPIRETIME: '',
          PERMISSIONS: '',
          PERSUBJECT: '',
        };
      },
    },
    isSingleData: {
      type: Boolean,
      default: false,
    },
  },
  emits: ['closeDialog', 'handleLoading'],
  setup(props, { emit }) {
    const { t } = useI18n();
    const { lang, connect, companyId, TIME_ZONE } = getInfo(ICP_CONFIG);
    /**
     * 表单状态
     * 描述：add|edit|view
     */
    const isStatus = inject('isStatus') || ref('add');
    /**
     * 表单详情
     * 描述：需要查看的数据（查看、编辑的时候获取表单详情，给表单赋值）
     */
    const reqFinish = ref((isStatus as any).value === 'add');
    const formDetail = reactive({
      dataPermissionList: [],
    });
    const onInit = async () => {
      if ((isStatus as any).value === 'add') {
        return;
      }
      const res = await useHttp({
        url: '/api/dataperservice/dataPerService/getOneDataPer',
        method: 'post',
        params: {
          objectId: props.modalParam?.EID,
          companyId,
          connect,
          lang,
        },
      });
      if (res.code == 200 && res?.data) {
        // 授权主体
        // const { assignDataPerSubjectVO } = PermissionSubRef.value;
        // const dataPerSubjectVO = res.data?.dataPerSubjectVO || {};
        // setTimeout(() => {
        //   assignDataPerSubjectVO(dataPerSubjectVO);
        // }, 500);
        objPerParams.dataPerSubjectVO = res.data?.dataPerSubjectVO || {};
        reqFinish.value = true;
        // 权限配置
        const dataPermissionVO = res.data?.dataPermissionVO || {};
        objPerParams.dataPermissionVO.expireTime = dataPermissionVO?.expireTime;
        if (dataPermissionVO?.permissionList?.length) {
          formDetail.dataPermissionList = dataPermissionVO?.permissionList || [];
        }
      }
    };
    onInit();
    /**
     * 表单提交值
     * 描述：需要保存的数据（表单提交）
     */
    // 表单入参
    const { modalParam } = toRefs(props);
    const { EID, EXPIRETIME, PERMISSIONS } = modalParam.value;
    const objPerParams = reactive<IObjPerParams>({
      lang: lang,
      connect: connect,
      companyId: companyId,
      objectId: EID,
      // 基础参数
      dataPermissionVO: {
        perType: '2',
        expireTime: '', // 授权截止有效期
        permissions: PERMISSIONS || '', // 权限配置
      },
      // 授权主体
      dataPerSubjectVO: {
        subjectType: '',
        subjectEid: '',
      },
      // 授权客体
      dataPerObjectVO: {
        objectType: '',
        objectEid: [],
      },
    });
    // 处理***授权客体***参数
    let permissionObjectInfosReq = ref([]);
    const handleDataPerObjectVO = () => {
      if (props.isSingleData) {
        // ProductionPermission弹窗过来的
        permissionObjectInfosReq.value = props.permissionObjectInfos;
        assignToDataPerObjectVO(props.permissionObjectInfos);
      } else {
        // 外部对象弹窗过来的
        const ids = props.permissionObjectList.map(item => {
          return (item as any).productCode;
        });
        getObjectPermissionDisplay(ids).then(data => {
          permissionObjectInfosReq.value = data;
          assignToDataPerObjectVO(permissionObjectInfosReq.value);
        });
      }
    };
    // 赋值操作
    const assignToDataPerObjectVO = infoList => {
      objPerParams.dataPerObjectVO = {
        objectType: infoList.map(item => item.objType).join(','),
        objectEid: infoList.map(item => {
          return {
            field: 'EID',
            operation: '==',
            value: item.id,
            andOrFlag: 'AND',
          };
        }),
      };
    };
    handleDataPerObjectVO();
    // 处理***权限配置***参数
    const handlePermissions = value => {
      objPerParams.dataPermissionVO.permissions = value !== '[]' ? value : '';
    };
    // 处理***授权主体***参数
    const handleDataPerSubjectVO = () => {
      const { methodsMain, mainType } = PermissionSubRef.value;
      // 授权主体类型当前选中数据，用于获取label
      const currentPerType = mainType.find(
        item => item.value === methodsMain.getData()?.subjectType,
      );
      // 授权主体当前选中数据，用于获取label
      const subjectEidFormSchemas = methodsMain.getFormSchemas('subjectEid') || [];
      const subjectEidOption = subjectEidFormSchemas[0]?.fieldProps?.options || [];
      // 授权主体获取
      objPerParams.dataPerSubjectVO = {
        ...(methodsMain.getData() || {}),
        subjectTypeLabel: currentPerType?.label,
        subjectLabel: subjectEidOption[0]?.label,
      };
    };
    /**
     * 表单提交
     * 描述：提交表单数据
     */
    const PermissionSubRef = ref(null);
    const submitForm = async () => {
      const { formRefMain } = PermissionSubRef.value;
      await Promise.all([formRefMain.validate()]).then(() => {
        handleDataPerSubjectVO();
      });
      emit('handleLoading', true); // 打开按钮loading
      const res = await useHttp({
        url: '/api/dataperservice/dataPerService/saveObjPer',
        method: 'post',
        params: {
          ...objPerParams,
          timeZone: TIME_ZONE,
        },
      });
      if (res.code == 200) {
        message.success(res.msg);
        emit('handleLoading', false);
        emit('closeDialog', false);
      } else {
        message.error(res.msg);
        emit('handleLoading', false);
      }
    };
    const disabledDate = (current: Dayjs) => {
      return current && current < dayjs().subtract(1, 'days').endOf('day');
    };

    const range = (start, end) => {
      const result = [];
      for (let i = start; i <= end; i++) {
        result.push(i);
      }
      return result;
    };

    const disabledDateTime = dates => {
      let hours = dayjs().hour(); //0~23

      let minutes = dayjs().minute(); //0~59
      let settingHours = dayjs(new Date(dates)).hour();

      if ((dates && dayjs().subtract(1, 'days').endOf('day'), dates < dayjs().endOf('day'))) {
        if (settingHours <= hours) {
          return {
            disabledHours: () => range(0, hours - 1),
            disabledMinutes: () => range(0, minutes),
          };
        } else {
          return {
            disabledHours: () => range(0, hours - 1),
          };
        }
      }
    };
    return {
      isStatus,
      reqFinish,
      ...toRefs(props),
      ...toRefs(objPerParams),
      ...toRefs(formDetail),
      handlePermissions,
      submitForm,
      PermissionSubRef,
      permissionObjectInfosReq,
      t,
      disabledDate,
      disabledDateTime,
    };
  },
});
</script>
<style lang="less" scoped>
@import '@/theme/default/variables.less';

.production-permission {
  .form-box {
    // padding: 0 6px;
    :deep(.hoteam-b-form-title-top) {
      display: none;
    }
    :deep(.crami-form-item-body) {
      overflow-y: unset !important;
      max-height: none !important;
    }
    :deep(.platform-b-description-form) {
      .crami-form-item-body {
        padding-bottom: 24px;
      }
    }
  }
  // 表单item和虚线都有间距，去掉虚线的上间距
  .divider-custom {
    margin-top: 0;
  }
  :deep(.ant-picker) {
    width: 399px;
  }
  // 修改descriptions样式同业务表单样式一致
  :deep(.ant-descriptions) {
    .ant-descriptions-item-label,
    .ant-descriptions-item-content {
      padding: 8px;
      span {
        display: block;
        height: @height-base;
        line-height: @height-base;
      }
    }
  }
  .ant-descriptions-view {
    .ant-picker-disabled {
      background: transparent;
      border: none;
      :deep(input) {
        color: rgba(0, 0, 0, 0.85);
      }
      :deep(.ant-picker-suffix) {
        display: none !important;
      }
    }
  }
}
// :deep(.crami-form-item-body) {
//   overflow-y: hidden !important;
// }
</style>
