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

export default {
  data() {
    return {
      id: this.$route.query.id ?? "",
      activeRefresh: true,
      form: {},
      formLoading: false,
      title: "",
      refreshParams: {},
      mechanismsId: "",
      getInfoByIdMethod: {}, //获取表单内容方法
      addOrUpdateInfoMethod: {}, //增改请求方法
      backPath: this.$route.query.backPath, //表单操作完成后返回路径
      // 机构级联选择器配置props
      mechanismsCascaderProp: {
        label: "mechanismsName",
        value: "id",
        children: "children",
        checkStrictly: true, // 是否可以选中任意一级
        emitPath: false, //是否返回选中路径值组成的数组
      },
      // 科室级联选择器配置props
      departmentsCascaderProp: {
        label: "departmentsName",
        value: "id",
        children: "children",
        checkStrictly: true, // 是否可以选中任意一级
        emitPath: false, //是否返回选中路径值组成的数组
      },
      formMultipleKey: [], //form中数据格式为数组的key集合
    };
  },

  mounted() {
    // console.log("this.$route ", this.$route);
    this.title = `${this.$route.meta.name} - ${this.id ? "编辑" : "新增"}`;
    this.getMechanismsId();
  },
  activated() {
    if (this.activeRefresh) {
      this.initOptions();
      if (this.id) this.initInfo(this.refreshParams);
    }
  },
  methods: {
    //获取机构id
    getMechanismsId() {
      // let user = JSON.parse(localStorage.getItem("etm_suserInfo"));
      this.mechanismsId = "836ad594b1de44a09db3ea20ec39c8f6";
    },

    initOptions() {
      return false;
    },

    // 表单初始化数据
    initInfo(getInfoParams) {
      this.form.id = this.id;
      //请求参数默认为id，若传入则以传入参数请求
      if (!getInfoParams) getInfoParams = { id: this.id };
      if (!this.getInfoByIdMethod) return;
      this.formLoading = true;
      this.getInfoById(getInfoParams);
      this.refreshParams = getInfoParams;
    },

    afterInitInfo() {
      return false;
    },

    afterAddOrUpdate() {
      return false;
    },

    beforeAddOrUpdateInfo() {
      return false;
    },

    afterAddOrUpdateFail() {
      return false;
    },

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

    //通过id获取表单内容
    getInfoById(params) {
      this.getInfoByIdMethod({ ...params })
        .then((res) => {
          if (res?.code === 1000) {
            this.form = res.data;
            this.formLoading = false;
            if (this.formMultipleKey.length > 0) {
              this.formMultipleKey.forEach((item) => {
                if (this.form[item]) {
                  this.form[item] = this.form[item].split(",");
                } else {
                  this.form[item] = [];
                }
              });
            }
            this.afterInitInfo();
          } else {
            this.formLoading = false;
            this.$message.error(res.msg);
          }
        })
        .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;
        });
    },

    addOrUpdateInfo: debounce(
      function (params, formName, backParams) {
        // console.log("params1: ", params);
        // console.log('formName: ', formName);
        // return;
        if (!formName) return this.$message.warning("表单ref为空,无法发起校验");
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let paramsCopy = { ...params };
            this.beforeAddOrUpdateInfo(paramsCopy);
            // console.log("paramsCopy: ", paramsCopy);
            if (this.formMultipleKey.length > 0) {
              this.formMultipleKey.forEach((item) => {
                paramsCopy[item] = paramsCopy[item].join(",");
              });
            }
            //参数中值为null时转换为空字符串
            for (let i in paramsCopy) {
              paramsCopy[i] = paramsCopy[i] || "";
            }
            // console.log("params2: ", params);
            // return;
            this.formLoading = true;
            this.addOrUpdateInfoMethod(paramsCopy)
              .then((res) => {
                if (res?.code === 1000) {
                  this.formLoading = false;
                  this.$message.success(this.id ? "修改成功" : "新增成功");
                  this.afterAddOrUpdate() ? this.afterAddOrUpdate() : false;
                  this.id ? false : this.closeTag();
                  this.$router.push({
                    path: this.backPath,
                    query: backParams,
                  });
                } else {
                  this.addOrUpdateInfoFail(res);
                  this.formLoading = false;
                  this.$message.error(`${res.msg},修改失败，请重试！`);
                }
              })
              .catch((err) => {
                this.addOrUpdateInfoCatch();
                this.formLoading = false;
                console.log("err: ", err);
                this.$message.error("网络异常，请重试！");
              });
          }
        });
      },
      200,
      true
    ),

    //新增或修改表单内容
    //params:增改参数，formName：需验证的表单ref
    // addOrUpdateInfo(params, formName, backParams) {
    //   // console.log("params1: ", params);
    //   // console.log('formName: ', formName);
    //   // return;
    //   if (!formName) return this.$message.warning("表单ref为空,无法发起校验");
    //   this.$refs[formName].validate((valid) => {
    //     if (valid) {
    //       let paramsCopy = { ...params };
    //       this.beforeAddOrUpdateInfo(paramsCopy);
    //       // console.log("paramsCopy: ", paramsCopy);
    //       if (this.formMultipleKey.length > 0) {
    //         this.formMultipleKey.forEach((item) => {
    //           paramsCopy[item] = paramsCopy[item].join(",");
    //         });
    //       }
    //       //参数中值为null时转换为空字符串
    //       for (let i in paramsCopy) {
    //         paramsCopy[i] = paramsCopy[i] || "";
    //       }
    //       // console.log("params2: ", params);
    //       // return;
    //       this.formLoading = true;
    //       this.addOrUpdateInfoMethod(paramsCopy)
    //         .then((res) => {
    //           if (res?.code === 1000) {
    //             this.formLoading = false;
    //             this.$message.success(this.id ? "修改成功" : "新增成功");
    //             this.afterAddOrUpdate() ? this.afterAddOrUpdate() : false;
    //             this.id ? false : this.closeTag();
    //             this.$router.push({
    //               path: this.backPath,
    //               query: backParams,
    //             });
    //           } else {
    //             this.addOrUpdateInfoFail(res);
    //             this.formLoading = false;
    //             this.$message.error(`${res.msg},修改失败，请重试！`);
    //           }
    //         })
    //         .catch((err) => {
    //           this.addOrUpdateInfoCatch();
    //           this.formLoading = false;
    //           console.log("err: ", err);
    //           this.$message.error("网络异常，请重试！");
    //         });
    //     }
    //   });
    // },

    addOrUpdateInfoCatch() {
      console.log("addOrUpdateInfoCatch");
      return false;
    },

    addOrUpdateInfoFail(res) {
      return false;
    },

    setCascaderProp(label, value) {
      return {
        label: label,
        value: value,
        children: "children",
        // expandTrigger: "hover",
        // disabled: this.form.mechanismsParent ?? "",
        checkStrictly: true, // 可以选择任意一级
      };
    },

    //不进行校验增改表单内容
    //params:增改参数
    addOrUpdateInfoDirectly(params) {
      this.addOrUpdateInfoMethod({ ...params })
        .then((res) => {
          if (res?.code === 1000) {
            this.$message.success(this.id ? "修改成功" : "新增成功");
            this.afterAddOrUpdate() ? this.afterAddOrUpdate() : false;
            this.$router.push(this.backPath);
          } else {
            this.$message.error(`${res.msg},修改失败，请重试！`);
            this.afterAddOrUpdateFail(res);
          }
        })
        .catch((err) => {
          console.log("err: ", err);
          this.$message.error("网络异常，请重试！");
        });
    },

    //重置表单
    resetForm(formName) {
      if (!formName || typeof formName === "object")
        return this.$message.warning("表单ref不正确,无法重置表单");
      this.$refs[formName].resetFields();
    },

    closeTag() {
      this.$store.dispatch("tagsView/delView", this.$route);
    },
  },
};
