<template>
  <div class="main-content-padding margin-bottom" id="TenantAuthorization">
    <h-card class="margin-bottom list-card-form">
      <template #title>
        <span class="icon-back">
          <h-icon name="hoteam-back" :size="40" title="返回" color="#1890ff" @click="goBack">
            返回
          </h-icon>
        </span>

        <span>{{ t('tenant.tenantAuthorization.tenantTitle') }}{{ labelData }}</span>
        <h-divider dashed style="margin: 16px 0" />
        <div class="card-header">
          <div class="card-header-title">
            {{ t('tenant.tenantAuthorization.openHeader') }}
          </div>
          <h-input-search
            class="header-search"
            v-model:value="openText"
            :placeholder="t('tenant.tenantAuthorization.openPlaceHolder')"
            enter-button
            @search="openSearchClick"
            @change="changeOpenClick"
          />
        </div>
      </template>
    </h-card>

    <h-row :gutter="24" class="card-list card-list-authorized">
      <h-col :span="24">
        <!-- 菜单定义-->
        <b-card-list
          id="TenantAuthorization-queryOpenCard"
          class="card-list-item"
          :bordered="cardOptions.bordered"
          :grid="cardOptions.grid"
          :pagination="cardOptions.pagination"
          action-type="link"
          :items="openCardData.items"
          :actions="openCardData.buttonGroupItems"
          @actionClick="actionClick"
        ></b-card-list>
        <!-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
        <!-- <h-list :data-source="cardprops.data" :grid="options.grid">
          <template #renderItem="{ item }">
            <h-list-item>
              <h-b-card-provider
                ref="cardRef"
                :data="item"
                :actions="data.actions"
                :bordered="options.bordered"
                :action-type="'link'"
                @actionClick="actionClick1"
              >
                <template #extraContentTop>
                  <div
                    style="color: #c0c4cc; display: flex; flex-direction: row; align-items: center"
                  >
                    <h-icon
                      :style="{ display: item.date?.iconName ? 'block' : 'none' }"
                      :name="item.date.iconName"
                    ></h-icon>
                    <span class="date-lable">{{ item.date?.label }}:</span>
                    <renewal-app
                      :componentProps="item.date"
                      @click="clickRentDate(item)"
                      @OKbutton="changeRentDate"
                    />
                    <br />
                  </div>
                  <h-divider></h-divider>
                </template>
              </h-b-card-provider>
            </h-list-item>
          </template>
        </h-list> -->
        <!-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
      </h-col>
    </h-row>
    <h-card class="margin-bottom list-card-form">
      <div class="card-header">
        <div class="card-header-title">{{ t('tenant.tenantAuthorization.noOpenHeader') }}</div>
        <h-input-search
          class="header-search"
          v-model:value="nopenText"
          :placeholder="t('tenant.tenantAuthorization.openPlaceHolder')"
          enter-button
          @search="nsearchClick"
          @change="nchangeOpenClick"
        />
      </div>
    </h-card>

    <h-row :gutter="24" class="card-list">
      <h-col :span="24">
        <b-card-list
          id="TenantAuthorization-queryNoOpenCard"
          class="card-list-item"
          :bordered="cardOptions.bordered"
          :grid="cardOptions.grid"
          :pagination="cardOptions.pagination"
          action-type="link"
          :items="nopenCardData.items"
          :actions="nopenCardData.buttonItems"
          @actionClick="actionClick"
        ></b-card-list>
        <!-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
        <!-- <h-list :data-source="cardprops_no.data" :grid="options.grid">
          <template #renderItem="{ item }">
            <h-list-item>
              <h-b-card-provider
                ref="cardRef"
                :data="item"
                :actions="data.actions_no"
                :bordered="options.bordered"
                :action-type="'link'"
                @actionClick="actionClick1"
              >
                <template #extraContentTop>
                  <div
                    style="color: #c0c4cc; display: flex; flex-direction: row; align-items: center"
                  >
                    {{ item.date?.label }}
                    {{ item.date?.value }}
                  </div>
                </template>
              </h-b-card-provider>
            </h-list-item>
          </template>
        </h-list> -->
        <!-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
      </h-col>
    </h-row>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, onActivated, reactive, createVNode } from 'vue';
import { BCardList } from '@crami/bui';
import { HModal, Icon } from '@crami/ui';
import type { IModalPageParams } from '@crami/ui-types';
import { useHttp } from '@crami/http';
import { useRouter } from 'vue-router';
import { CreateApp } from './components/CreateApp';
import { CreateFunction } from './components/CreateFunction';
import { RenewalApp } from './components/RenewalApp';
// import icomDelete from '../../platform/tenantManagement/iconImg/icom-delet.png';
import { useI18n } from '@crami/locale';
import useMonitorLang from '@/utils/hooks/useMonitorLang';

