<template>
  <h-modal
    id="AdminMember-queryModal"
    v-model:visible="visible"
    :title="t('permission.common.authorizedObject')"
    :cancelText="t('platform.common.cancel')"
    :okText="t('platform.common.save')"
    width="886px"
    wrap-class-name="full-modal"
    :destroyOnClose="true"
    :maskClosable="false"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <p class="platform-perssionsub-title">
      {{ t('permission.dataPermissionPolicy.dataPermissionPolicy.objectType') }}：{{
        subType?.label
      }}
    </p>
    <h-divider dashed></h-divider>
    <div>
      <p class="platform-perssionsub-title">
        {{ t('permission.dataPermissionPolicy.dataPermissionPolicy.permissionSub.attrSelect') }}
        <h-tooltip placement="right">
          <template #title>
            <span>
              {{
                t(
                  'permission.dataPermissionPolicy.dataPermissionPolicy.permissionSub.attrSelectTip',
                )
              }}
            </span>
          </template>
          <ExclamationCircleOutlined class="exclamation-icon" />
        </h-tooltip>
      </p>
      <h-row class="table-title-margin app-custom-edit-form-header">
        <h-col :span="11">
          {{ t('permission.dataPermissionPolicy.dataPermissionPolicy.permissionSub.objectAttr') }}
        </h-col>
        <h-col :span="11" style="padding-left: 10px">
          {{
            t('permission.dataPermissionPolicy.dataPermissionPolicy.permissionSub.objectAttrValue')
          }}
        </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="formManageRefAttr"
        name="dynamic_form_nest_item"
        :model="attrValidateForm"
      >
        <h-row v-for="(attr, index) in attrValidateForm.attr" :key="attr.key">
          <h-col :span="11">
            <h-form-item
              label=""
              :name="['attr', index, 'field']"
              :rules="{
                required: true,
                message: t(
                  'permission.dataPermissionPolicy.dataPermissionPolicy.permissionSub.objectAttrMsg',
                ),
                trigger: 'blur',
              }"
            >
              <h-select
                v-model:value="attr.field"
                :optionLabelProp="null"
                @change="data => attrChange(data, index)"
              >
                <h-select-option
                  v-for="item in permissionSub"
                  :key="item.value"
                  :value="item.value"
                >
                  {{ item.label }}
                </h-select-option>
              </h-select>
            </h-form-item>
          </h-col>
          <h-col :span="11">
            <h-form-item
              label=""
              :name="['attr', index, 'value']"
              :rules="{
                required: true,
                message: t(
                  'permission.dataPermissionPolicy.dataPermissionPolicy.permissionSub.objectAttrValueMsg',
                ),
                trigger: ['change', 'blur'],
              }"
            >
              <h-select
                v-model:value="attr.value"
                :mode="
                  currentMainExtend[index]?.type == 'select' &&
                  currentMainExtend[index]?.attr?.multible
                    ? 'multiple'
                    : ''
                "
                :optionLabelProp="null"
                :showSearch="false"
                @change="data => attrValChange(data, index)"
                @dropdownVisibleChange="open => dropdownVisibleChange(open, index)"
              >
                <h-select-option
                  v-for="(item, ind) in subDataList[index]"
                  :key="ind"
                  :value="item.value"
                >
                  {{ item.label }}
                </h-select-option>
              </h-select>
            </h-form-item>
          </h-col>
          <h-col :span="2" class="app-custom-edit-form-operation">
            <h-form-item>
              <h-button type="link" @click="removeAttr(index)">
                {{ t('platform.common.delete') }}
              </h-button>
            </h-form-item>
          </h-col>
        </h-row>
        <h-form-item>
          <h-button type="dashed" block @click="addAttr">
            <plus-outlined />
            {{ t('platform.common.add') }}
          </h-button>
        </h-form-item>
      </h-form>
    </div>
    <h-divider dashed></h-divider>
    <div>
      <p class="platform-perssionsub-title">
        {{ t('permission.dataPermissionPolicy.dataPermissionPolicy.permissionSub.customAttr') }}
        <h-tooltip placement="right">
          <template #title>
            <span>
              {{
                t(
                  'permission.dataPermissionPolicy.dataPermissionPolicy.permissionSub.customAttrTip',
                )
              }}
            </span>
          </template>
          <ExclamationCircleOutlined class="exclamation-icon" />
        </h-tooltip>
      </p>
      <h-row type="flex" class="table-title-margin app-custom-edit-form-header">
        <h-col flex="1">
          {{
            t('permission.dataPermissionPolicy.dataPermissionPolicy.permissionSub.customAttrName')
          }}
        </h-col>
        <h-col flex="1">
          {{
            t(
              'permission.dataPermissionPolicy.dataPermissionPolicy.permissionSub.customAttrOperation',
            )
          }}
        </h-col>
        <h-col flex="1">
          {{
            t('permission.dataPermissionPolicy.dataPermissionPolicy.permissionSub.customAttrValue')
          }}
        </h-col>
        <h-col flex="70px" class="app-custom-edit-form-operation">
          {{ t('platform.common.operate') }}
        </h-col>
      </h-row>
      <h-form
        class="app-custom-edit-form-body"
        ref="formManageRefCustom"
        name="dynamic_form_nest_item"
        :model="attrValidateForm"
      >
        <h-row type="flex" v-for="(custom, index) in attrValidateForm.custom" :key="custom.key">
          <h-col flex="1">
            <h-form-item
              label=""
              :name="['custom', index, 'field']"
              :rules="[
                {
                  required: true,
                  message: t(
                    'permission.dataPermissionPolicy.dataPermissionPolicy.permissionSub.customAttrNameMsg',
                  ),
                  pattern: '^\\s*(\\S+\\s*)+$',
                  trigger: 'change',
                },
                {
                  message: t(
                    'permission.dataPermissionPolicy.dataPermissionPolicy.permissionSub.customAttrNameMaxLen',
                  ),
                  trigger: 'change',
                  max: 20,
                },
              ]"
            >
              <h-input
                v-model:value="custom.field"
                autocomplete="off"
                :placeholder="t('permission.common.inputPlaceholder')"
              />
            </h-form-item>
          </h-col>
          <h-col flex="1">
            <h-form-item
              label=""
              :name="['custom', index, 'operation']"
              :rules="{
                required: true,
                message: t(
                  'permission.dataPermissionPolicy.dataPermissionPolicy.permissionSub.customAttrOperationMsg',
                ),
                trigger: 'blur',
              }"
            >
              <h-select
                v-model:value="custom.operation"
                :optionLabelProp="null"
                :showSearch="false"
              >
                <h-select-option value="==">==</h-select-option>
                <h-select-option value="!=">!=</h-select-option>
                <h-select-option value=">">></h-select-option>
                <h-select-option value=">=">>=</h-select-option>
                <h-select-option value="<">&lt;</h-select-option>
                <h-select-option value="<=">&lt;=</h-select-option>
                <h-select-option value="like">like</h-select-option>
                <h-select-option value="not like">not like</h-select-option>
              </h-select>
            </h-form-item>
          </h-col>
          <h-col flex="1">
            <h-form-item
              label=""
              :name="['custom', index, 'value']"
              :rules="[
                {
                  required: true,
                  message: t(
                    'permission.dataPermissionPolicy.dataPermissionPolicy.permissionSub.customAttrValueMsg',
                  ),
                  trigger: 'change',
                },
                {
                  message: t(
                    'permission.dataPermissionPolicy.dataPermissionPolicy.permissionSub.customAttrValueMaxLen',
                  ),
                  trigger: 'change',
                  max: 50,
                },
              ]"
            >
              <h-input
                v-model:value="custom.value"
                autocomplete="off"
                :placeholder="t('permission.common.inputPlaceholder')"
              />
            </h-form-item>
          </h-col>
          <h-col flex="85px" class="app-custom-edit-form-operation">
            <h-form-item>
              <h-button type="link" @click="removeCustom(index)">
                {{ t('platform.common.delete') }}
              </h-button>
            </h-form-item>
          </h-col>
        </h-row>

        <h-form-item>
          <h-button type="dashed" block @click="addCustom">
            <plus-outlined />
            {{ t('platform.common.add') }}
          </h-button>
        </h-form-item>
      </h-form>
    </div>
    <h-modal
      ref="mainModal"
      id="AdminMember-queryModal"
      v-model:visible="visibleModal"
      :title="mainModalTitle"
      :cancelText="t('platform.common.cancel')"
      :okText="t('platform.common.save')"
      width="1250px"
      wrap-class-name="full-modal"
      :destroyOnClose="true"
      @ok="handleChildrenOk"
    >
      <permission-pllicy-content
        ref="componentRef"
        :modalParam="modalParam"
        id="AdminMember-queryTransfer"
      />
    </h-modal>
  </h-modal>
