<template>
  <div class="main-content main-content-padding flex-content" id="FormList">
    <h-card class="list-tree margin-right width-fixed has-card-head">
      <template #title class="left-title log-service-display">
        {{ t('FormDesign.common.modelList') }}
      </template>
      <h-input-search
        v-model:value="searchValue"
        :placeholder="t('FormDesign.common.searchPlaceholder')"
        style="margin-bottom: 20px"
        @search="onSearch"
      />
      <h-b-card-pane
        v-bind="cardPaneProps"
        ref="cardPaneRef"
        v-model:value="cardVal"
        row-key="value"
        show-key="label"
        align="start"
        defaultFirst
        ellipsis
        itemClassName="appilcation-cell"
        @change="handleChange"
        id="FormList-tabpane"
      ></h-b-card-pane>
    </h-card>
    <div class="width-computed">
      <h-card class="list-table margin-bottom">
        <h-b-pro-table
          showHeaderLine="true"
          id="FormList-queryTable"
          v-bind="tableProps"
          rowKey="EID"
          :title="t('FormDesign.common.listTitle')"
          :needRowIndex="true"
          :show-size="false"
          :showExport="false"
          :row-selection="{
            type: 'checkbox',
            memory: true,
            clickSelectTrigger: 'row',
            unSelectable: true,
          }"
          ref="gridRef"
          size="middle"
          :scroll="{
            y: true,
            extra: 24,
          }"
          :pagination="
            tableProps && tableProps.dataSource && tableProps.dataSource.length
              ? {
                  // 使用showTotal属性不应该加pageNo,pageSize,total属性，不然会有显示bug
                  showSizeChanger: true, // 显示可改变每页数量
                  showQuickJumper: true, //是否可以快速跳转至某页
                  pageSizeOptions: ['10', '20', '50', '100'], // 每页数量选项
                  showTotal: (total, range) =>
                    t('pages.table.pagination', {
                      total,
                      number1: range[0],
                      number2: range[1],
                    }), // 显示总数
                  hideOnSinglePage: false,
                }
              : false
          "
        >
          <!-- 按钮组插槽 -->
          <template #headerContent>
            <h-b-button-group
              v-bind="menuProps"
              ref="menuRef"
              id="FormList-buttonGroup"
              :checkPermission="false"
            />
          </template>
          <!--自定义处理-->
          <template #bodyCell="{ column, record, recordIndexs }">
            <!--  行内操作按钮 -->
            <template v-if="column.dataIndex === 'action'">
              <h-b-button-group
                id="FormList-buttonGroup-inline"
                v-bind="menuPropsTable"
                :checkPermission="false"
                ref="menuRefTable"
                :processButtonGroupData="() => processButtonGroupData(recordIndexs)"
              />
            </template>
            <template v-if="column.dataIndex === 'ISPUBLISH'">
              {{
                record.ISPUBLISH == '是' || record.ISPUBLISH == 'true'
                  ? t('FormDesign.list.published')
                  : t('FormDesign.list.unpublish')
              }}
            </template>
            <!-- <template v-if="column.dataIndex === 'ISMAINVERSION'">
              {{ record.ISMAINVERSION ? t('FormDesign.list.yes') : t('FormDesign.list.no') }}
            </template> -->
          </template>
        </h-b-pro-table>
      </h-card>
    </div>
  </div>
</template>

<script lang="ts">
import {
  computed,
  defineComponent,
  ref,
  createVNode,
  onMounted,
  getCurrentInstance,
  watchEffect,
} from 'vue';
import { useI18n } from '@crami/locale';
import { useCardPane, useProTable, useButtonGroup } from '@crami/bui-platform';
import { useRouter } from 'vue-router';
import { commonApi } from '@remote/icpx-platform/commonApi';
import { HMessage, HModal, Icon, message } from '@crami/ui';
import { useHttp } from '@crami/http';
import { getInfo, ICP_CONFIG } from '@remote/icpx-platform/utils';
import AddApp from './AddApp.vue';
import VersionManagement from './VersionManagement.vue';

import type { IBButtonGroupItem } from '@crami/bui-types';
import { publishTemplate, getModelTemplateNum } from '@/api/platform/form';

