import { debounce } from "lodash";
import * as api from "@/api/pageSearch.js";
//
export default {
  data() {
    return {
      dataList: [],
      total: 0,
      pageIndex: 1,
      pageSize: 10,
    };
  },
  props: {
    //请求地址
    url: {},
    method: {
      type: String,
      default: "post",
    },
    urlExport: {},
    //请求参数
    searchData: {},
    //是否手动查询
    manual: {
      type: Boolean,
      default: false,
    },
    //是否分页
    pageable: {
      type: Boolean,
      default: true,
    },
    beforeSearchCheck: {
      type: Function,
      default: function (callback) {
        //   console.info("beforeSearchCheck default function")
        return true;
      },
    },
  },
  watch: {
    url: "search",
    pageSize: "search",
    searchData: {
      deep: true,
      handler: debounce(
        function () {
          if(!this.manual){
            this.search();
          }         
        },
        300,
        { leading: true }
      ),
    },
  },
  methods: {
    /**
     * 重新搜索
     */
    search() {
      console.log("this.searchData",this.searchData)
      let checkResult = this.beforeSearchCheck(this.searchData);
      // console.info("search" ,checkResult)
      if (!checkResult) return;
      this.pageIndex = 1;
      this.load(this.searchData);
    },

    /**
     * 重新刷新当页
     */
    refresh() {
      this.load(this.searchData);
    },

    /**
     * 请求数据
     * @param params
     */
    async load(params) {
      // debugger
      params = params || {};
      params.pageNum = this.pageIndex<1?1:this.pageIndex;
      params.pageSize = this.pageSize;
      console.log(params);

      let data;
      // debugger
      if (this.method === "post") {
        data = await api.post(this.url, params);
      } else {
        data = await api.get(this.url, params);
      }
      // this.selectItemList=[];
      // this.selectItemList=[];
      // this.$emit("select", []);
      // this.$emit("select-all", []);
      // this.$emit("handleSelectionChange", []);
      this.$emit("load", data);
      if(data.data){
        data=data.data
      }
      if (data.length) {
        this.dataList = this.checkSelect(data);
        this.total = data.length;
      } else if(data.data){
        this.dataList = this.checkSelect(data.data);
        this.total = this.dataList.length;
      }
      else{
        this.dataList = this.checkSelect(data.rows);
        this.total = data.total;
      }
      this.$emit("totalCount", this.total);
    },

    /**
     * 页数变动
     * @param page
     */
    onPageChange(page) {
      this.pageIndex = page;
      this.load(this.searchData);
    },

    /**
     * 分页大小变动
     * @param s
     */
    onSizeChange(s) {
      this.size = s;
      this.pageIndex = 1;
      this.search();
    },

    /**
     * 排序
     */
    onSort({ prop, order }) {
      this.$set(this.searchData, "sortList", [{ column: prop, desc: order }]);
    },
  },
};
