<template>
  <div class="main-content main-content-padding" id="ObjectViewer">
    <h-card class="margin-bottom list-query-form">
      <h-b-form
        id="ObjectViewer-queryForm"
        ref="formRef"
        name="use"
        v-bind="formProps"
        @finish="onFinish"
        @reset="onReset"
      />
    </h-card>
    <h-card class="list-table-has-card-head" :title="t('platform.objectViewer.detailTitle')">
      <h-b-pro-table
        id="ObjectViewer-queryTable"
        ref="gridRefOne"
        rowKey="objId"
        :needRowIndex="false"
        :animateRows="false"
        :columns="oneTableColumn"
        :data-source="oneTableData"
        :pagination="false"
        :total="pageState.total"
        :show-size="false"
        :showExport="false"
        :resizable="true"
        :row-selection="false"
        :toolbar="{
          showCustomSetting: false,
          autoColumnWidth: false,
        }"
        :show-title-tip="false"
        :title="t('platform.objectViewer.tableResultTitle')"
      >
        <template #bodyCell="{ record, column }">
          <template v-if="column.dataIndex">
            <h-three-checkbox
              :disabled="true"
              v-model:checked="record[column.dataIndex]"
            ></h-three-checkbox>
          </template>
        </template>
      </h-b-pro-table>
      <h-b-pro-table
        id="ObjectViewer-queryTable"
        ref="gridRefTwo"
        rowKey="EID"
        :columns="twoTableColumn"
        :data-source="twoTableData"
        :needRowIndex="false"
        :animateRows="false"
        :showExport="false"
        :resizable="false"
        :show-size="false"
        :row-selection="false"
        :pagination="false"
        :current="pageState.current"
        :pageSize="pageState.pageSize"
        :custom-cell="customCell"
        :toolbar="{
          showCustomSetting: false,
          autoColumnWidth: false,
        }"
        :show-title-tip="onShowTitleTip"
        :title="t('platform.objectViewer.tableDetailTitle')"
      >
        <!-- :pagination="pageState" -->

        <template #bodyCell="{ column, value }">
          <template
            v-if="
              ![
                'AUTH_SUBJECT',
                'AUTH_SUBJECT_TYPE',
                'DATAPER_NAME',
                'DATAPER_TYPE',
                'EID',
                'EXPIRE_TIME',
              ].includes(column.dataIndex)
            "
          >
            <h-three-checkbox
              v-if="column.dataIndex"
              :disabled="true"
              :checked="value"
            ></h-three-checkbox>
          </template>
          <template v-else>
            {{ value || '-' }}
          </template>
        </template>
      </h-b-pro-table>
      <h-pagination
        v-model:current="pageState.current"
        v-model:pageSize="pageState.pageSize"
        style="margin-top: 30px; justify-content: flex-end; display: flex"
        :total="pageState.total"
        show-size-changer
      >
        <template #buildOptionText="props">
          <span v-if="+props.value <= 500" style="width: 60px; display: inline-block">
            {{ props.value }}条/页
          </span>
          <span v-else style="width: 60px; display: inline-block">全部</span>
        </template>
      </h-pagination>
    </h-card>
  </div>
</template>

<script lang="ts">
import { defineComponent, computed, watch, ref, onBeforeMount, reactive } from 'vue';
import { useRoute } from 'vue-router';
import { useForm } from '@crami/bui-platform';
import { useI18n } from '@crami/locale';
import { commonApi } from '@/api/commonApi/index';
import { getInfo, ICP_CONFIG } from '@/utils/commMethods';
import { useHttp } from '@crami/http';