let timeout: any;
export default defineComponent({
  name: 'FormList',
  components: {},
  setup() {
    // 多语言
    const { t } = useI18n();
    const searchValue = ref<string>('');
    const { lang, connect, companyId, userId } = getInfo(ICP_CONFIG);

    const commonParams = computed(() => {
      return getInfo(ICP_CONFIG);
    });

    const onSearch = () => {
      const allParam = {
        lang: localStorage.getItem('lang') || 'zhs',
        connect: localStorage.getItem('connect'),
        companyId: localStorage.getItem('companyId'),
        modelFilter: searchValue.value,
      };
      cardPaneMethods.search(allParam, true);
    };
    const searchPlaceholder = t('transfer.searchPlaceholder');
    // 左侧的应用仓库
    const cardVal = ref<string>(''); //p_log_application_2
    const [cardPaneRef, cardPaneProps, cardPaneMethods] = useCardPane({
      configApi: {
        url: '/api/system/modelForm/getAllModels',
        method: 'post',
        params: {
          lang: localStorage.getItem('lang') || 'zhs',
          connect: localStorage.getItem('connect'),
          companyId: localStorage.getItem('companyId'),
          modelFilter: searchValue.value,
        },
        // studioParams: {
        //   ...commonApi().system.getGetOnePageGridDataList.params,
        //   page: 1,
        //   pageSize: 10,
        //   viewName: 'P_LOG_APPLICATIONListView',
        // },
      },
      defaultSelect: 0,
      onErrorSelectDefault: () => {
        console.log('此时左侧树没搜到数据 :>> ');
        cardVal.value = '';
        newJsFun();

        // 没有应用数据的时候重新加载右侧的数据
        // initData();
        // tableMethods.query();
        // tableMethods2.query();
      },
    });
    // 右侧的第一个列表
    const listView = 'P_SYS_CUSTORM_DATAListView'; //右侧列表
    const menuName = 'P_SYS_CUSTORM_DATAMenu'; //自定义路径按钮组
    const objectType = 'P_SYS_CUSTORM_DATA'; //表名
    const [gridRef, tableProps, tableMethods] = useProTable({
      // 表头数据
      configApi: {
        url: commonApi().system.getData.url,
        method: commonApi().system.getData.method,
        params: {
          type: 'gridTitle',
          data: {
            ...commonApi().system.getData.params,
            viewName: listView,
          },
        },
      },
      // 数据接口
      dataSourceApi: {
        url: commonApi().system.getGetOnePageGridDataList.url,
        method: commonApi().system.getGetOnePageGridDataList.method,
        studioParams: {
          ...commonApi().system.getGetOnePageGridDataList.params,
          viewName: listView,
        },
      },
      beforeRequest: (type, params: any) => {
        if (type == 'column') {
          if (params && params.data && typeof params.data == 'object') {
            params.data = JSON.stringify(params.data);
          }
        }
        // const selectKey = methods.getSelectedKeys() || [];
        return {
          ...params,
          showUnder: true,
          filter: [
            {
              andOrFlag: 'AND',
              field: 'MASTERTYPE',
              operation: '=',
              value: cardVal.value,
            },
          ],
        };
      },
      // afterRequest(type, data) {
      //   console.log('menuMethodsTable', menuMethodsTable);
      //   console.log('data', data);
      //   if (data && data.total > 0) {
      //     // 不允许新增
      //     console.log('不能新增');
      //     menuMethodsTable.setButtonLoadingState('CreateP_SYS_CUSTORM_DATA', { loading: false });
      //   }
      // },
      operation: {
        dataIndex: 'action',
        title: t('platform.common.operate'),
        width: 270,
        show: true,
        customSlot: 'action',
        fixed: 'right',
        align: 'left',
      },

      initialLoad: true,
    });

    const [menuRef, menuProps, { getRowMenu }] = useButtonGroup({
      sortRule: 'default',
      computedByNumber: 10,
      pageName: 'FormList',
      menuName: menuName,
      dataSourceApi: {
        url: commonApi().studioCache.getMetaInfo.url,
        params: {
          ...commonApi().studioCache.getMetaInfo.params,
          name: menuName,
          type: 'menuv2',
        },
        method: commonApi().studioCache.getMetaInfo.method,
        dataType: 'json',
      },
    });
    const [menuRefTable, menuPropsTable, menuMethodsTable] = useButtonGroup({
      sortRule: 'computedByNumber',
      computedByNumber: 4,
      pageName: 'FormList',
      //space: 1,
      // items: [],
      moreItem: {
        trigger: ['click'],
      },
    });
    const search = (params: any, refresh?: boolean) => {
      tableMethods.query(params, refresh).then(() => {
        const rowData = getRowMenu('link');
        menuMethodsTable.load(rowData);
      });
    };
    const refreshTable = (refresh?: boolean) => {
      const allParam = {
        filter: [
          {
            andOrFlag: 'AND',
            field: 'MASTERTYPE',
            operation: '=',
            value: cardVal.value,
          },
        ],
      };
      search(allParam, refresh);
    };
    const refreshCurrentPage = () => {
      refreshTable(true);
    };
    const handleChange = value => {
      console.log('左侧树点击得数据 :>> ', value);
      cardVal.value = value;
      newJsFun();
    };
    const router = useRouter();
    const toDesinger = () => {
      const currentItem = gridRef.value?.getSelectedRows()[0];
      if (!currentItem) {
        return;
      }
      const params = { templateId: currentItem.EID };
      // TODO: 修改跳转地址
      const url = `/FormDesigner/${cardVal.value}`;
      router.replace({ path: url, query: params });
    };
    const initData = computed(() => {
      return {
        MASTERTYPE: cardVal.value,
        MODELNAME: cardVal.value,
      };
    });
    const newJsFun = () => {
      refreshCurrentPage();
    };
    // 保存数据
    const saveData = async (page, resolve, mode: string) => {
      const formData = await page.getFormData();
      // 校验失败时会返回false，成功返回表单对象
      if (formData) {
        const result = await useHttp({
          url: '/api/system/model/saveObjectData',
          method: 'post',
          params: {
            type: 'form',
            objectType: objectType,
            productLine: commonParams.value.project,
            productCode: commonParams.value.projectCode,
            data: { ...formData, MASTERTYPE: cardVal.value },
            mode: mode,
            modelName: objectType,
            newObject: mode == 'add' ? true : false,
            objectId: '',
            companyId: companyId || '',
            connect: connect || '',
            userId: userId || '',
            lang: lang || '',
            timeZone: commonParams.value?.TIME_ZONE,
          },
        });
        if (result.code == 200) {
          // HModal.success(result.msg);
          message.success(result.msg);
          newJsFun();
          // cardPaneMethods.search();
          resolve();
        } else {
          // HModal.error(result.msg);
          message.error(result.msg);
        }
      }
    };
    const saveOnOK = (page, resolve) => {
      saveData(page, resolve, 'add');
    };
    const addApp = record => {
      console.log('点击得新建时左侧树得value值 :>> ', cardVal.value);
      // 如果左侧树没有数据，则不允许点击新建（点击新建时提示）
      if (!cardVal.value || cardVal.value == '') {
        HMessage.warning(t('FormDesign.common.noModelData'));
        return;
      }
      const dataSource = tableMethods.getDataSource();
      if (dataSource && dataSource.length > 0) {
        HMessage.warning(t('FormDesign.common.maxCountMsg'));
        return;
      }
      let addAppOptions = {
        title: t('FormDesign.common.add'),
        content: AddApp,
        componentProps: {
          row: record,
          mode: 'add',
          MASTERTYPE: cardVal.value,
        },
        width: 600,
        onOk: saveOnOK,
        okText: t('FormDesign.common.save'),
      };
      HModal.page(addAppOptions);
    };
    // 获取模型中表单模板的数量，判断是否可以删除
    const getDeleteFlag = async () => {
      const data = await getModelTemplateNum(cardVal.value);
      if (data.code === 200) {
        return data.data <= 0;
      } else {
        message.error(data.msg);
        return false;
      }
    };
    //表单有版本后、需要传版本号
    const deleteApp = async () => {
      const selectedDatas = tableMethods.getSelectedDatas();
      if (selectedDatas.length === 0) {
        HMessage.warning(t('FormDesign.common.choose'));
        return;
      }

      const record = selectedDatas[0];
      const canDelete = await getDeleteFlag();
      if (!canDelete) {
        HMessage.warning(t('FormDesign.common.ISENABLE'));
        return;
      }
      HModal.confirm({
        closable: true,
        icon: createVNode(Icon, {
          name: 'icp-exclamation-circle-filled',
          size: 24,
          style: {
            float: 'left',
            marginRight: '8px',
          },
        }),
        title: t('FormDesign.common.deleteTitle'),
        content: t('FormDesign.common.deleteMsg', { count: 1 }),
        onOk() {
          return new Promise(resolve => {
            deleteCodeApi(record.EID);
            resolve(true);
          }).catch(err => console.log('Oops errors!', err));
        },
      });
    };
    const deleteCodeApi = async (eid: string) => {
      const data = await useHttp({
        url: '/api/system/model/deleteObjectData',
        method: 'post',
        params: {
          EIDStr: [eid],
          PageMode: 'DeleteObject', //这个参数有什么意义？
          lang: lang,
          companyId: companyId,
          connect: connect,
        },
      });
      if (data.code === 200) {
        message.success(data.msg);
        newJsFun();
      } else {
        message.error(data.msg);
      }
    };

    // 取消发布
    const unpublish = () => {
      const currentItem = gridRef.value?.getSelectedRows()[0];
      if (timeout) {
        // ladash 方法函数
        clearTimeout(timeout);
        timeout = null;
      }
      function fetchData() {
        publishTemplate(currentItem.EID, false).then(source => {
          if (source.code == 200) {
            refreshTable(false);
          } else if (!source.success) {
            message.error(source.msg);
          }
        });
      }
      timeout = setTimeout(fetchData, 300);
    };
    // 发布
    const publishVersion = () => {
      const currentItem = gridRef.value?.getSelectedRows()[0];

      if (timeout) {
        clearTimeout(timeout);
        timeout = null;
      }
      function fetchData() {
        publishTemplate(currentItem.EID, true).then(source => {
          if (source.code == 200) {
            refreshTable(false);
          } else if (!source.success) {
            message.error(source.msg);
          }
        });
      }
      timeout = setTimeout(fetchData, 300);
    };
    let appContext;
    // 版本管理
    const versionManage = () => {
      let popAuthConfigOptions = {
        title: t('FormDesign.list.versionManage'),
        content: VersionManagement,
        okText: ' ',
        cancelText: ' ',
        componentProps: {
          rows: gridRef.value?.getSelectedRows(),
        },
        width: '60%',
        appContext,
      };
      HModal.promise(popAuthConfigOptions).then(() => {
        refreshTable(false);
      });
    };
    //处理行内按钮的显示
    const processButtonGroupData = recordIndexs => {
      const record = tableProps.dataSource[recordIndexs[0]];
      const items: IBButtonGroupItem = [];
      const buttonData = getRowMenu('link');

      buttonData.forEach(element => {
        if (
          (record.ISPUBLISH == '是' || record.ISPUBLISH == 'true') &&
          element.key !== 'aa758d38'
        ) {
          // 已发布不显示 发布流程 按钮
          items.push(element);
        } else if (
          record.ISPUBLISH !== 'true' &&
          record.ISPUBLISH !== '是' &&
          element.key !== '2d533aee'
        ) {
          // 未发布不显示取消发布按钮 和 表单权限按钮
          items.push(element);
        }
      });
      return items;
    };
    //处理行内操作按钮
    watchEffect(() => {
      const rowData = getRowMenu('link');
      menuMethodsTable.load(rowData);
    });
    onMounted(() => {
      appContext = getCurrentInstance()?.appContext;
    });
    return {
      initData,
      searchValue,
      t,
      onSearch,
      searchPlaceholder,
      cardVal,
      cardPaneProps,
      cardPaneRef,
      handleChange,
      toDesinger,
      gridRef,
      tableProps,
      menuRef,
      menuProps,
      menuRefTable,
      menuPropsTable,
      newJsFun,
      addApp,
      deleteApp,
      versionManage,
      publishVersion,
      unpublish,
      processButtonGroupData,
    };
  },
});
</script>
<style lang="less" scoped>
.list-tree {
  > :deep(.ant-card-body) {
    overflow-y: auto;
    overflow-y: overlay;
  }
}

