/* eslint-disable prettier/prettier */
import { defineComponent, ref } from "vue";

import PureTable from "@pureadmin/table";
import { pageContentProps } from "./types";
import { TableProBar } from "../../ReTable";
import { onBeforeRouteLeave } from "vue-router";
import { useColumns } from "./hooks/use-columns";
import { useActions } from "./hooks/use-actions";
import { useRequeset } from "./hooks/use-request";
import { useSelection } from "./hooks/use-selection";
import { useRenderIcon } from "../../ReIcon/src/hooks";
import { createActionProps } from "./utils/create-operation";

import { useAppStoreHook } from "/@/store/modules/app";
import { useUserInfo } from "/@/hooks/core/useUser";
import { Operation } from "./actions";
import "./styles/index.scss";

import {
  ElButton,
  ElTooltip,
  ElCheckbox,
  ElScrollbar,
  ElButtonGroup,
  ElCheckboxGroup
} from "element-plus";

const PageContent = defineComponent({
  name: "PageContent",
  props: pageContentProps,
  emits: [
    "createBtnClick",
    "updateBtnClick",
    "statusBtnClick",
    "getContentData",
    "previewBtnClick",
    "selectionChange",
  ],
  setup(props, { expose, emit, slots }) {
    //根据传入的api决定表格需要的操作
    const tableRef = ref<InstanceType<typeof PureTable>>(null);

    const { setSearchParams } = useAppStoreHook();

    const {
      loading,
      dataList,
      onSearch,
      onSearchPro,
      getPageData,
      getBasicParams,
      getPagination,
      onBeforeAction,
      paginationConfig
    } = useRequeset(props);

    const { selects } = useSelection();
    const { action } = useActions(props.contentConfig);
    const { isSuperUser } = useUserInfo();

    const { columns, fixed, displayColumns, _raw, reset } = useColumns(
      props.contentConfig.columns
    );

    function handleSelection(value) {
      selects.value = value;
      emit("selectionChange", value);
    }

    /**
     * 渲染需要的操作按钮
     */
    function renderOperation(row) {
      const { contentConfig } = props;
      const {
        inv,
        apis,
        payProps,
        showStatus,
        notPreview,
        delTooltip,
        showDelete,
        returnProps,
        showPreview,
        showPayTagFn,
        showReturnTagFn,
        showUnPayTagFn,
        showUnReturnTagFn,
        isRequesetArray,
        superUserNoAction,
        superUserNoPerview,
        statusListProp,
        permissions
      } = contentConfig;

      const powers = permissions

      const view = showPreview ? showPreview(row) : true;

      const del = showDelete ? showDelete(row) : true;

      const noAction = (superUserNoAction && !isSuperUser.value) || !superUserNoAction;

      const noPerview =
        (superUserNoPerview && !isSuperUser.value) || !superUserNoPerview;

      const showPay = showPayTagFn ? showPayTagFn(row, powers) : true;
      const showReturn = showReturnTagFn ? showReturnTagFn(row, powers) : true;

      const showUnPay = showUnPayTagFn ? showUnPayTagFn(row, powers) && Number(row.pay_tag_id) !== 0 : false;
      const showUnReturn = showUnReturnTagFn ? showUnReturnTagFn(row, powers) && Number(row.inv_tag_id) !== 0 : false;


      const _showStatus = showStatus
        ? showStatus(isSuperUser.value)
        : action.status &&
        noAction &&
        ((powers.some(i => i == "004") && row[statusListProp || 'status'] + "" === "0") ||
          (powers.some(i => i == "004") && row[statusListProp || 'status'] + "" === "1"));

      return (
        <>
          {!notPreview && view && noPerview && powers.some(i => i == "007") && (
            <Operation.Preview
              isInv={inv}
              onPreview={() => emit("previewBtnClick", row)}
            />
          )}


          {returnProps && noAction && showReturn && (
            <Operation.Tag
              row={row}
              tagProps={returnProps}
              onReload={() => onSearch()}
            />
          )}

          {payProps && noAction && showPay && (
            <Operation.Tag
              row={row}
              tagProps={payProps}
              isPay
              onReload={() => onSearch()}
            />
          )}

          {
            returnProps && showUnReturn && (
              <Operation.UnTag
                row={row}
                tagProps={returnProps}
                onReload={() => onSearch()}
              />
            )
          }

          {
            payProps && showUnPay && (
              <Operation.UnTag
                row={row}
                isPay
                tagProps={payProps}
                onReload={() => onSearch()}
              />
            )
          }

          {action.update && powers.some(i => i == "005") && noAction && (
            <Operation.Update
              onUpdate={() => emit("updateBtnClick", row)}
              {...createActionProps("update", apis)}
            />
          )}

          {_showStatus && (
            <Operation.Status
              row={row}
              prop={contentConfig.statusProp}
              statusRowProp={contentConfig.statusRowProp}
              statusListProp={contentConfig.statusListProp}
              onReload={() => onSearch()}
              isRequesetArray={isRequesetArray}
              {...createActionProps("status", apis)}
            />
          )}

          {del && noAction && action.delete && powers.some(i => i == "006") && (
            <Operation.Delete
              row={row}
              prop={contentConfig.deleteProp}
              delTooltip={delTooltip}
              onReload={() => onSearch()}
              {...createActionProps("delete", apis)}
            />
          )}

          {slots.custom && slots.custom(row)}
        </>
      );
    }

    function renderCreateButton() {
      const { contentConfig } = props;
      const { superUserNoAction, showCreate, permissions } = contentConfig;
      const powers = permissions

      if (((superUserNoAction && isSuperUser.value) || (showCreate && !showCreate(isSuperUser.value)))) {
        return null;
      }

      return (
        (slots.create && slots.create()) ||
        (action.create && powers.some(i => i == "003") && (
          <Operation.Create
            {...createActionProps("create", contentConfig.apis)}
            onCreate={() => emit("createBtnClick")}
          />
        ))
      );
    }

    function renderButtons() {
      return (
        <div style={{ width: '100%', marginBottom: '5px' }}>
          {/* excel导出 */}
          {slots.table_header && slots.table_header()}
          <div class="float-right">
            {slots.header && slots.header()}
            {renderCreateButton()}
          </div>

          <div class="clear-both" />
        </div>
      );
    }

    onBeforeRouteLeave(({ path }) => {
      //到详情页保存查询参数 到其他页面清空查询参数
      const isDetail = path.indexOf("Detail") >= 0;
      const basicParams = isDetail ? getBasicParams() : null;
      const pagination = isDetail ? getPagination() : null;
      setSearchParams(basicParams, pagination);
    });

    const renderExpand = (row) => slots.expand && slots.expand(row)

    function renderFilterColumnns() {
      return (
        <div class="filter-columns__content">
          <div class="filter-columns_reset">
            列筛选
            <ElButton type="text" onClick={() => reset()} size="small">
              重置
            </ElButton>
          </div>

          <ElScrollbar maxHeight={300} size="small">
            <ElCheckboxGroup v-model={displayColumns.value} size="small">
              {_raw.map(({ label, prop, fixed: fixedValue }, index) => {
                if (!label || label === "序号" || label === "z  ") return;
                return (
                  <div class="fixed-group">
                    <ElButtonGroup size="small">
                      <ElTooltip
                        content="固定在左边"
                        placement="top"
                        size="small"
                        disabled={fixedValue === "left"}
                      >
                        <ElButton
                          link
                          size="small"
                          icon={useRenderIcon("arrow-left-s-line")}
                          onClick={() => fixed("left", index)}
                        />
                      </ElTooltip>
                      <ElTooltip
                        content="固定在右边"
                        placement="top"
                        size="small"
                        disabled={fixedValue === "right"}
                      >
                        <ElButton
                          link
                          size="small"
                          icon={useRenderIcon("arrow-right-s-line")}
                          onClick={() => fixed("right", index)}
                        />
                      </ElTooltip>
                    </ElButtonGroup>
                    <ElCheckbox label={prop} key={prop} size="small">
                      {label}
                    </ElCheckbox>
                  </div>
                );
              })}
            </ElCheckboxGroup>
          </ElScrollbar>
        </div>
      );
    }

    function renderPureTable(size, checkList) {
      const { contentConfig } = props;
      const { treeProps, rowKey, isTree, maxHeight, tableRowClassName } = contentConfig;

      return (
        <PureTable
          ref={isTree && tableRef}
          border
          stripe
          defaultExp
          align="left"
          size="small"
          rowKey={rowKey}
          table-layout="auto"
          showOverflowTooltip
          columns={columns.value}
          treeProps={treeProps}
          data={dataList.value}
          checkList={checkList}
          maxHeight={maxHeight ? maxHeight : '660px'}
          paginationSmall={
            size === "small" ? true : false
          }
          rowClassName={tableRowClassName}
          headerCellStyle={{ background: "#fafafa", color: "#606266" }}
          onSelectionChange={handleSelection}
          {...paginationConfig}
          v-slots={{
            operation: ({ row }) => renderOperation(row),
            expand: ({ row }) => renderExpand(row)
          }}
        />
      );
    }

    expose({
      onSearch,
      getPageData,
      getBasicParams,
      onBeforeAction,
      onSearchPro
    });

    return () => {
      const { contentConfig } = props;
      const { title, showTitle } = contentConfig;

      return (
        <TableProBar
          tableRef={tableRef.value?.getTableRef()}
          title={title}
          showTitle={showTitle}
          dataList={dataList.value}
          onRefresh={onSearch}
          loading={loading.value}
          custom
          v-slots={{
            buttons: () => renderButtons(),
            toolbar: () => renderFilterColumnns(),
            default: ({ size, checkList }) => renderPureTable(size, checkList)
          }}
        />
      );
    };
  }
});

export default PageContent;