export default defineComponent({
  name: 'ObjectViewer',
  props: {
    EID: {
      type: String,
    },
    showSearch: {
      type: Boolean,
      default: true,
    },
    tableTitle: {
      type: String,
      default: '',
    },
    listViewName: {
      type: String,
    },
    menuName: {
      type: String,
    },
  },
  setup(props) {
    // 多语言
    const { t } = useI18n();
    const commonParams = computed(() => {
      return getInfo(ICP_CONFIG);
    });

    const route = useRoute();

    watch(
      () => props.EID,
      () => {
        RefreshTable();
      },
    );

    const gridRefOne = ref(null);
    const gridRefTwo = ref(null);

    //第一个表的column和data
    // <Array<customRowData>>
    const oneTableColumn = ref([]);
    // <Array<ontTableData>>
    const oneTableData = ref([{}]);
    //第二个表的column和data
    const twoTableColumn = ref([]);
    const twoTableData = ref([]);

    const pageState = reactive({
      //同current字段内容  组件与后台字段不同
      pageNo: 1,
      current: 1,
      pageSize: 10,
      total: 0,
      showQuickJumper: true,
    });
    let chooseUserId = ref('');
    const definitionIdTaskKeys = ref({});
    // 表格数据的接口
    const getTableData = async () => {
      //获取表单userid
      let formUserId = formMethods.getData().USER_ID?.split(';')[0];
      const res = await useHttp({
        url: '/api/datapermission/dataPer/getDataPerResultInfo',
        method: 'post',
        params: {
          companyId: commonParams.value?.companyId, //租户id
          lang: commonParams.value?.lang,
          connect: 'MYSQL',
          objId: props.EID, //对象ID
          userId: formUserId ? formUserId : commonParams.value?.user_id,
          // 'P_SYS_USER_b51b2a6a14524ab6b1c92a7eb08dd2a7', //用户ID
          definitionIdTaskKeys: definitionIdTaskKeys.value,
          timeZone: commonParams.value?.TIME_ZONE,
          ...pageState,
        },
      });
      const { data, code } = res;
      //异步请求成功进行数据操作
      if (code == 200) {
        //第一个表-----------------
        //赋值表头数据
        oneTableColumn.value = data.authResult;
        //统一配置宽度
        oneTableColumn.value.forEach(ele => {
          switch (ele.dataIndex) {
            case 'ALL':
            case 'WORKFLOW':
              ele.width = 120;
              break;
            case 'PLM_PM_PJ_PERMISSION':
              ele.width = 150;
              break;
            case 'EDIT_PUBLIC':
              ele.width = 180;
              break;
            default:
              ele.width = 100;
              break;
          }
          ele.resizable = true;
        });
        //解析数据数据（筛选出数组值 赋值给另一个数组）
        data.authResult.map(e => {
          oneTableData.value[0][e.dataIndex] = e.value;
        });
        //第二个表-----------------
        //赋值表头数据
        twoTableColumn.value = data.dataPerTitle;
        pageState.total = data.total;

        //统一配置宽度
        twoTableColumn.value.forEach(ele => {
          switch (ele.dataIndex) {
            case 'ALL':
            case 'WORKFLOW':
              ele.width = 120;
              break;
            case 'PLM_PM_PJ_PERMISSION':
              ele.width = 150;
              break;
            case 'EDIT_PUBLIC':
              ele.width = 180;
              break;
            case 'DATAPER_TYPE':
              ele.width = 100;
              break;
            case 'DATAPER_NAME':
              ele.width = 150;

              break;
            case 'AUTH_SUBJECT_TYPE':
              ele.width = 180;

              break;
            case 'EXPIRE_TIME':
              ele.width = 150;

              break;
            case 'AUTH_SUBJECT':
              ele.width = 200;

              break;
            default:
              ele.width = 95;
              break;
          }
          ele.resizable = true;
        });
        //解析数据数据（筛选出数组值 赋值给另一个数组）
        twoTableData.value = data.dataPerInfoList;
        //多选框的值为数组对象内的数组 需要遍历字段到外部结构
        twoTableData.value.forEach((ele, index) => {
          //定义一次循环的obj（item）
          let obj = {};
          //将字段与值得键值对拿出来赋值给obj
          ele.authResult.forEach(element => {
            obj[element.index] = element.value;
            obj[element.index + 'check'] = element.check;
          });
          //将obj合并到外部结构里 绑定twoTableData到table组件
          let itemObj = Object.assign(twoTableData.value[index], obj);
          twoTableData.value[index] = itemObj;
        });
      }
    };

    //监听分页页码参数变化，进行请求
    watch(
      () => pageState.current,
      (newValue, oldValue) => {
        pageState.pageNo = newValue;
        if (newValue != oldValue) {
          getTableData();
        }
      },
    );
    //添加高亮（给字段拼接上'check' 通过字段+check 这个字段判断是否高亮
    const customCell = ({ column, record }) => {
      if (record[column.dataIndex + 'check'] == true) {
        return { style: { background: 'rgb(204 227 237)' } };
      }
    };

    onBeforeMount(() => {
      getProcessTaskNodeInfoWithCurrentUserId();
    });
    // 流程权限判断
    const getProcessTaskNodeInfoWithCurrentUserId = async () => {
      const res = await useHttp({
        url: '/api/platform-base-workflow/workFlowDataPermission/getProcessTaskNodeInfoWithCurrentUserId',
        method: 'post',
        params: {
          objIds: props.EID,
        },
      });

      if (res.code == 200 && res?.data) {
        definitionIdTaskKeys.value = res?.data;
        getTableData();
      }
    };

    const [formRef, formProps, formMethods] = useForm({
      configApi: {
        url: commonApi().studioCache.getMetaInfo.url,
        params: {
          ...commonApi().studioCache.getMetaInfo.params,
          type: 'form_view',
          mode: 'search',
          // name: props.listViewName ? props.listViewName : commonParams.value?.listViewName,
          name: 'P_SYS_DATAPER_USER_VIEW',
        },
        method: commonApi().studioCache.getMetaInfo.method,
      },
      beforeSetData: (type, props) => {
        formMethods.setData({
          USER_ID: commonParams.value?.user_id,
        });
        if (type === 'config') {
          const _props = {
            submitter: {
              isQuery: true,
            },
            column: 1,
          };
          formMethods?.setProps(_props, props);
          formMethods.updateSchema(
            [
              {
                dataIndex: 'USER_ID',
                fieldProps: {
                  dataQueryType: 'company',
                  componentType: 'user',
                  selectMode: 'single',
                },
                width: '33%',
                formItemProps: {
                  // rules: [
                  //   { required: true, message: t('queryConfiguration.common.selectPlaceholder') },
                  // ],
                },
              },
            ],
            props,
          );
        }
        return props;
      },
      immediate: true,
    });

    // 校验完成，提交前
    const onFinish = () => {
      // 获取/刷新data数据
      //组件获取到的数据带有‘；’符号 在这做一下去除
      chooseUserId.value = formMethods.getData().USER_ID.split(';')[0];
      getTableData();
    };

    // 重置
    const onReset = () => {
      RefreshTable();
    };

    // 刷新表格-FunName是从buttonGroup样式接口获取的
    const RefreshTable = () => {
      const refs = formMethods.getFormSchemaRef();
      const formRef2 = refs['USER_ID'];
      formRef2?.setSelectData(commonParams.value?.user_id);
      getTableData();
    };
    const onShowTitleTip = (record, text, showText, column) => {
      if (
        column.dataIndex === 'DATAPER_TYPE' ||
        column.dataIndex === 'DATAPER_NAME' ||
        column.dataIndex === 'AUTH_SUBJECT_TYPE' ||
        column.dataIndex === 'AUTH_SUBJECT'
      ) {
        return showText;
      } else {
        return false;
      }
    };
    return {
      onShowTitleTip,
      formRef,
      formProps,
      gridRefOne,
      gridRefTwo,
      commonParams,
      t,
      onFinish,
      onReset,
      RefreshTable,
      getTableData,
      oneTableColumn,
      twoTableColumn,
      oneTableData,
      twoTableData,
      pageState,
      customCell,
    };
  },
});
</script>
<style lang="less" scoped>
.tableDetailHeightLight {
  padding: 5px 0;
  text-align: center;
  border: 1px solid #1890ff;
  border-radius: 5px;
}
</style>