.list-query-form {
  :deep(.crami-form-bottom-row) {
    border-top: 0 !important;
  }
}

:deep(#LogServiceManagement-queryForm) {
  .ant-form-item {
    margin-bottom: 16px;
  }
}

:deep(#LogServiceManagement-tabpane .hoteam-b-card-pane-item-active) {
  background-color: #e8f0fd !important;
  color: #3979f9 !important;

  .ant-list-item-action {
    z-index: 0;
  }
}

:deep(.appilcation-cell) {
  padding: 14px 16px 14px 24px !important;
}

.log-service-display {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.log-service-add-div {
  width: 16px;
  height: 16px;
  cursor: pointer;
  border-radius: 2px !important;
  margin-top: 2px !important;

  // background-color: #e8f0fd;
  &:hover,
  &:active {
    background-color: #e8f0fd;
  }
}

.log-service-add-icon {
  position: relative;
  top: -3px !important;
  left: 1px !important;
  opacity: 1;

  :hover {
    color: #3979f9;
    opacity: 1;
  }
}

.log-service-drop-icon {
  position: relative;
  top: -1px !important;
  left: 0 !important;
  z-index: 9;
  opacity: 1;
  color: #3979f9;

  :hover {
    color: #3979f9;
    opacity: 1;
  }
}

.log-service-add-drop-down {
  width: 20px;
  height: 20px;
  cursor: pointer;
  border-radius: 2px;
  margin-top: 2px !important;

  // background-color: #e8f0fd;
  &:hover,
  :active {
    background-color: #bfd3f7;
    color: #3979f9 !important;
  }

  z-index: 0;
}
</style>

<style>
.log-service-add-apply-tooltip .ant-tooltip-inner {
  border-radius: 4px;
}
</style>