export default defineComponent({
  name: 'TenantAuthorization',
  components: {
    BCardList,
    // RenewalApp,
  },
  setup() {
    const { t } = useI18n();
    const router = useRouter();
    onActivated(() => {
      getTenantInfo();
      getTenantAppData({
        EID: alertInfo.tenantEID,
      });
    });

    let tenantEID = '';
    const openText = ref('');
    const nopenText = ref('');
    const labelData = ref('');
    const alertInfo = {
      appEID: '',
      tenantEID: tenantEID,
      appTitle: '',
      appCode: '',
    };
    const cardOptions = reactive({
      bordered: true,
      pagination: false,
      grid: { gutter: 30, column: 3 },
    });

    const openCardData = reactive({
      items: [],
      buttonGroupItems: [],
    });

    const nopenCardData = reactive({
      items: [],
      // divider:'a',
      buttonItems: [],
    });

    const getTenantInfo = () => {
      const routerParams = router.currentRoute.value.params;
      tenantEID = routerParams.EID as string;
      if (tenantEID !== undefined) {
        localStorage.setItem('tenantAuthorization', tenantEID);
      } else {
        tenantEID = localStorage.getItem('tenantAuthorization') as string;
      }
      alertInfo.tenantEID = tenantEID;
    };

    // 对外提供方法
    const openSearchClick = (event: string) => {
      if (nopenText.value !== '') {
        nopenText.value = '';
      }
      if (event.length == 0) {
        return;
      }
      getTenantAppData({
        EID: alertInfo.tenantEID,
        openedAppName: event,
      });
    };

    const changeOpenClick = () => {
      if (openText.value.length == 0) {
        getTenantAppData({ EID: alertInfo.tenantEID });
      }
    };

    // 对外提供方法
    const nsearchClick = (event: string) => {
      if (openText.value !== '') {
        openText.value = '';
      }
      if (event.length == 0) {
        return;
      }
      getTenantAppData({
        EID: alertInfo.tenantEID,
        unopenedAppName: event,
      });
    };

    const nchangeOpenClick = () => {
      if (nopenText.value.length == 0) {
        getTenantAppData({ EID: alertInfo.tenantEID });
      }
    };

    const getTenantAppData = async (params: any) => {
      const data = await useHttp({
        url: '/api/system/tenant/getAppPermission',
        method: 'post',
        params: params,
      });
      const resultData = data.data;
      // resultData.openedAppData[0].descriptions.itemList = [
      //   { label: '有效期至', content: '2022-05-11' },
      //   { label: '', content: '描述描述描述描述描述描述描述描述描述' },
      // ];
      // resultData.unopenedAppData[0].descriptions.itemList = [
      //   { label: '', content: '描述描述描述描述描述描述描述描述描述' },
      // ];
      if (data.code == 200) {
        console.log(`****`);
        console.log(resultData);
        labelData.value = resultData.tenantName;
        openCardData.items = resultData.openedAppData;
        openCardData.buttonGroupItems = [
          {
            name: 'add',
            text: t('tenant.tenantAuthorization.funcAuth'),
          },
          {
            name: 'time',
            text: t('tenant.tenantAuthorization.term'),
          },
          {
            name: 'remove',
            text: t('tenant.tenantAuthorization.remove'),
          },
        ];
        nopenCardData.items = resultData.unopenedAppData;
        nopenCardData.buttonItems = [
          {
            name: 'open',
            text: t('tenant.tenantAuthorization.openApp'),
          },
        ];
      } else {
        // HMessage.error(data.msg);
      }
    };

    useMonitorLang(() => {
      openCardData.buttonGroupItems = [
        {
          name: 'add',
          text: t('tenant.tenantAuthorization.funcAuth'),
        },
        {
          name: 'time',
          text: t('tenant.tenantAuthorization.term'),
        },
        {
          name: 'remove',
          text: t('tenant.tenantAuthorization.remove'),
        },
      ];
      nopenCardData.buttonItems = [
        {
          name: 'open',
          text: t('tenant.tenantAuthorization.openApp'),
        },
      ];
    });

    onMounted(() => {
      getTenantInfo();
      getTenantAppData({
        EID: alertInfo.tenantEID,
      });
    });

    const getDeepList = (deepList: Array<string | number>, treeData: any[]) => {
      treeData?.forEach(item => {
        if (item?.children?.length) {
          getDeepList(deepList, item.children);
        } else {
          deepList.push(item);
        }
      });
      return deepList;
    };
    const componentRef = ref();
    const formRef = ref();
    const actionClick = (item, index, text) => {
      // const type = event.item.name;
      let title = '';
      alertInfo.appEID = item.id;
      alertInfo.appCode = item.code;
      alertInfo.appTitle = item.descriptions.title;
      let content: any = undefined;
      const modelParams = {
        code: item.code,
        instanceRef: formRef,
      };
      let modelEvent = onOk;

      if (text === t('tenant.tenantAuthorization.funcAuth')) {
        // 功能
        title = item.descriptions.title + '-' + t('tenant.tenantAuthorization.funcAuth');
        content = CreateFunction;
        modelParams['eId'] = tenantEID;
        modelParams['appId'] = item.id;
        modelParams['appName'] = item.descriptions.title;
        modelParams['appCode'] = item.code;
        modelParams['project'] = item.project;
        modelEvent = setFunction;
      } else if (text === t('tenant.tenantAuthorization.term')) {
        // 期限
        title = item.descriptions.title + '-' + t('tenant.tenantAuthorization.serviceTerm');
        content = RenewalApp;
        for (let i = 0; i < item.descriptions.itemList.length; i++) {
          const descItem = item.descriptions.itemList[i];
          if (descItem.label === '有效期至') {
            modelParams['time'] = descItem.content;
            break;
          }
        }
        modelEvent = setTime;
      } else if (text === t('tenant.tenantAuthorization.remove')) {
        // 移除
        title = t('tenant.tenantAuthorization.deleteTitle');
        const options = reactive<IModalPageParams>({
          closable: true,
          width: '448px',
          icon: createVNode(Icon, {
            name: 'icp-exclamation-circle-filled',
            size: 24,
            style: {
              float: 'left',
              marginRight: '8px',
            },
          }),
          title: title,
          content: item.descriptions.title + t('tenant.tenantAuthorization.deleteTipMsg'),
          cancelText: t('tenant.common.cancel'),
          okText: t('tenant.common.ok'),
          onOk: deleteClick,
        });
        HModal.confirm(options);
        return;
      } else if (text === t('tenant.tenantAuthorization.openApp')) {
        // 开通
        title = t('tenant.tenantAuthorization.openApp') + ':' + item.descriptions.title;
        content = CreateApp;
        modelParams['appName'] = item.descriptions.title;
        modelParams['appCode'] = item.code;
        modelParams['project'] = item.project;
      }
      let options = reactive<IModalPageParams>({
        title,
        content: content,
        componentProps: modelParams,
        componentRef: componentRef,
        cancelText: t('tenant.common.cancel'),
        okText: t('tenant.common.ok'),
        onOk: modelEvent,
        onCancel: onCancel,
        width: 700,
      });
      HModal.page(options);
    };

    const deleteClick = () => {
      deleteAppData({ appId: alertInfo.appEID, tenantId: alertInfo.tenantEID });
    };

    const onOk = (data, resovle) => {
      formRef.value
        .validate()
        .then(res => {
          const result = {
            appEID: alertInfo.appEID,
            appECODE: alertInfo.appCode,
            appENAME: alertInfo.appTitle,
            tenantEID: alertInfo.tenantEID,
            expireTime: res.expireTime,
            menuEIDs: res.menuEID.map(item => {
              return item.value;
            }),
          };
          saveAppData(result);
          resovle();
        })
        .catch(err => {
          console.log('error', err);
        });
    };
    const onCancel = () => {};

    const setFunction = (data, resolve) => {
      // return new Promise((resolve, reject) => {
      formRef.value
        .validate()
        .then(res => {
          let menuEIDList = res.menuEID;
          let menuEIDs = [];
          let filterMenuEID = list => {
            for (let item of list) {
              let index = menuEIDList.findIndex(key => key === item.key);
              if (index >= 0) {
                menuEIDs.push(menuEIDList.splice(index, 1)[0]);
                if (!menuEIDList.length) return;
              }
              if (item.children && item.children.length) {
                filterMenuEID(item.children);
              }
            }
          };
          filterMenuEID(data.formTreeList);

          const result = {
            appEID: alertInfo.appEID,
            appECODE: alertInfo.appCode,
            appENAME: alertInfo.appTitle,
            tenantEID: alertInfo.tenantEID,
            menuEIDs,
          };
          saveFunData(result);
          resolve();
        })
        .catch(err => {
          console.log('error', err);
          // reject();
        });
      // });
    };

    const setTime = (data, resolve) => {
      // return new Promise((resolve, reject) => {
      formRef.value
        .validate()
        .then(res => {
          const result = {
            appEID: alertInfo.appEID,
            tenantEID: alertInfo.tenantEID,
            EXPIRETIME: res.expireTime,
          };
          saveTime(result);
          resolve();
        })
        .catch(err => {
          console.log('error', err);
          // reject();
        });
      // });
    };

    const saveAppData = async (params: any) => {
      const result = await useHttp({
        url: '/api/system/tenant/openApp',
        method: 'post',
        params,
      });
      if (result.code === 200) {
        getTenantAppData({
          EID: alertInfo.tenantEID,
        });
      }
    };

    const saveFunData = async (params: any) => {
      const result = await useHttp({
        url: '/api/system/tenant/saveMenuPer',
        method: 'post',
        params,
      });
      if (result.code === 200) {
        getTenantAppData({
          EID: alertInfo.tenantEID,
        });
      }
    };

    const saveTime = async (params: any) => {
      const result = await useHttp({
        url: '/api/system/tenant/retime',
        method: 'post',
        params,
      });
      if (result.code === 200) {
        getTenantAppData({
          EID: alertInfo.tenantEID,
        });
      }
    };

    const deleteAppData = async (params: any) => {
      const result = await useHttp({
        url: '/api/system/tenant/removeApp',
        method: 'post',
        params,
      });
      if (result.code === 200) {
        getTenantAppData({
          EID: alertInfo.tenantEID,
        });
      }
    };

    const goBack = () => {
      router.push({ name: 'TenantManagement' });
    };

    return {
      t,
      openText,
      nopenText,
      cardOptions,
      openCardData,
      nopenCardData,
      labelData,
      // ++++++
      // cardprops,
      // cardprops_no,
      // options,
      // data,
      // actionClick1,
      // clickRentDate,
      // changeRentDate,
      // setTime,
      // ++++++
      getDeepList,
      openSearchClick,
      changeOpenClick,
      nsearchClick,
      nchangeOpenClick,
      actionClick,
      goBack,
    };
  },
});
</script>

