import uploadAPI from "@/api/upload";
import global from "@/config/global";
import { method } from "lodash";
import { getAsyncData } from "@/utils/asyncRequest";

export default {
  data() {
    return {
      form: {},
      formLoading: false,
      activeRefresh: true,
      listData: [], //列表数据
      mechanismsId: "", //机构id
      listMethod: {}, //列表刷新方法
      deleteMethod: {}, //删除列表项方法
      limitParams: {}, //列表请求限制参数
      total: 0,
      currentPage: 1,
      pageSize: 10,
      searchForm: {}, //搜索框表单对象
      deleteWarnText: "确认删除？", //删除提示语
      tableLoading: true,
      searchFormMultipleKey: [], //searchForm中数据格式为数组的key集合
    };
  },
  mounted() {
    this.getMechanismsId();
  },
  activated() {
    // 在首次挂载、
    // 以及每次从缓存中被重新插入的时候调用
    if (this.activeRefresh) {
      this.init();
    }
  },
  methods: {
    getAsyncData, //返回各种请求数据,使用时要配合async、await
    //获取机构id
    getMechanismsId() {
      let user = JSON.parse(localStorage.getItem("mh_userInfo"));
      // this.mechanismsId = user.mechanismsId;
      this.mechanismsId = "836ad594b1de44a09db3ea20ec39c8f6";
    },

    //获取列表数据
    //listMethod:列表刷新方法，params：列表刷新请求参数
    getTableList(listMethod, params) {
      //获取列表数据成功后赋值listData和total
      listMethod({
        ...params,
        ...this.limitParams,
        pageSize: this.pageSize,
        currentPage: this.currentPage,
      })
        .then((res) => {
          if (res?.code === 1000) {
            this.listData = res.data.list;
            this.total = res.data.total;
          }
          this.afterInit();
          this.tableLoading = false;
        })
        .catch((err) => {
          this.tableLoading = false;
          console.log("err: ", err);
          this.$message.error("网络错误");
        });
    },

    //通过id获取列表中的单条数据
    //listMethod:列表刷新方法，params：列表刷新请求参数
    getTableListById(listMethod, params) {
      //获取列表数据成功后赋值listData和total
      this.formLoading = true;
      listMethod({
        ...params,
        ...this.limitParams,
        pageSize: this.pageSize,
        currentPage: this.currentPage,
      })
        .then((res) => {
          if (res?.code === 1000) {
            if (res.data.list && res.data.list.length) {
              this.form = res.data.list[0];
              this.formLoading = false;
            } else {
              this.formLoading = false;
              this.afterInitInfo();
            }
          } else {
            this.formLoading = false;
            this.$message.error(res.msg);
            this.afterInitInfo();
          }
        })
        .catch((err) => {
          this.formLoading = false;
          console.log("err: ", err);
          this.$message.error("网络异常，请重试！");
        });
    },

    //返回各种列表请求数据,使用时要配合async、await
    getList(method, params) {
      return method({ ...params })
        .then((res) => {
          // console.log(res);
          if (res?.code === 1000) {
            return res.data;
          } else {
            this.$message.error("获取列表失败!");
            return false;
          }
        })
        .catch((err) => {
          console.log("err: ", err);
          this.$message.error("网络错误");
          return false;
        });
    },

    //删除列表项
    //id:删除目标id,deleteWarnText:删除成功提示语
    //deleteMethod:删除项方法,listMethod:刷新列表方法
    deleteListItemById(deleteId) {
      this.$confirm(this.deleteWarnText, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.deleteMethod({ id: deleteId })
            .then((res) => {
              if (res?.code === 1000) {
                this.$message.success("删除成功");
                this.getTableList(this.listMethod);
              } else {
                this.$message.error(res.msg);
              }
            })
            .catch((err) => {});
        })
        .catch(() => {});
    },

    //跳转添加界面
    //pathName:跳转路由名称，query:跳转携带内容，backPath：表单修改成功后路由返回路径
    toInfo(pathName, query, backPath) {
      //query不为对象则说明第二个参数为空或返回路径
      let isQuery = Object.prototype.toString.call(query) == "[object Object]";
      //backPath为空时，默认当前列表页
      backPath = backPath ?? this.$route.name;
      //当第二个参数为路由返回路径时，将值赋给backPath，query置空
      if (!isQuery && !!query && !backPath) {
        backPath = query;
        query = {};
      }
      this.$router.push({
        name: pathName,
        query: { ...query, backPath: backPath },
      });
    },

    //表格条数变化
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.init(this.handleSearchForm(this.searchForm));
    },

    //表格页数变化
    handleCurrentChange(val) {
      this.currentPage = val;
      this.init(this.handleSearchForm(this.searchForm));
    },

    //搜索框查询
    searchByForm(form) {
      this.searchForm = form;
      // console.log("submit", form, JSON.stringify(form));
      // console.log('this.searchData: ', this.searchData);
      let isSearch = true;
      isSearch = this.beforeSearch(form);
      let params = this.handleSearchForm(form);
      this.currentPage = 1;
      this.pageSize = 10;
      // return;
      this.init({
        ...params,
        currentPage: this.currentPage,
        pageSize: this.pageSize,
      });
    },

    beforeSearch(form) {
      return true;
    },

    handleSearchForm(form) {
      let result = {};
      if (JSON.stringify(form) !== "{}") {
        for (let i in form) {
          if (typeof form[i] === "object") {
            result[i] = !form[i] ? form[i] : form[i].join(",");
          } else {
            result[i] = form[i] ? form[i] : null;
          }
        }
      }
      return result;
    },

    //列表项value转换label，
    // val：该项值 ， attBuName：该项值的属性名 ， target：匹配项label的属性名 ，targetList：匹配的列表
    valueToLabel(val, attBuName, target, targetList) {
      // console.log('targetList: ', targetList);
      let result = {};
      if (targetList && targetList.length > 0) {
        result = targetList.find((item) => item[attBuName] === val);
      }
      return !result ? "" : result[target];
    },

    init(params) {
      if (!!params && JSON.stringify(params) !== "{}") {
        for (let i in params) {
          // console.log(i, params[i]);
          if (!params[i] || JSON.stringify(params[i]) === "[]")
            delete params[i];
        }
      }
      // console.log("params: ", params);
      this.getTableList(this.listMethod, params ?? {});
    },

    initById(params) {
      this.getTableListById(this.listMethod, params ?? {});
    },
    afterInit() {
      return false;
    },
    afterInitInfo() {
      return false;
    },
  },
};
