﻿<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="showBatchCreateDialog"
        >
          一键创建
        </el-button>
        <el-button 
          type="primary" 
          icon="el-icon-refresh-left"
          @click="showSyncDialog"
        >
          同步上月数据
        </el-button>
        <el-button 
          type="primary" 
          icon="el-icon-plus" 
          @click="handleAdd"
          :loading="loading"
        >
          新增
        </el-button>
        <el-button 
          icon="el-icon-refresh" 
          @click="getList"
          :loading="loading"
        >
          刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="80px">
        <el-form-item label="门店" prop="storeId">
          <el-select 
            v-model="queryParams.storeId" 
            placeholder="请选择门店"
            clearable
            filterable
            @change="handleQuery"
            style="width: 200px"
          >
            <el-option
              v-for="store in storeList"
              :key="store.id"
              :label="store.dm"
              :value="store.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="月份" prop="month">
          <el-date-picker
            v-model="queryParams.month"
            type="month"
            placeholder="选择月份"
            format="yyyyMM"
            value-format="yyyyMM"
            @change="handleQuery"
            style="width: 200px"
          />
        </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 - 500px)"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <!-- 门店名称 -->
        <el-table-column label="门店名称" width="160" align="center">
          <template slot-scope="scope">
            <div class="store-name">
              <i class="el-icon-shop store-icon"></i>
              <span>{{ getStoreName(scope.row.storeId) || '无' }}</span>
            </div>
          </template>
        </el-table-column>

        <!-- 月份 -->
        <el-table-column label="月份" width="120" align="center">
          <template slot-scope="scope">
            <div class="month-item">
              <i class="el-icon-date month-icon"></i>
              <span>{{ formatMonth(scope.row.month) || '无' }}</span>
            </div>
          </template>
        </el-table-column>

        <!-- 事业部 -->
        <el-table-column label="事业部" width="120" align="center">
          <template slot-scope="scope">
            <div class="department-item">
              <i class="el-icon-office-building department-icon"></i>
              <span>{{ getDepartmentName(scope.row.businessUnit, businessUnitOptions) || '无' }}</span>
            </div>
          </template>
        </el-table-column>

        <!-- 科技部 -->
        <el-table-column label="科技部" width="120" align="center">
          <template slot-scope="scope">
            <div class="department-item">
              <i class="el-icon-office-building department-icon"></i>
              <span>{{ getDepartmentName(scope.row.techDepartment, techDepartmentOptions) || '无' }}</span>
            </div>
          </template>
        </el-table-column>

        <!-- 教育部 -->
        <el-table-column label="教育部" width="120" align="center">
          <template slot-scope="scope">
            <div class="department-item">
              <i class="el-icon-office-building department-icon"></i>
              <span>{{ getDepartmentName(scope.row.educationDepartment, educationDepartmentOptions) || '无' }}</span>
            </div>
          </template>
        </el-table-column>

        <!-- 大项目部 -->
        <el-table-column label="大项目部" width="140" align="center">
          <template slot-scope="scope">
            <div class="department-item">
              <i class="el-icon-office-building department-icon"></i>
              <span>{{ getDepartmentName(scope.row.majorProjectDepartment, majorProjectDepartmentOptions) || '无' }}</span>
            </div>
          </template>
        </el-table-column>

        <!-- 事业部目标 -->
        <el-table-column label="事业部目标" align="center" width="140">
          <template slot-scope="scope">
            <div class="target-item">
              <i class="el-icon-aim target-icon"></i>
              <span v-if="scope.row.businessUnitTarget" class="amount">{{ formatMoney(scope.row.businessUnitTarget) }}元</span>
              <span v-else class="no-data">无</span>
            </div>
          </template>
        </el-table-column>

        <!-- 科技部目标 -->
        <el-table-column label="科技部目标" align="center" width="140">
          <template slot-scope="scope">
            <div class="target-item">
              <i class="el-icon-aim target-icon"></i>
              <span v-if="scope.row.techDepartmentTarget" class="amount">{{ formatMoney(scope.row.techDepartmentTarget) }}元</span>
              <span v-else class="no-data">无</span>
            </div>
          </template>
        </el-table-column>

        <!-- 教育部目标 -->
        <el-table-column label="教育部目标" align="center" width="140">
          <template slot-scope="scope">
            <div class="target-item">
              <i class="el-icon-aim target-icon"></i>
              <span v-if="scope.row.educationDepartmentTarget" class="amount">{{ formatMoney(scope.row.educationDepartmentTarget) }}元</span>
              <span v-else class="no-data">无</span>
            </div>
          </template>
        </el-table-column>

        <!-- 大项目部目标 -->
        <el-table-column label="大项目部目标" align="center" width="140">
          <template slot-scope="scope">
            <div class="target-item">
              <i class="el-icon-aim target-icon"></i>
              <span v-if="scope.row.majorProjectDepartmentTarget" class="amount">{{ formatMoney(scope.row.majorProjectDepartmentTarget) }}元</span>
              <span v-else class="no-data">无</span>
            </div>
          </template>
        </el-table-column>

        <!-- 门店目标 -->
        <el-table-column label="门店目标" align="center" width="140">
          <template slot-scope="scope">
            <div class="target-item">
              <i class="el-icon-aim target-icon"></i>
              <span v-if="scope.row.storeTarget" class="amount">{{ formatMoney(scope.row.storeTarget) }}元</span>
              <span v-else class="no-data">无</span>
            </div>
          </template>
        </el-table-column>

        <!-- 门店生命线 -->
        <el-table-column label="门店生命线" align="center" width="140">
          <template slot-scope="scope">
            <div class="life-line-item">
              <i class="el-icon-money life-line-icon"></i>
              <span v-if="scope.row.storeLifeline" class="amount">{{ formatMoney(scope.row.storeLifeline) }}元</span>
              <span v-else class="no-data">无</span>
            </div>
          </template>
        </el-table-column>

        <!-- 门店耗卡目标 -->
        <el-table-column label="门店耗卡目标" align="center" width="140">
          <template slot-scope="scope">
            <div class="target-item">
              <i class="el-icon-aim target-icon"></i>
              <span v-if="scope.row.storeConsumeTarget" class="amount">{{ formatMoney(scope.row.storeConsumeTarget) }}元</span>
              <span v-else class="no-data">无</span>
            </div>
          </template>
        </el-table-column>

        <!-- 门店项目目标 -->
        <el-table-column label="门店项目目标" align="center" width="140">
          <template slot-scope="scope">
            <div class="target-item">
              <i class="el-icon-aim target-icon"></i>
              <span v-if="scope.row.storeProjectTarget" class="amount">{{ formatMoney(scope.row.storeProjectTarget) }}元</span>
              <span v-else class="no-data">无</span>
            </div>
          </template>
        </el-table-column>

        <!-- 门店人员目标 -->
        <el-table-column label="门店人员目标" align="center" width="140">
          <template slot-scope="scope">
            <div class="target-item">
              <i class="el-icon-user target-icon"></i>
              <span v-if="scope.row.storeHeadcountTarget" class="amount">{{ scope.row.storeHeadcountTarget }}人</span>
              <span v-else class="no-data">无</span>
            </div>
          </template>
        </el-table-column>

        <!-- 助理人员目标阶段1 -->
        <el-table-column label="助理人员目标阶段1" align="center" width="160">
          <template slot-scope="scope">
            <div class="target-item">
              <i class="el-icon-user target-icon"></i>
              <span v-if="scope.row.assistantHeadcountTargetStage1" class="amount">{{ scope.row.assistantHeadcountTargetStage1 }}人</span>
              <span v-else class="no-data">无</span>
            </div>
          </template>
        </el-table-column>

        <!-- 助理人员目标阶段2 -->
        <el-table-column label="助理人员目标阶段2" align="center" width="160">
          <template slot-scope="scope">
            <div class="target-item">
              <i class="el-icon-user target-icon"></i>
              <span v-if="scope.row.assistantHeadcountTargetStage2" class="amount">{{ scope.row.assistantHeadcountTargetStage2 }}人</span>
              <span v-else class="no-data">无</span>
            </div>
          </template>
        </el-table-column>

        <!-- 操作 -->
        <el-table-column label="操作" width="180" align="left" fixed="right">
          <template slot-scope="scope">
            <div class="action-buttons">
              <el-button 
                type="text" 
                icon="el-icon-edit" 
                @click="handleEdit(scope.row)"
                size="small"
                class="edit-btn"
              >
                编辑
              </el-button>
              <el-button 
                type="text" 
                icon="el-icon-delete" 
                @click="handleDelete(scope.row)"
                size="small"
                class="delete-btn"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </NCC-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </div>

    <!-- 月份选择弹窗 -->
    <el-dialog
      :title="batchDialogTitle"
      :visible="batchDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      @close="handleBatchDialogClose"
    >
      <el-form label-width="100px" label-position="right">
        <el-form-item label="选择月份" required>
          <el-date-picker
            v-model="batchOperationMonth"
            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="handleBatchDialogClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleBatchDialogConfirm"
          :loading="batchCreateLoading || syncLoading"
        >
          确定
        </el-button>
      </div>
    </el-dialog>

    <!-- 编辑弹窗 -->
    <edit-dialog 
      :visible="editVisible"
      :form-data="currentRow"
      :store-list="storeList"
      @close="editVisible = false"
      @success="handleEditSuccess"
    />
  </div>
