<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"
                :placeholder="t('permission.common.selectPlaceholder')"
                :getPopupContainer="getPopupContainer"
                @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'],
              }"
            >
              <template v-if="currentMainExtend[index]?.type == 'pop'">
                <HBCustomSelect
                  v-model:value="attr.value"
                  valueType="string"
                  :labelInValue="true"
                  :componentType="currentMainExtend[index]?.attr?.componentType"
                  :dataQueryType="currentMainExtend[index]?.attr?.dataQueryType"
                  :selectShowMaxLength="3"
                  :showSearch="false"
                  :open="false"
                  :notFoundContent="null"
                />
              </template>
              <template v-else>
                <h-select
                  v-model:value="attr.value"
                  :mode="
                    currentMainExtend[index]?.type == 'select' &&
                    currentMainExtend[index]?.attr?.multible
                      ? 'multiple'
                      : ''
                  "
                  :getPopupContainer="getPopupContainer"
                  :optionLabelProp="null"
                  :showSearch="false"
                  :placeholder="t('permission.common.selectPlaceholder')"
                  @change="data => attrValChange(data, index)"
                >
                  <h-select-option
                    v-for="(item, ind) in subDataList[index]"
                    :key="ind"
                    :value="item.value"
                  >
                    {{ item.label }}
                  </h-select-option>
                </h-select>
              </template>
            </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"
                :placeholder="t('permission.common.selectPlaceholder')"
                :getPopupContainer="getPopupContainer"
              >
                <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>
</template>
<script lang="ts">
import { defineComponent, ref, reactive, computed, nextTick } from 'vue';
import { HModal, message } from '@crami/ui';
import { getInfo, ICP_CONFIG } from '@remote/icpx-platform/utils';
/* import { getInfo, ICP_CONFIG } from '@/utils/commMethods'; */
import { useHttp } from '@crami/http';
import { useI18n } from '@crami/locale';

export default defineComponent({
  name: 'PermissionSub',
  components: { HModal },
  emits: ['permissionSubFunSuccess'],
  setup(_, { emit }) {
    const { t } = useI18n();
    const visible = ref(false);
    const visibleModal = ref(false);
    const mainModalTitle = ref('');
    const permissionSub: any = ref([]);
    const attrIndex = ref(0);
    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 = JSON.parse(JSON.stringify(data.filter(item => !item.custom)));
      attrValidateForm.custom = JSON.parse(JSON.stringify(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') {
          const labels = item.label ? item.label?.split(':')[1] : '';
          const labelArr = labels && labels.split(';');
          const valuesArr = item.value && item.value.split(';');
          let popSelectData = [];
          valuesArr.map((val, ind) => {
            popSelectData.push({
              value: val,
              label: labelArr[ind] || '',
            });
          });
          attrValidateForm.attr[index].value = popSelectData;
        }
        if (extend.type == 'select') {
          handlerSelect(extend, index + '');
          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: null,
          value: null,
          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: null,
        value: currentMainExtend.value[len]?.attr?.multible ? [] : null,
        custom: false,
        operation: '==',
        label: '',
        key: new Date().getTime(),
      });
    };

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

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

    const currentMainExtend: any = ref([]);
    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);
      attrIndex.value = ind;
      if (extend.type == 'select') {
        subDataList.value[ind] = [];
        attrValidateForm.attr[ind].value = extend?.attr?.multible ? [] : '';
        // 调用属性值接口获取数据
        handlerSelect(extend);
      }
      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, isInit?) => {
      const data = await useHttp({
        url,
        method: 'post',
        params: params,
      });
      if (data.code == 200 && data?.data?.length) {
        subDataList.value[isInit ? isInit : attrIndex.value] = data.data || [];
      }
    };

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

    // 使用定制选择器下的处理方式
    const getLabelOrValue = (data, type, index?) => {
      let value = '';
      data?.value?.map(item => {
        if (typeof item == 'string') {
          value = value ? value + ';' + item : item;
        } else {
          value = value ? value + ';' + item[type] : item[type];
        }
      });
      return type == 'label' ? attrText.value[index] + ':' + value : value;
    };

    const handleOk = () => {
      formManageRefAttr.value.validate().then(() => {
        formManageRefCustom.value.validate().then(async () => {
          const { attr, custom } = attrValidateForm || {};
          const allData = JSON.parse(JSON.stringify([...(attr || []), ...(custom || [])]));
          let params = [];
          allData.map((item, index) => {
            delete item.key;
            let newItem = {
              ...item,
              value: isArray(item.value) ? getLabelOrValue(item, 'value') : item.value,
            };
            if (!item.custom) {
              newItem = {
                ...newItem,
                label: isArray(item.value)
                  ? item.value.some(i => typeof i == 'string')
                    ? item.label
                    : getLabelOrValue(item, 'label', index)
                  : item.label,
              };
            }
            params.push(newItem);
          });
          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);
          }
        });
      });
    };
    const getPopupContainer = triggerNode => {
      return triggerNode.parentNode || document.body;
    };
    return {
      t,
      handleOk,
      visible,
      show,
      subType,
      attrValidateForm,
      formManageRefCustom,
      hiddenDelete,
      removeAttr,
      addAttr,
      removeCustom,
      addCustom,
      formManageRefAttr,
      hiddenDeleteCustom,
      handleCancel,
      attrChange,
      permissionSub,
      subDataList,
      visibleModal,
      mainModalTitle,
      attrValChange,
      currentMainExtend,
      getPopupContainer,
    };
  },
});
</script>
<style lang="less" scoped>
@import '@/theme/default/variables.less';
.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>
