<template>
  <!-- 小型弹窗，用于完成，删除，保存等操作 -->
  <el-dialog class="l-dialog" :class="lDialog" :title="title" :visible.sync="dialogVisible" :showClose="true"
             :closeOnClickModal="false" @close="handleClose" :append-to-body="true">
    <div>
      <el-form :model="form" :rules="rules" ref="ruleForm" label-width="120px" :disabled="disabled">
        <el-form-item label="自定义分类名称" prop="customizeClassifyName">
          <el-input class="form-item" v-model="form.customizeClassifyName" clearable show-word-limit
                    placeholder="请输入自定义分类名称" maxlength="64" :disabled="disabled"></el-input>
        </el-form-item>
        <el-form-item label="分类描述" prop="classifyDesc">
          <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 6 }" class="form-item"
                    v-model="form.classifyDesc" clearable show-word-limit placeholder="请输入分类描述" maxlength="255" :disabled="disabled"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer" v-if="!disabled">
            <el-button class="clear-btn" @click="handleClose">取消</el-button>
            <el-button type="primary" class="search-btn"
                       @click="submitForm('ruleForm')">确认</el-button>
        </span>
  </el-dialog>
</template>
<script>
import _ from 'lodash'
import {
  addKyFilesCustomizeClassifyAPI,
  updateKyFilesCustomizeClassifyAPI,
} from '@/api/archivesManagement/archCustomClassification'
export default {
  name: "CustomizeForm",
  props: ["width", "dataForm", "title", "disabled", "isAdd", "rowData"],
  dicts: ['dimension'],
  data() {
    return {
      lDialog: this.width > 500 ? "w700" : "w500",
      dialogVisible: true,
      isDisabled: true,
      form: {
        customizeClassifyName: null,
        classifyDesc: null,
      },
      loading: null,
      rules: {
        customizeClassifyName: [
          { required: true, message: '自定义分类名称不能为空', trigger: 'blur' }
        ],
      },
      errorObj: {
        customizeClassifyName: '自定义分类名称',
        classifyDesc: '分类描述',
      },
    };
  },
  watch: {
    // 监听 rowData 变化，确保数据正确回显
    rowData: {
      handler(newVal) {
        if (newVal) {
          this.initFormData();
        }
      },
      immediate: true,
      deep: true
    },
    // 监听 disabled 变化，确保详情模式正确禁用
    disabled: {
      handler(newVal) {
        if (newVal) {
          // 在详情模式下，清空验证规则避免干扰显示
          this.rules = {};
        } else {
          // 非详情模式恢复验证规则
          this.rules = {
            customizeClassifyName: [
              { required: true, message: '自定义分类名称不能为空', trigger: 'blur' }
            ],
          };
        }
      },
      immediate: true
    }
  },
  created() {
    this.initFormData();
  },
  methods: {
    /** 初始化表单数据 */
    initFormData() {
      if ((this.isAdd === 'edit' || this.isAdd === 'detail') && this.rowData) {
        // 编辑模式或详情模式：填充表单数据
        this.form = {
          customizeClassifyName: this.rowData.customizeClassifyName || '',
          classifyDesc: this.rowData.classifyDesc || '',
          id: this.rowData.id || null,
        };
      } else {
        // 新增模式：重置表单
        this.form = {
          customizeClassifyName: null,
          classifyDesc: null,
        };
      }
    },
    /*关闭弹窗 */
    handleClose() {
      this.dialogVisible = false;
      this.$emit("closeDialog");
    },
    /**确认弹窗 */
    sureBtnClick() {
      this.dialogVisible = false;
      this.$emit("closeDialog");
    },
    /**重置表单*/
    reset() {
      this.form = {
        customizeClassifyName: null,
        classifyDesc: null,
        id:null
      };
      this.resetForm("ruleForm");
    },
    handleReuslt(res) {
      this.$modal.msgSuccess(res.msg);
      this.reset();
      this.$emit('handleQuery');
      this.handleClose();
    },
    /**验证 */
    submitForm(formName) {
      // 在详情模式下不执行提交操作，直接关闭弹窗
      if (this.disabled) {
        this.handleClose();
        return;
      }

      this.$refs[formName].validate(valid => {
        if (valid) {
          // 显示遮罩层
          this.loading = this.$loading({
            lock: true,
            text: "数据提交中，请稍候...",
            background: 'rgba(0,0,0,0.5)',
            target: this.$el.querySelector('.el-dialog') || document.body
          })
          let params = _.cloneDeep(this.form);
          if (this.isAdd === 'add') {
            addKyFilesCustomizeClassifyAPI(params).then(res => {
              this.loading.close();
              if (res.code === 200) {
                this.handleReuslt(res);
              } else {
                this.$modal.msgError(res.msg);
              }
            }).catch(error => {
              this.loading.close();
              this.$modal.msgError(this.errorMsg(error));
            });
          } else {
            updateKyFilesCustomizeClassifyAPI(params).then(res => {
              this.loading.close();
              if (res.code === 200) {
                this.handleReuslt(res);
              } else {
                this.$modal.msgError(res.msg);
              }
            }).catch(error => {
              this.loading.close();
              this.$modal.msgError(this.errorMsg(error));
            });
          }
        }
      });
    },
    errorMsg(error) {
      const errorMessage = error.message;
      const errorArr = errorMessage.split('：');
      const errorObjData = errorArr.length > 1 ? JSON.parse(errorArr[1]) : '';
      if(errorObjData){
        return this.errorObj[errorObjData.paramName] + errorArr[0] + ':' + errorObjData.originalValue;
      }else{
        return errorMessage;
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.w700 ::v-deep .el-dialog {
  width: 700px;
}

.w500 ::v-deep .el-dialog {
  width: 500px;
}

.w500 ::v-deep .el-dialog__header,
.w700 ::v-deep .el-dialog__header {
  .el-dialog__title {
    font-size: 16px;
  }
}

.yxq .el-range-separator {
  margin-right: 7px !important;
}

.el-date-editor--daterange.el-input__inner {
  width: 260px;
}

.form-item {
  width: 100%;
}

.select-style {
  display: flex;
  justify-content: space-between;
}

/* 详情模式下的样式 */
::v-deep .el-form-item.is-disabled .el-form-item__label {
  color: #606266;
}

::v-deep .el-input.is-disabled .el-input__inner {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #606266;
  cursor: not-allowed;
}

::v-deep .el-textarea.is-disabled .el-textarea__inner {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #606266;
  cursor: not-allowed;
}
</style>