</template>

<script>
import { lqmdtargetApi } from '@/api/extend/lqmdtarget'
import EditDialog from './components/edit-dialog.vue'

export default {
  name: 'LqYcsdMdmbsd',
  components: {
    EditDialog
  },
  data() {
    // 获取当前月份，格式为 yyyyMM
    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,
      batchCreateLoading: false,
      syncLoading: false,
      list: [],
      total: 0,
      storeList: [],
      batchOperationMonth: getCurrentMonth(), // 批量操作使用的独立月份选择器
      batchDialogVisible: false, // 批量操作弹窗显示状态
      batchDialogTitle: '', // 批量操作弹窗标题
      batchOperationType: '', // 批量操作类型：'create' 或 'sync'
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        storeId: '',
        month: getCurrentMonth()
      },
      editVisible: false,
      currentRow: null,
      businessUnitOptions: [],
      techDepartmentOptions: [],
      educationDepartmentOptions: [],
      majorProjectDepartmentOptions: []
    }
  },
  created() {
    this.getStoreList()
    this.getDepartmentOptions()
    this.getList()
  },
  methods: {
    // 获取门店列表
    async getStoreList() {
      try {
        const response = await lqmdtargetApi.getStoreList()
        this.storeList = response.data.list || []
      } catch (error) {
        console.error('获取门店列表失败:', error)
        this.storeList = []
      }
    },

    // 获取部门选项
    getDepartmentOptions() {
      // 获取事业部选项
      lqmdtargetApi.previewDataInterface('734724946332222725').then(res => {
        this.businessUnitOptions = res.data.list || []
      }).catch(() => {
        this.businessUnitOptions = []
      })
      // 获取科技部选项
      lqmdtargetApi.previewDataInterface('734725044101448965').then(res => {
        this.techDepartmentOptions = res.data.list || []
      }).catch(() => {
        this.techDepartmentOptions = []
      })
      // 获取教育部选项
      lqmdtargetApi.previewDataInterface('734725010941281541').then(res => {
        this.educationDepartmentOptions = res.data.list || []
      }).catch(() => {
        this.educationDepartmentOptions = []
      })
      // 获取大项目部选项
      lqmdtargetApi.previewDataInterface('734725079920805125').then(res => {
        this.majorProjectDepartmentOptions = res.data.list || []
      }).catch(() => {
        this.majorProjectDepartmentOptions = []
      })
    },

    // 获取部门名称
    getDepartmentName(id, options) {
      if (!id || !options || options.length === 0) return ''
      const option = options.find(item => item.id === id || item.Id === id)
      return option ? (option.fullName || option.FullName) : ''
    },

    // 获取列表数据
    async getList() {
      this.loading = true
      try {
        const params = {
          currentPage: this.queryParams.pageNum,
          pageSize: this.queryParams.pageSize,
          storeId: this.queryParams.storeId || '',
          month: this.queryParams.month || ''
        }
        const response = await lqmdtargetApi.getPageList(params)
        
        this.list = response.data.list || []
        this.total = (response.data.pagination && response.data.pagination.total) || 0
      } catch (error) {
        console.error('获取列表失败:', error)
        this.$message.error('获取列表失败')
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    // 重置搜索
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 20,
        storeId: '',
        month: this.getCurrentMonth()
      }
      this.list = []
      this.total = 0
      this.getList()
    },

    // 获取当前月份，格式为 yyyyMM
    getCurrentMonth() {
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      return `${year}${month}`
    },

    // 显示一键创建弹窗
    showBatchCreateDialog() {
      this.batchOperationMonth = this.getCurrentMonth()
      this.batchDialogTitle = '一键创建'
      this.batchOperationType = 'create'
      this.batchDialogVisible = true
    },

    // 显示同步上月数据弹窗
    showSyncDialog() {
      this.batchOperationMonth = this.getCurrentMonth()
      this.batchDialogTitle = '同步上月数据'
      this.batchOperationType = 'sync'
      this.batchDialogVisible = true
    },

    // 关闭批量操作弹窗
    handleBatchDialogClose() {
      this.batchDialogVisible = false
      this.batchOperationType = ''
    },

    // 确认批量操作
    async handleBatchDialogConfirm() {
      if (!this.batchOperationMonth) {
        this.$message.warning('请先选择月份')
        return
      }

      if (this.batchOperationType === 'create') {
        await this.handleBatchCreate()
      } else if (this.batchOperationType === 'sync') {
        await this.handleSyncLastMonthData()
      }
    },

    // 一键创建
    async handleBatchCreate() {
      this.$confirm(`确定要为 ${this.formatMonth(this.batchOperationMonth)} 月份一键创建所有门店的目标设置吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.batchCreateLoading = true
        try {
          await lqmdtargetApi.batchCreateByStores(this.batchOperationMonth)
          this.$message.success('一键创建成功')
          this.batchDialogVisible = false
          this.getList()
        } catch (error) {
          console.error('一键创建失败:', error)
          this.$message.error(error.message || '一键创建失败')
        } finally {
          this.batchCreateLoading = false
        }
      }).catch(() => {
        // 用户取消操作
      })
    },

    // 同步上月数据
    async handleSyncLastMonthData() {
      this.$confirm(`确定要将上月数据同步到 ${this.formatMonth(this.batchOperationMonth)} 月份吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.syncLoading = true
        try {
          const result = await lqmdtargetApi.syncLastMonthData(this.batchOperationMonth)
          this.$message.success(result.data.message)
          this.batchDialogVisible = false
          this.getList()
        } catch (error) {
          console.error('同步上月数据失败:', error)
          this.$message.error(error.message || '同步上月数据失败')
        } finally {
          this.syncLoading = false
        }
      }).catch(() => {
        // 用户取消操作
      })
    },

    // 新增
    handleAdd() {
      this.currentRow = null
      this.editVisible = true
    },

    // 编辑
    handleEdit(row) {
      this.currentRow = { ...row }
      this.editVisible = true
    },

    // 删除
    handleDelete(row) {
      this.$confirm('确定要删除这条目标设置吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const id = row.id || row.Id
          await lqmdtargetApi.delete(id)
          this.$message.success('删除成功')
          this.getList()
        } catch (error) {
          console.error('删除失败:', error)
          this.$message.error(error.message || '删除失败')
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    // 编辑成功
    handleEditSuccess() {
      this.editVisible = false
      this.getList()
      this.$message.success('操作成功')
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getList()
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.getList()
    },

    // 获取门店名称
    getStoreName(id) {
      if (!id) return ''
      const store = this.storeList.find(s => s.id === id)
      return store ? store.dm : ''
    },

    // 格式化金额
    formatMoney(amount) {
      if (!amount) return '0.00'
      return Number(amount).toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })
    },

    // 格式化月份
    formatMonth(month) {
      if (!month) return ''
      if (month.length === 6) {
        return `${month.substring(0, 4)}-${month.substring(4, 6)}`
      }
      return month
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  background: #f5f5f5;
  // min-height: calc(100vh - 84px);
}

