<template>
  <!-- :title="isDetail ? title.detail : !dataForm.id ? title.add : title.edit" -->
  <el-dialog
    class="a-small-dialog"
    :visible.sync="visible"
    @close="handleClose"
    :distory-on-close="true"
    :close-on-click-modal="false"
    v-bind="$attrs"
    :width="'30%'"
    :modal="false"
    :fullscreen="false"
    :top="'10vh'">
    <!-- :append-to-body="appendToBody"> -->
    <div v-loading="loading">
      <el-form ref="dataForm" :model="dataForm">
        <el-row v-for="(row, rowIndex) in configs.rows" :key="'row_' + rowIndex" :gutter="20">
          <el-col v-for="(col, colIndex) in row" :key="colIndex" :span="col.span ?? 24 / row.length">
            <el-form-item :prop="col.prop" :rules="col.rules || null" :label="col.label">
              <el-input
                v-if="col.input"
                v-model="dataForm[col.prop]"
                clearable
                :disabled="detailMode"
                v-bind="col.elparams" />
              <el-select
                v-if="col.select"
                v-model="dataForm[col.prop]"
                clearable
                :disabled="detailMode"
                v-bind="col.elparams"
                @change="handleSelectChange(col, $event)">
                <el-option
                  v-for="(opt, optIdx) in col.options"
                  :key="'option_' + optIdx"
                  :label="opt.label"
                  :value="opt.value">
                  <span>{{ opt.label }}</span>
                  <span v-if="col.customLabel" style="display: inline-clock; margin-left: 12px; font-size: 0.9em">
                    {{ opt[col.customLabel] || "-" }}
                  </span>
                </el-option>
              </el-select>
              <el-switch
                v-if="col.switch"
                v-model="dataForm[col.prop]"
                :active-value="1"
                :inactive-value="0"
                @change="handleSwitchChange"
                :disabled="detailMode" />
              <el-input
                v-if="col.textarea"
                type="textarea"
                v-model="dataForm[col.prop]"
                :disabled="detailMode"
                v-bind="col.elparams" />
              <!-- add more...  -->
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- footer  -->
    <div slot="footer">
      <template v-for="(operate, index) in configs.operations">
        <el-button
          v-if="showButton(operate)"
          :key="'operation_' + index"
          :type="operate.type"
          @click="handleBtnClick(operate)"
          :loading="(operate.name === 'add' || operate.name === 'update') && btnLoading">
          {{ operate.label }}
        </el-button>
      </template>
      <el-button @click="handleBtnClick({ name: 'cancel' })">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
// import CKEditor from 'ckeditor4-vue'
// import AttrForm from './AttrForm'
// import { pick } from 'lodash/object'
import { pick as __pick } from "@/utils/filters";
// import i18n from '@/i18n'

export default {
  name: "SmallDialog",
  props: {
    configs: {
      type: Object,
      default: () => ({}),
    },
    relatedId: {
      type: String,
      default: "",
    },
  },
  inject: ["urls"],
  data() {
    const dataForm = {};
    this.configs.rows.forEach((row) => {
      row.forEach((col) => {
        dataForm[col.prop] = col.default ?? "";
        //console.log("[small dialog]==========>", col.prop, dataForm[col.prop]);

        if (typeof col.fetchData === "function")
          col.fetchData().then(({ data: res }) => {
            if (res.code === 0) {
              this.$set(
                col,
                "options",
                !col.customLabel
                  ? res.data.list.map((item) => ({ label: item[col.optionLabel ?? "name"], value: item.id }))
                  : res.data.list.map((item) => ({
                      label: item[col.optionLabel ?? "name"],
                      value: item.id,
                      [col.customLabel]: item[col.customLabel],
                    }))
              );
              //console.log(
                // res.data.list.map((item) => ({
                //   label: item.name,
                //   value: item.id,
                //   [col.customLabel]: item[col.customLabel],
                // }))
              // );
            } else {
              this.$set(col, "options", []);
            }
          });
      });
    });

    return {
      loading: false,
      btnLoading: false,
      visible: false,
      detailMode: false,
      dataForm,
      dataFormRules: {},
      tempForm: [], // 临时保存自动生成的code，或其他数据
    };
  },
  methods: {
    /** utitilities */
    showButton(operate) {
      const notDetailMode = !this.detailMode;
      const showAlways = operate.showAlways ?? false;
      const editMode = operate.showOnEdit && this.dataForm.id;
      const addMode = !operate.showOnEdit && !this.dataForm.id;
      const permission = operate.permission ? this.$hasPermission(operate.permission) : true;
      return notDetailMode && (showAlways || ((editMode || addMode) && permission));
    },
    resetForm(excludeId = false) {
      setTimeout(() => {
        Object.keys(this.dataForm).forEach((key) => {
          // //console.log(">>> clearing key: ", key);
          if (excludeId && key === "id") return;
          this.dataForm[key] = null;
        });
        this.detailMode = false;
      }, 500);
    },

    init(id, isdetail = false) {
      // //console.log("[small dialog] init", id, isdetail);
      this.visible = true;

      this.detailMode = isdetail;
      if (this.$refs.dataForm) this.$refs.dataForm.clearValidate();

      this.$nextTick(() => {
        // this.$refs['dataForm'].resetFields();
        this.dataForm.id = id || null;

        if (this.dataForm.id) {
          // 如果是编辑
          this.loading = true;
          this.$http
            .get(this.urls.subase + `/${this.dataForm.id}`)
            .then(({ data: res }) => {
              if (res && res.code === 0) {
                const dataFormKeys = Object.keys(this.dataForm);
                this.dataForm = __pick(res.data, dataFormKeys);
              } else {
                throw new Error(res.msg);
              }
              this.loading = false;
            })
            .catch((err) => {
              this.loading = false;
              this.$message.error(err.message);
            });
        }
      });
    },

    handleSelectChange(col, event) {},
    handleSwitchChange() {},

    handleBtnClick(payload) {
      //console.log("btn click payload: ", payload);
      //console.log("configs", this.configs);
      if ("name" in payload) {
        switch (payload.name) {
          case "cancel":
            this.handleClose();
            break;
          case "add":
          case "update": {
            this.$refs.dataForm.validate((passed, result) => {
              if (passed) {
                this.btnLoading = true;
                //console.log("update extraParam: ", this.configs.extraParam);
                const method = payload.name === "add" ? "POST" : "PUT";

                const fields = {};
                fields[this.configs.extraParam] = this.relatedId;
                // [this.configs.extraParam]: this.relatedId,  // this.configs.extraParam 只能是字符串
                if (this.configs.forceAttachCode) fields["code"] = "";

                this.$http({
                  url: this.urls.subase,
                  method,
                  data: {
                    ...this.dataForm,
                    ...fields,
                  },
                }).then(({ data: res }) => {
                  //console.log("[add&update] res is: ", res);
                  this.btnLoading = false;
                  if (res.code === 0) {
                    this.$message.success(payload.name === "add" ? "添加成功" : "更新成功");
                    this.$emit("refreshDataList");
                    this.handleClose();
                  } else this.$message.error(res.msg);
                });
              }
            });
          }
        }
      } else {
        //console.log("[x] 不是这么用的! 缺少name属性");
      }
    },

    handleClose() {
      this.resetForm();
      this.visible = false;
    },
  },
};
</script>

<style scoped>
.a-small-dialog >>> .el-dialog {
  border-radius: 8px;
  box-shadow: 0 0 8px 2px rgba(0, 0, 0, 0.2);
}

.a-small-dialog >>> .el-select {
  width: 100%;
}
</style>