<style lang="less" scoped>
.icon-back {
  cursor: pointer;
  padding-right: 10px;
}
#TenantAuthorization {
  background-color: transparent;
  height: 100%;
  .card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .card-header-title {
      font-size: 16px;
      font-weight: 600;
      color: black;
      padding-left: 4px;
    }
    .header-search {
      width: 30%;
      .ant-input-search-button {
        padding: 0 10px;
      }
    }
  }
  //卡片样式
  .card-list {
    margin-left: 0px !important;
    margin-right: 0px !important;
    margin-top: 24px;
    background-color: white;

    border-radius: 8px;
    background-color: transparent;
    .ant-col {
      padding-left: 12px !important;
      padding-right: 12px !important;
      // margin-bottom: 24px !important;
    }
    .ant-col-24 {
      padding-left: 0px !important;
      padding-right: 0px !important;
    }
    .ant-card-body {
      padding: 15px 20px 8px 20px;
    }
    // :deep(.card-list-item) {
    //   padding-left: 15px;
    //   padding-right: 15px;
    // }
    .ant-list-item {
      margin-bottom: 24px;
    }
    .ant-card.ant-card-bordered.ant-card-hoverable {
      height: 148px;
    }
    //卡片标题
    .ant-descriptions-title {
      font-size: 18px;
    }
    .ant-descriptions-header {
      margin-bottom: 8px;
      height: 24px;
    }
    //卡片描述
    .ant-descriptions-item-content {
      color: #999999;
    }
    .ant-descriptions-item-label {
      color: #999999;
    }
    //卡片按钮
    .ant-card-actions {
      width: 100%;
      position: absolute;
      bottom: 0;
      height: 40px;
      border-bottom-left-radius: 8px;
      border-bottom-right-radius: 8px;
      li {
        // margin: 0;
      }
    }
    .ant-btn.ant-btn-link.h-b-card-list-button-style.h-btn-icon.h-b-card-list-button-style {
      margin-top: 4px;
      color: rgba(0, 0, 0, 0.64) !important;
    }
    .ant-btn.ant-btn-link.h-b-card-list-button-style.h-btn-icon.h-b-card-list-button-style:hover {
      color: #3979f9 !important;
    }
  }
  //已开通应用卡片 样式
  .card-list-authorized {
    .ant-card.ant-card-bordered.ant-card-hoverable {
      height: 204px;
    }
    .ant-descriptions-item {
      display: block;
    }
    .ant-descriptions-item:first-child {
      border-bottom: 1px dashed #e9e9e9;
    }
    .ant-descriptions-item {
      padding-top: 10px;
    }
    td:last-child {
      .ant-descriptions-item-content {
        color: #333333;
      }
    }

    //卡片tags
    .hb-card-list-title {
      .hb-card-list-tags {
        position: absolute;
        top: 20px;
        right: 21px;
      }
    }
  }
}
//删除弹窗感叹号
.ant-modal-confirm-body img {
  width: 24px;
  height: 24px;
  float: left;
  margin-right: 10px;
}
</style>