.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 {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

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

// 门店信息样式
.store-name {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  
  .store-icon {
    color: #67C23A;
    font-size: 16px;
  }
  
  span {
    font-weight: 500;
    color: #303133;
  }
}

// 月份样式
.month-item {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  
  .month-icon {
    color: #909399;
    font-size: 16px;
  }
  
  span {
    color: #606266;
  }
}

// 部门项样式
.department-item {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  
  .department-icon {
    color: #67C23A;
    font-size: 16px;
  }
  
  span {
    color: #606266;
  }
}

// 目标项目样式
.target-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  gap: 6px;
  min-height: 40px;

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

  .amount {
    font-weight: 600;
    color: #409EFF;
    font-size: 14px;
  }
}

// 生命线项目样式
.life-line-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  gap: 6px;
  min-height: 40px;

  .life-line-icon {
    color: #409EFF;
    font-size: 16px;
  }

  .amount {
    font-weight: 600;
    color: #409EFF;
    font-size: 14px;
  }
}

// 操作按钮样式
.action-buttons {
  display: flex;
  align-items: center;
  gap: 8px;
  
  .edit-btn {
    color: #409EFF;
    
    &:hover {
      color: #66b1ff;
    }
  }
  
  .delete-btn {
    color: #F56C6C;
    
    &:hover {
      color: #f78989;
    }
  }
}

.no-data {
  color: #C0C4CC;
  font-size: 12px;
  font-style: italic;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
</style>