</template>
<script lang="ts">
import { defineComponent, ref, reactive, computed, nextTick } 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 PermissionPllicyContent from './Components/PermissionPllicyContent.vue';

export default defineComponent({
  name: 'PermissionSub',
  components: { HModal, PermissionPllicyContent },
  emits: ['permissionSubFunSuccess'],
  setup(_, { emit }) {
    const { t } = useI18n();
    const visible = ref(false);
    const visibleModal = ref(false);
    const mainModalTitle = ref('');
    const permissionSub: any = ref([]);
    const subType: any = ref({}); // 授权客体类型
    const show = (data, params) => {
      visible.value = true;
      nextTick(() => {
        data && (subType.value = data);
        getDataPerObjectPluginItems(params);
      });
    };

    // 初始化数据回显
    const initData = (data = []) => {
      data.map((item, index) => {
        item.key = new Date().getTime() + index;
        return item;
      });
      attrValidateForm.attr = data.filter(item => !item.custom);
      attrValidateForm.custom = data.filter(item => item.custom);
      attrValidateForm.attr.map((item, index) => {
        const etr = permissionSub.value?.find(per => per.value == item.field);
        var evalFun = new Function('return ' + etr.extend);
        const extend = evalFun();
        currentMainExtend.value[index] = extend;
        attrText.value[index] = item.label ? item.label?.split(':')[0] : '';
        if (extend.type == 'pop') {
          subDataList.value[index] = [
            {
              value: item.value,
              label: item.label ? item.label?.split(':')[1] : '',
            },
          ];
        }
        if (extend.type == 'select') {
          handlerSelect();
          if (extend.attr.multible) {
            attrValidateForm.attr[index].value = item.value.split(';');
          }
        }
      });
    };

    const getDataPerObjectPluginItems = async params => {
      const data = await useHttp({
        url: '/api/dataperservice/dataPerService/getDataPerObjectPluginItems',
        method: 'post',
        params: {
          connect: getInfo(ICP_CONFIG)?.connect,
          lang: getInfo(ICP_CONFIG)?.lang,
          companyId: getInfo(ICP_CONFIG)?.companyId,
          objType: subType?.value?.value,
        },
      });
      permissionSub.value = data?.data || [];
      params?.length && initData(params);
    };

    const formManageRefAttr = ref();
    const formManageRefCustom = ref();

    const attrValidateForm = reactive<any>({
      attr: [
        {
          field: '',
          value: '',
          custom: false,
          operation: '==',
          label: '',
          key: new Date().getTime(),
        },
      ],
      custom: [
        // {
        //   field: '',
        //   operation: '',
        //   value: '',
        //   custom: true,
        // },
      ],
    });

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

    const hiddenDeleteCustom = computed(() => {
      return { display: attrValidateForm?.custom?.length <= 1 ? 'none' : 'block' };
    });

    const removeAttr = (index: number) => {
      // if (attrValidateForm.attr.length == 1) {
      //   return;
      // }
      currentMainExtend.value?.splice(index, 1);
      attrText.value?.splice(index, 1);
      subDataList.value?.splice(index, 1);
      attrValidateForm.attr.splice(index, 1);
    };

    const removeCustom = (index: number) => {
      // if (attrValidateForm.custom.length == 1) {
      //   return;
      // }
      attrValidateForm.custom.splice(index, 1);
    };

    const addAttr = () => {
      const len = attrValidateForm.attr?.length;
      attrValidateForm.attr.push({
        field: '',
        value: currentMainExtend.value[len]?.attr?.multible ? [] : '',
        custom: false,
        operation: '==',
        label: '',
        key: new Date().getTime(),
      });
    };

    const addCustom = () => {
      attrValidateForm.custom.push({
        field: '',
        operation: '',
        value: '',
        custom: true,
        key: new Date().getTime(),
      });
    };

    const handleCancel = () => {
      visible.value = false;
      attrValidateForm.attr = [
        {
          field: '',
          value: '',
          custom: false,
          operation: '==',
          label: '',
        },
      ];
      attrValidateForm.custom = [
        // {
        //   field: '',
        //   operation: '',
        //   value: '',
        //   custom: true,
        // },
      ];
    };

    const currentMainExtend: any = ref([]);
    const attrIndex = ref(0);
    const attrText = ref([]);
    // 属性选择 - 客体属性变化使属性值变化
    const attrChange = (id, ind) => {
      const etr = permissionSub.value?.find(item => item.value === id);
      var evalFun = new Function('return ' + etr.extend);
      const extend = evalFun();
      currentMainExtend.value[ind] = extend;
      attrText.value[ind] = getLabel(permissionSub.value, id);
      if (extend.type == 'select') {
        subDataList.value[ind] = [];
        attrValidateForm.attr[ind].value = extend?.attr?.multible ? [] : '';
      }
      if (extend.type == 'pop') {
        //调用方法，1.请空置 2.并且可点击 3.清空下拉数据源
        // attrValidateForm.attr[ind].disabled = false;
        subDataList.value[ind] = [];
        attrValidateForm.attr[ind].value = extend?.attr?.multible ? [] : '';
      }
    };

    // 是否是数组
    const isArray = data => {
      return data instanceof Array;
    };

    // 获取label
    const getLabel = (list = [], id) => {
      let label = '';
      if (isArray(id)) {
        let current = [];
        list?.map(item => {
          if (id.indexOf(item.value) >= 0) {
            current.push(item);
          }
        });
        label = (current?.map(item => item.label) || []).join(';');
      } else {
        const current: any = list.find(item => item.value == id);
        label = current ? current?.label : '';
      }
      return label;
    };

    // 切换属性
    const attrValChange = (id, index) => {
      const label = getLabel(subDataList.value[index], id);
      attrValidateForm.attr[index].label = attrText.value[index] + ':' + label;
    };

    const subDataList = ref([]);
    const getSubValue = async (url, params) => {
      const data = await useHttp({
        url,
        method: 'post',
        params: params,
      });
      if (data.code == 200 && data?.data?.length) {
        subDataList.value[attrIndex.value] = data.data || [];
      }
    };

    //
    const dropdownVisibleChange = (open, ind) => {
      if (open) {
        attrIndex.value = ind;
        getCurrentMainExtend(ind);
        if (currentMainExtend.value[ind]?.type == 'select') {
          handlerSelect();
          return;
        }
        if (currentMainExtend?.value[ind]?.type == 'pop') {
          const id = attrValidateForm.attr[ind]?.value;
          handlePop(currentMainExtend.value[ind], id);
        }
      }
    };

    // 授权客体属性值下拉类型执行参数处理
    const handlerSelect = () => {
      const params = {
        connect: getInfo(ICP_CONFIG)?.connect,
        lang: getInfo(ICP_CONFIG)?.lang,
        companyId: getInfo(ICP_CONFIG)?.companyId,
        ...(currentMainExtend.value[attrIndex.value]?.para?.params || {}),
        objType: subType?.value?.value,
      };
      const url = currentMainExtend.value[attrIndex.value]?.para?.url || '';
      getSubValue(url, params);
    };

    const getCurrentMainExtend = ind => {
      const field = attrValidateForm.attr[ind]?.field;
      const current: any = permissionSub.value.find(item => item.value == field);
      if (current?.extend) {
        var evalFun = new Function('return ' + current.extend);
        const extend = evalFun();
        currentMainExtend.value[ind] = extend;
      } else {
        currentMainExtend.value[ind] = [];
      }
    };

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

    const handlePop = (currentMainExtend, data) => {
      modalParam.params = currentMainExtend;
      modalParam.data = data;
      mainModalTitle.value = currentMainExtend.attr.title;
      // 打开弹窗
      openModal();
    };
    const openModal = () => {
      visibleModal.value = true;
    };

    //数据获取部分
    const componentRef = ref({});
    const handleChildrenOk = async () => {
      const list = (componentRef.value as any).getTableData();
      if (list?.length > 50) {
        message.warning(t('permission.common.selectSubMaxLen'));
        return;
      }
      const idList = (componentRef.value as any).getTableData().join(';');
      const params = {
        connect: getInfo(ICP_CONFIG)?.connect,
        lang: getInfo(ICP_CONFIG)?.lang,
        pluginName: attrValidateForm.attr[attrIndex?.value]?.field,
        value: idList,
        companyId: getInfo(ICP_CONFIG)?.companyId,
      };
      const data = await useHttp({
        url: '/api/dataperservice/dataPerService/getObjectDisplayText',
        method: 'post',
        params: params,
      });
      if (data.code == 200 && data?.data?.length) {
        subDataList.value[attrIndex.value] = data?.data;
        visibleModal.value = false;
        attrValidateForm.attr[attrIndex?.value].value = idList;
        const label = getLabel(data?.data, idList);
        attrValidateForm.attr[attrIndex?.value].label =
          attrText.value[attrIndex?.value] + ':' + label;
        formManageRefAttr.value?.validateFields([['attr', attrIndex?.value, 'value']]);
      }
    };

    const handleOk = () => {
      formManageRefAttr.value.validate().then(() => {
        formManageRefCustom.value.validate().then(async () => {
          const { attr, custom } = attrValidateForm || {};
          let params = [];
          [...(attr || []), ...(custom || [])].map(item => {
            delete item.key;
            params.push({
              ...item,
              value: isArray(item.value) ? item.value.join(';') : item.value,
            });
          });
          const data = await useHttp({
            url: '/api/dataperservice/dataPerService/checkDataPerObjUnique',
            method: 'post',
            params: { data: params },
          });
          if (data.code == 200) {
            emit('permissionSubFunSuccess', params);
            handleCancel();
          } else {
            message.warning(data.msg);
          }
        });
      });
    };
    return {
      t,
      handleOk,
      visible,
      show,
      subType,
      attrValidateForm,
      formManageRefCustom,
      hiddenDelete,
      removeAttr,
      addAttr,
      removeCustom,
      addCustom,
      formManageRefAttr,
      hiddenDeleteCustom,
      handleCancel,
      attrChange,
      permissionSub,
      dropdownVisibleChange,
      subDataList,
      visibleModal,
      mainModalTitle,
      modalParam,
      handleChildrenOk,
      componentRef,
      attrValChange,
      currentMainExtend,
    };
  },
});
</script>
<style lang="less" scoped>
.platform-perssionsub-title {
  font-size: 16px;
  font-weight: bold;
  &::before {
    content: '';
    width: 3px;
    height: 16px;
    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>
