<template>
  <el-dialog :title="title"
             :visible.sync="dialogVisible"
             width="500px"
             append-to-body
             @close="cancel"
             @open="handleOpen"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-row>
        <form-col :span="span" label="选择店铺" prop="storeId">
          <el-select
            v-model="form.storeId"
            @change="handleStoreChange"
            placeholder="请选择店铺"
            clearable
            filterable
            :loading="loading"
          >
            <el-option
              v-for="item in storeOptions"
              :key="item.storeId"
              :label="item.storeName"
              :value="item.storeId"
            />
          </el-select>
        </form-col>
        <form-col :span="span" label="所属区域" prop="parentId" clearable>
          <el-cascader v-model="form.parentId"
                       :options="parentOptions"
                       :props="cascaderProps"
                       :disabled="!form.storeId"
                       placeholder="选定店铺后选择所属区域"
                       clearable
                       :show-all-levels="false"/>
        </form-col>
        <form-col :span="span" label="区域名称" prop="partName">
          <el-input v-model="form.partName" placeholder="请输入区域名称"/>
        </form-col>
        <form-col :span="span" label="区域图片" prop="picture">
          <image-upload v-model="form.picture"/>
        </form-col>
        <form-col :span="span" label="显示顺序" prop="orderNum">
          <el-input-number v-model="form.orderNum" controls-position="right" :min="1"></el-input-number>
        </form-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {addPart, getPart, listPart, updatePart} from "@/api/bst/part";

export default {
  props: {
    id: {
      type: String,
      default: null
    },
    visible: Boolean,       // 控制显示
    formData: Object,       // 表单初始数据
    storeOptions: {
      type: Array,
      default: () => []
    },
  },

  computed: {
    title() {
      return this.formData.partId ? '修改区域' : '新增区域'
    },
    dialogVisible: {
      get() {
        return this.visible;
      },
      set(value) {
        this.$emit('update:visible', value); // 触发同步
      }
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      span: 24,
      localVisible: this.visible,
      parentOptions: [],
      submitLoading: false,
      form: { ...this.formData },
      rules: {
        storeId: [
          {required: true, message: "所属店铺不能为空", trigger: "blur"}
        ],
        partName: [
          {required: true, message: "区域名称不能为空", trigger: "blur"}
        ],
        orderNum: [
          {required: true, message: "显示顺序不能为空", trigger: "blur"}
        ],
        createTime: [
          {required: true, message: "创建时间不能为空", trigger: "blur"}
        ]
      },
      cascaderProps: {
        value: 'partId',
        label: 'partName',
        children: 'children',
        checkStrictly: true,// 可单选任意级
        emitPath: false
      }
    };
  },
  watch: {
    'form.storeId': {
      immediate: true,
      handler(storeId) {
        if (storeId) {
          this.loadParentTree(storeId); // 自动加载区域
        } else {
          this.parentOptions = [];
        }
      }
    },
    visible(newVal) {
      this.localVisible = newVal;
    },
    formData: {
      deep: true,
      handler(newVal) {
        this.form = newVal;
        // 自动加载区域树
        if (newVal.storeId) {
          this.loadParentTree(newVal.storeId);
        }
      }
    }
  },
  methods: {
    mounted(){
      console.log('子组件接收的 storeOptions:',this.storeOptions)
    },
    reset() {
      this.form = {
        id: null,
        partId: null,
        storeId: null,
        parentId: null,
        parentName: null,
        picture: null,
        orderNum: 1
      }
      this.resetForm('form')
    },
    /** 获取详细信息 */
    getInfo(formData) {
      if (formData.partId) {
        getPart(formData.partId)
          .then(response => {
            this.form = response.data;
          })
          .finally(() => {
            this.loading = false;
          });
      } else {
        this.form = {
          ...this.form,
          parentId: formData.parentId,
          partName: formData.parentName,
          storeId: formData.storeId,
          orderNum: 1
        };
        this.loading = false;
      }
      console.log(this.form)
    },
    // 保留原有表单方法（稍作调整）
    loadParentTree(storeId) {
      listPart({
        storeId: storeId,
      }).then(res => {
        this.parentOptions = this.handleTree(res.data, "partId", "parentId", "children");
      });
    },
    handleStoreChange(storeId) {
      this.form.parentId = null;
      if (storeId) {
        this.loadParentTree(storeId);
      } else {
        this.parentOptions = [];
      }
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.submitLoading = true
          const submitFunc = this.form.partId ? updatePart : addPart
          submitFunc(this.form).then(() => {
            this.$modal.msgSuccess(this.form.partId ? "修改成功" : "新增成功")
            this.$emit('success')
            this.cancel()
          }).finally(() => {
            this.submitLoading = false
          })
        }
      })
    },
    cancel() {
      this.localVisible = false;
      this.$emit('update:visible', false);
    },
    // 打开事件
    handleOpen() {
      this.getInfo(this.formData);
      console.log("formData",this.formData)
    }
  }
};
</script>
