<template>
  <div class="app-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2>门店大项目部老师归属设置</h2>
        <p class="page-desc">管理门店大项目部老师的归属设置，包括门店、年份、月份、老师等信息</p>
      </div>
      <div class="header-right">
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="handleAdd"
        >
          新增
        </el-button>
        <el-button
          type="success"
          icon="el-icon-copy-document"
          @click="showCopyDialog"
          :loading="copyLoading"
        >
          复制上月设置
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        label-width="50px"
        label-position="right"
      >
        <el-form-item label="门店" prop="storeId">
          <el-select
            v-model="queryParams.storeId"
            placeholder="请选择门店"
            clearable
            filterable
            style="width: 200px"
          >
            <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="queryParams.year"
            type="year"
            placeholder="选择年份"
            format="yyyy"
            value-format="yyyy"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="月份" prop="month">
          <el-date-picker
            v-model="queryParams.month"
            type="month"
            placeholder="选择月份"
            format="yyyyMM"
            value-format="yyyyMM"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="老师" prop="teacherId">
          <el-select
            v-model="queryParams.teacherId"
            placeholder="请选择老师"
            clearable
            filterable
            style="width: 200px"
          >
            <el-option
              v-for="teacher in teacherList"
              :key="teacher.id"
              :label="teacher.realName"
              :value="teacher.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">
            搜索
          </el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <NCC-table
        v-loading="loading"
        :data="list"
        border
        stripe
        height="calc(100vh - 520px)"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column
          prop="year"
          label="年份"
          width="100"
          
        >
          <template slot-scope="scope">
            <span>{{ scope.row.year || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="month"
          label="月份"
          width="100"
          
        >
          <template slot-scope="scope">
            <span>{{ scope.row.month || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="storeName"
          label="门店名称"
          width="150"
        >
          <template slot-scope="scope">
            <div class="cell-with-icon">
              <span>{{ scope.row.storeName || '无' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="teacherName"
          label="大项目部老师"
          width="150"
          
        >
          <template slot-scope="scope">
            <div class="cell-with-icon">
              <span>{{ scope.row.teacherName || '无' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="remark"
          label="备注说明"
          min-width="200"
          
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>{{ scope.row.remark || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          width="180"
          
        >
          <template slot-scope="scope">
            <span>{{ formatDateTime(scope.row.createTime) || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="updateTime"
          label="更新时间"
          width="180"
          
        >
          <template slot-scope="scope">
            <span>{{ formatDateTime(scope.row.updateTime) || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="150"
          align="left"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.row.id)"
            >
              编辑
            </el-button>
            <el-button
              type="text"
              icon="el-icon-delete"
              style="color: #f56c6c"
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </NCC-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.currentPage"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 表单弹窗 -->
    <form-dialog ref="formDialog" @refresh="getList" />

    <!-- 复制上月设置弹窗 -->
    <el-dialog
      title="复制上月设置"
      :visible.sync="copyDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      @close="handleCopyDialogClose"
    >
      <el-form
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="目标年份" required>
          <el-date-picker
            v-model="copyTargetYear"
            type="year"
            placeholder="请选择目标年份"
            format="yyyy"
            value-format="yyyy"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="目标月份" required>
          <el-date-picker
            v-model="copyTargetMonth"
            type="month"
            placeholder="请选择目标月份"
            format="yyyyMM"
            value-format="yyyyMM"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCopyDialogClose">取消</el-button>
        <el-button
          type="primary"
          @click="handleCopyConfirm"
          :loading="copyLoading"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getMajorProjectTeacherAssignmentList,
  deleteMajorProjectTeacherAssignment,
  copyLastMonthData,
  getTeacherList
} from '@/api/extend/majorProjectTeacherAssignment'
import { getStoreSelector } from '@/api/extend/store'
import FormDialog from './form-dialog.vue'
import Pagination from '@/components/Pagination'

export default {
  name: 'MajorProjectTeacherAssignment',
  components: {
    FormDialog,
    Pagination
  },
  data() {
    // 获取当前年月
    const getCurrentYear = () => {
      return new Date().getFullYear().toString()
    }
    const getCurrentMonth = () => {
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      return `${year}${month}`
    }

    return {
      loading: false,
      copyLoading: false,
      list: [],
      total: 0,
      storeList: [],
      teacherList: [],
      copyDialogVisible: false,
      copyTargetYear: getCurrentYear(),
      copyTargetMonth: getCurrentMonth(),
      queryParams: {
        currentPage: 1,
        pageSize: 20,
        storeId: '',
        year: getCurrentYear(),
        month: getCurrentMonth(),
        teacherId: ''
      }
    }
  },
  created() {
    this.getStoreList()
    this.getTeacherList()
    this.getList()
  },
  methods: {
    // 获取门店列表
    async getStoreList() {
      try {
        const response = await getStoreSelector()
        if (response.code === 200 && response.data) {
          this.storeList = response.data.list || []
        }
      } catch (error) {
        console.error('获取门店列表失败:', error)
        this.storeList = []
      }
    },
    // 获取老师列表
    async getTeacherList() {
      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 = []
      }
    },
    // 获取列表数据
    async getList() {
      this.loading = true
      try {
        // 处理月份格式：从yyyyMM格式转换为MM格式
        let month = this.queryParams.month
        if (month && month.length === 6) {
          month = month.substring(4, 6)
        }

        const params = {
          currentPage: this.queryParams.currentPage,
          pageSize: this.queryParams.pageSize,
          storeId: this.queryParams.storeId || '',
          year: this.queryParams.year || '',
          month: month || '',
          teacherId: this.queryParams.teacherId || ''
        }

        const response = await getMajorProjectTeacherAssignmentList(params)

        if (response.code === 200) {
          this.list = response.data.list || []
          this.total =
            (response.data.pagination && response.data.pagination.total) || 0
        } else {
          this.$message.error(response.msg || '获取数据失败')
        }
      } catch (error) {
        console.error('获取列表失败:', error)
        this.$message.error('获取数据失败')
      } finally {
        this.loading = false
      }
    },
    // 搜索
    handleQuery() {
      this.queryParams.currentPage = 1
      this.getList()
    },
    // 重置搜索
    resetQuery() {
      const getCurrentYear = () => {
        return new Date().getFullYear().toString()
      }
      const getCurrentMonth = () => {
        const now = new Date()
        const year = now.getFullYear()
        const month = String(now.getMonth() + 1).padStart(2, '0')
        return `${year}${month}`
      }
      this.queryParams = {
        currentPage: 1,
        pageSize: 20,
        storeId: '',
        year: getCurrentYear(),
        month: getCurrentMonth(),
        teacherId: ''
      }
      this.getList()
    },
    // 新增
    handleAdd() {
      this.$refs.formDialog.openAdd()
    },
    // 编辑
    handleEdit(id) {
      this.$refs.formDialog.openEdit(id)
    },
    // 删除
    handleDelete(id) {
      this.$confirm('确定要删除这条记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            const response = await deleteMajorProjectTeacherAssignment(id)
            if (response.code === 200) {
              this.$message.success('删除成功')
              this.getList()
            } else {
              this.$message.error(response.msg || '删除失败')
            }
          } catch (error) {
            console.error('删除失败:', error)
            this.$message.error('删除失败')
          }
        })
        .catch(() => {})
    },
    // 显示复制弹窗
    showCopyDialog() {
      const getCurrentYear = () => {
        return new Date().getFullYear().toString()
      }
      const getCurrentMonth = () => {
        const now = new Date()
        const year = now.getFullYear()
        const month = String(now.getMonth() + 1).padStart(2, '0')
        return `${year}${month}`
      }
      this.copyTargetYear = getCurrentYear()
      this.copyTargetMonth = getCurrentMonth()
      this.copyDialogVisible = true
    },
    // 关闭复制弹窗
    handleCopyDialogClose() {
      this.copyDialogVisible = false
    },
    // 确认复制
    async handleCopyConfirm() {
      if (!this.copyTargetYear || !this.copyTargetMonth) {
        this.$message.warning('请选择目标年份和月份')
        return
      }

      // 从copyTargetMonth中提取月份（yyyyMM格式，如202512）
      const year = this.copyTargetYear
      const month =
        this.copyTargetMonth.length === 6
          ? this.copyTargetMonth.substring(4, 6)
          : this.copyTargetMonth

      this.copyLoading = true
      try {
        const response = await copyLastMonthData(year, month)
        if (response.code === 200) {
          this.$message.success(
            (response.data && response.data.message) || '复制上月设置成功'
          )
          this.copyDialogVisible = false
          this.getList()
        } else {
          this.$message.error(response.msg || '复制上月设置失败')
        }
      } catch (error) {
        console.error('复制上月设置失败:', error)
        this.$message.error(error.message || '复制上月设置失败')
      } finally {
        this.copyLoading = false
      }
    },
    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return ''
      const date = new Date(dateTime)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  background: #f5f5f5;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

  .header-left {
    h2 {
      margin: 0 0 8px 0;
      color: #303133;
      font-size: 20px;
      font-weight: 600;
    }

    .page-desc {
      margin: 0;
      color: #909399;
      font-size: 14px;
    }
  }

  .header-right {
    display: flex;
    gap: 12px;
  }
}

.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-container {
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.cell-with-icon {
  display: flex;
  align-items: center;
  gap: 6px;

  .icon {
    color: #409eff;
    font-size: 16px;
  }
}

// 表格样式优化
::v-deep .el-table {
  .el-table__header-wrapper {
    th {
      background-color: #f5f7fa;
      color: #606266;
      font-weight: 600;
    }
  }

  .el-table__body-wrapper {
    .el-table__row {
      &:hover {
        background-color: #f5f7fa;
      }
    }
  }
}

.dialog-footer {
  text-align: right;
}
</style>

