<template>
  <el-dialog
    :title="isEdit ? '编辑归属设置' : '新增归属设置'"
    :visible.sync="visible"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="120px"
      label-position="right"
    >
      <el-form-item label="门店" prop="storeId">
        <el-select
          v-model="form.storeId"
          placeholder="请选择门店"
          style="width: 100%"
          clearable
          filterable
        >
          <el-option
            v-for="store in storeList"
            :key="store.id"
            :label="store.fullName"
            :value="store.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="年份" prop="year">
        <el-date-picker
          v-model="form.year"
          type="year"
          placeholder="请选择年份"
          format="yyyy"
          value-format="yyyy"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="月份" prop="month">
        <el-date-picker
          v-model="form.month"
          type="month"
          placeholder="请选择月份"
          format="yyyyMM"
          value-format="yyyyMM"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="大项目部老师" prop="teacherId">
        <el-select
          v-model="form.teacherId"
          placeholder="请选择大项目部老师"
          clearable
          filterable
          style="width: 100%"
        >
          <el-option
            v-for="teacher in teacherList"
            :key="teacher.id"
            :label="teacher.realName"
            :value="teacher.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注说明" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注说明"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
        确定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  createMajorProjectTeacherAssignment,
  updateMajorProjectTeacherAssignment,
  getMajorProjectTeacherAssignmentInfo,
  getTeacherList
} from '@/api/extend/majorProjectTeacherAssignment'
import { getStoreSelector } from '@/api/extend/store'

export default {
  name: 'MajorProjectTeacherAssignmentFormDialog',
  data() {
    return {
      visible: false,
      isEdit: false,
      submitLoading: false,
      form: {
        storeId: '',
        year: '',
        month: '',
        teacherId: '',
        remark: ''
      },
      rules: {
        storeId: [{ required: true, message: '请选择门店', trigger: 'change' }],
        year: [{ required: true, message: '请选择年份', trigger: 'change' }],
        month: [{ required: true, message: '请选择月份', trigger: 'change' }],
        teacherId: [
          { required: true, message: '请选择大项目部老师', trigger: 'change' }
        ]
      },
      storeList: [],
      teacherList: [],
      editId: null
    }
  },
  methods: {
    // 打开新增弹窗
    openAdd() {
      this.isEdit = false
      this.editId = null
      this.resetForm()
      this.loadStoreList()
      this.loadTeacherList()
      this.visible = true
    },
    // 打开编辑弹窗
    async openEdit(id) {
      this.isEdit = true
      this.editId = id
      this.resetForm()
      this.loadStoreList()
      this.loadTeacherList()
      this.visible = true

      try {
        const response = await getMajorProjectTeacherAssignmentInfo(id)
        if (response.code === 200 && response.data) {
          const data = response.data
          this.form = {
            storeId: data.storeId || '',
            year: data.year || '',
            month: data.month || '',
            teacherId: data.teacherId || '',
            remark: data.remark || ''
          }
          // 处理月份格式：从MM格式转换为yyyyMM格式（用于日期选择器）
          if (this.form.year && this.form.month) {
            this.form.month = `${this.form.year}${this.form.month.padStart(2, '0')}`
          }
        } else {
          this.$message.error(response.msg || '获取详情失败')
          this.visible = false
        }
      } catch (error) {
        console.error('获取详情失败:', error)
        this.$message.error('获取详情失败')
        this.visible = false
      }
    },
    // 重置表单
    resetForm() {
      this.form = {
        storeId: '',
        year: '',
        month: '',
        teacherId: '',
        remark: ''
      }
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },
    // 加载门店列表
    async loadStoreList() {
      try {
        const response = await getStoreSelector()
        if (response.code === 200 && response.data) {
          this.storeList = response.data.list || []
        }
      } catch (error) {
        console.error('加载门店列表失败:', error)
        this.storeList = []
      }
    },
    // 加载老师列表
    async loadTeacherList() {
      try {
        const response = await getTeacherList({
          organizeId: '734725079920805125',
          currentPage: 1,
          pageSize: 100
        })
        if (response.code === 200 && response.data) {
          this.teacherList = response.data.list || []
        }
      } catch (error) {
        console.error('加载老师列表失败:', error)
        this.teacherList = []
      }
    },
    // 提交表单
    handleSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (!valid) return

        // 处理月份格式：从yyyyMM格式转换为MM格式
        let month = this.form.month
        if (month && month.length === 6) {
          month = month.substring(4, 6)
        }

        const submitData = {
          storeId: this.form.storeId,
          year: this.form.year,
          month: month,
          teacherId: this.form.teacherId,
          remark: this.form.remark || ''
        }

        this.submitLoading = true
        try {
          let response
          if (this.isEdit) {
            response = await updateMajorProjectTeacherAssignment(
              this.editId,
              {...submitData,id:this.editId}
            )
          } else {
            response = await createMajorProjectTeacherAssignment(submitData)
          }

          if (response.code === 200) {
            this.$message.success(this.isEdit ? '更新成功' : '创建成功')
            this.handleClose()
            this.$emit('refresh')
          } else {
            this.$message.error(response.msg || '操作失败')
          }
        } catch (error) {
          console.error('提交失败:', error)
          this.$message.error(error.message || '操作失败')
        } finally {
          this.submitLoading = false
        }
      })
    },
    // 关闭弹窗
    handleClose() {
      this.visible = false
      this.resetForm()
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}
</style>

