import { defineComponent, ref } from "vue";
import PureTable from "@pureadmin/table";
import { pageContentProps } from "./types";
import { TableProBar } from "../../ReTable";
import { createActionProps, createOperation } from "./utils/create-operation";
import { useRequeset } from "./hooks/use-request";
import { Operation } from "./actions";
import { useSelection } from "./hooks/use-selection";
import { POWERS } from "/@/config/status";
import {
  ElButton,
  ElButtonGroup,
  ElCheckbox,
  ElCheckboxGroup,
  ElScrollbar,
  ElTooltip
} from "element-plus";
import { useColumns } from "./hooks/use-columns";
import { useRenderIcon } from "../../ReIcon/src/hooks";
import "./styles/index.scss";
const powers = POWERS;
const PageConent = defineComponent({
  name: "PageContent",
  props: pageContentProps,
  emits: [
    "createBtnClick",
    "updateBtnClick",
    "previewBtnClick",
    "statusBtnClick",
    "selectionChange",
    "changePwdBtnClick",
    "resetPwdBtnClick",
    "logBtnClick"
  ],
  setup(props, { expose, emit, slots }) {
    //根据传入的api决定表格需要的操作
    const action = createOperation(props.contentConfig.apis);
    // console.log(action);

    const tableRef = ref<InstanceType<typeof PureTable>>(null);

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

    const { selects } = useSelection();

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

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

    /**
     * 渲染需要的操作按钮
     */
    function renderOperation(row) {
      const {
        contentConfig
        // , powers
      } = props;
      const {
        inv,
        apis,
        notPreview,
        delTooltip,
        showPreview,
        showDelete,
        isRequesetArray
      } = contentConfig;

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

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

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

          {slots.custom && slots.custom(row)}

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

          {action.status &&
            ((powers.some(i => i == "003") && row.status + "" === "0") ||
              (powers.some(i => i == "004") && row.status + "" === "1")) && (
              <Operation.Status
                row={row}
                prop={contentConfig.statusProp}
                onReload={() => onSearch()}
                isRequesetArray={isRequesetArray}
                {...createActionProps("status", apis)}
              />
            )}

          {del && action.delete && powers.some(i => i == "006") && (
            <Operation.Delete
              row={row}
              prop={contentConfig.deleteProp}
              delTooltip={delTooltip}
              onReload={() => onSearch()}
              {...createActionProps("delete", apis)}
            />
          )}
          {action.changePwd && powers.some(i => i == "012") && (
            <Operation.ChangePwd
              row={row}
              prop={contentConfig.changePwdProp}
              delTooltip={delTooltip}
              onChangePwd={() => emit("changePwdBtnClick", row)}
              {...createActionProps("changePwd", apis)}
            />
          )}
          {action.resetPwd && powers.some(i => i == "013") && (
            <Operation.ResetPwd
              row={row}
              prop={contentConfig.resetPwdProp}
              delTooltip={delTooltip}
              onResetPwd={() => emit("resetPwdBtnClick", row)}
              {...createActionProps("resetPwd", apis)}
            />
          )}
          {action.log && powers.some(i => i == "022") && (
            <Operation.Log
              row={row}
              prop={contentConfig.logProp}
              delTooltip={delTooltip}
              onLog={() => emit("logBtnClick", row)}
              {...createActionProps("log", apis)}
            />
          )}
        </>
      );
    }

    function renderButtons() {
      const {
        contentConfig
        // , powers
      } = props;
      // const { columns } = contentConfig;

      return (
        <div style={{ display: "flex", gap: "5px" }}>
          {/* excel导出 */}
          {slots.header && slots.header()}
          {(slots.create && slots.create()) ||
            (action.create && powers.some(i => i == "003") && (
              <Operation.Create
                {...createActionProps("create", contentConfig.apis)}
                onCreate={() => emit("createBtnClick")}
              />
            ))}
        </div>
      );
    }

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

    function renderExpand(row) {
      console.log(slots.expand);
      return slots.expand && slots.expand(row);
    }

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

          <ElScrollbar maxHeight={300}>
            <ElCheckboxGroup v-model={displayColumns.value}>
              {_raw.map(({ label, prop, fixed: fixedValue }, index) => {
                if (!label || label === "序号" || label === "操作") return;

                return (
                  <div class="fixed-group">
                    <ElButtonGroup>
                      <ElTooltip
                        content="固定在左边"
                        placement="top"
                        disabled={fixedValue === "left"}
                      >
                        <ElButton
                          link
                          icon={useRenderIcon("arrow-left-s-line")}
                          onClick={() => fixed("left", index)}
                        />
                      </ElTooltip>
                      <ElTooltip
                        content="固定在右边"
                        placement="top"
                        disabled={fixedValue === "right"}
                      >
                        <ElButton
                          link
                          icon={useRenderIcon("arrow-right-s-line")}
                          onClick={() => fixed("right", index)}
                        />
                      </ElTooltip>
                    </ElButtonGroup>
                    <ElCheckbox label={prop} key={prop}>
                      {label}
                    </ElCheckbox>
                  </div>
                );
              })}
            </ElCheckboxGroup>
          </ElScrollbar>
        </div>
      );
    }

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

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

    expose({
      onSearch,
      getPageData,
      onBeforeAction
    });

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

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

export default PageConent;
