<template>
  <div class="app-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2>总经理门店生命线设置</h2>
        <p class="page-desc">管理总经理对各门店的生命线设置，支持3个生命线级别配置</p>
      </div>
      <div class="header-right">
        <el-button 
          type="primary" 
          icon="el-icon-plus" 
          @click="handleBatchCreate"
          :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="zjlUserid">
          <el-select 
            v-model="queryParams.zjlUserid" 
            placeholder="请选择总经理"
            clearable
            filterable
            @change="handleQuery"
            style="width: 200px"
          >
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="`${user.realName} (${user.gw || '无岗位'})`"
              :value="user.id"
            >
              <span style="float: left">{{ user.realName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ user.gw || '无岗位' }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="门店" prop="mdId">
          <el-select 
            v-model="queryParams.mdId" 
            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>
          <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">
      <el-table 
        v-loading="loading" 
        :data="list" 
        border 
        stripe
        height="calc(100vh - 300px)"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <!-- 总经理 -->
        <el-table-column label="总经理" width="140" align="center">
          <template slot-scope="scope">
            <div class="user-info">
              <i class="el-icon-user-solid user-icon"></i>
              <span>{{ scope.row.ZjlName || '无' }}</span>
            </div>
          </template>
        </el-table-column>
        
        <!-- 门店编码 -->
        <el-table-column label="门店编码" width="120" align="center">
          <template slot-scope="scope">
            <div class="store-code">
              <i class="el-icon-office-building store-icon"></i>
              <span>{{ scope.row.Mdbm || '无' }}</span>
            </div>
          </template>
        </el-table-column>
        
        <!-- 门店名称 -->
        <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>{{ scope.row.Dm || '无' }}</span>
            </div>
          </template>
        </el-table-column>
        
        <!-- 生命线1 -->
        <el-table-column label="生命线1" 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.Smx1" class="amount">{{ formatMoney(scope.row.Smx1) }}元</span>
              <span v-else class="no-data">无</span>
            </div>
          </template>
        </el-table-column>
        
        <!-- 提成比例1 -->
        <el-table-column label="提成比例1" align="center" width="120">
          <template slot-scope="scope">
            <div class="ratio-item">
              <i class="el-icon-percent ratio-icon"></i>
              <span v-if="scope.row.Tcbl1" class="ratio">{{ scope.row.Tcbl1 }}%</span>
              <span v-else class="no-data">无</span>
            </div>
          </template>
        </el-table-column>
        
        <!-- 生命线2 -->
        <el-table-column label="生命线2" 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.Smx2" class="amount">{{ formatMoney(scope.row.Smx2) }}元</span>
              <span v-else class="no-data">无</span>
            </div>
          </template>
        </el-table-column>
        
        <!-- 提成比例2 -->
        <el-table-column label="提成比例2" align="center" width="120">
          <template slot-scope="scope">
            <div class="ratio-item">
              <i class="el-icon-percent ratio-icon"></i>
              <span v-if="scope.row.Tcbl2" class="ratio">{{ scope.row.Tcbl2 }}%</span>
              <span v-else class="no-data">无</span>
            </div>
          </template>
        </el-table-column>
        
        <!-- 生命线3 -->
        <el-table-column label="生命线3" 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.Smx3" class="amount">{{ formatMoney(scope.row.Smx3) }}元</span>
              <span v-else class="no-data">无</span>
            </div>
          </template>
        </el-table-column>
        
        <!-- 提成比例3 -->
        <el-table-column label="提成比例3" align="center" width="120">
          <template slot-scope="scope">
            <div class="ratio-item">
              <i class="el-icon-percent ratio-icon"></i>
              <span v-if="scope.row.Tcbl3" class="ratio">{{ scope.row.Tcbl3 }}%</span>
              <span v-else class="no-data">无</span>
            </div>
          </template>
        </el-table-column>
        
        <!-- 备注 -->
        <el-table-column label="备注" min-width="160" show-overflow-tooltip>
          <template slot-scope="scope">
            <div class="remark-item">
              <i class="el-icon-document remark-icon"></i>
              <span>{{ scope.row.Bz || '无' }}</span>
            </div>
          </template>
        </el-table-column>
        
        <!-- 创建时间 -->
        <el-table-column label="创建时间" width="160" align="center">
          <template slot-scope="scope">
            <div class="time-item">
              <i class="el-icon-time time-icon"></i>
              <span>{{ formatDate(scope.row.Cjsj) }}</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>
      </el-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>

    <!-- 批量设置弹窗 -->
    <batch-create-dialog 
      :visible="batchCreateVisible"
      :user-list="userList"
      :store-list="storeList"
      @close="batchCreateVisible = false"
      @success="handleBatchCreateSuccess"
    />

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

<script>
import { lqZjlMdsmxszApi } from '@/api/extend/lqZjlMdsmxsz'
import request from '@/utils/request'
import BatchCreateDialog from './components/BatchCreateDialog.vue'
import EditDialog from './components/EditDialog.vue'

export default {
  name: 'LqZjlMdsmxsz',
  components: {
    BatchCreateDialog,
    EditDialog
  },
  data() {
    return {
      loading: false,
      list: [],
      total: 0,
      userList: [],
      storeList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        zjlUserid: '',
        mdId: ''
      },
      batchCreateVisible: false,
      editVisible: false,
      currentRow: null
    }
  },
  created() {
    this.getUserList()
    this.getStoreList()
    this.getList()
  },
  methods: {
    // 获取总经理用户列表
    async getUserList() {
      try {
        const response = await lqZjlMdsmxszApi.getZjlUserList()
        this.userList = response.data || []
        console.log('获取总经理用户列表成功:', this.userList)
      } catch (error) {
        console.error('获取总经理用户列表失败:', error)
        // 如果获取失败，使用空数组
        this.userList = []
      }
    },

    // 获取门店列表
    async getStoreList() {
      try {
        // 获取所有门店列表，用于编辑时显示门店名称
        const response = await request({
          url: '/api/Extend/LqMdxx',
          method: 'GET',
          params: { pageSize: 1000 } // 获取所有门店
        })
        this.storeList = response.data.list || []
        console.log('门店列表:', this.storeList)
      } catch (error) {
        console.error('获取门店列表失败:', error)
        this.storeList = []
      }
    },

    // 获取列表数据
    async getList() {
      this.loading = true
      try {
        // 使用分页查询接口
        const response = await lqZjlMdsmxszApi.getPageList({
          currentPage: this.queryParams.pageNum,
          pageSize: this.queryParams.pageSize,
          zjlUserid: this.queryParams.zjlUserid || '',
          mdId: this.queryParams.mdId || ''
        })
        
        // 适配新的数据结构
        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,
        zjlUserid: '',
        mdId: ''
      }
      this.list = []
      this.total = 0
    },

    // 批量设置
    handleBatchCreate() {
      this.batchCreateVisible = true
    },

    // 编辑
    handleEdit(row) {
      console.log('编辑行数据:', row)
      this.currentRow = { ...row }
      console.log('当前行数据:', this.currentRow)
      
      // 确保门店列表已加载
      if (this.storeList.length === 0) {
        this.getStoreList()
      }
      
      this.editVisible = true
    },

    // 删除
    handleDelete(row) {
      this.$confirm('确定要删除这条生命线设置吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // TODO: 实现删除接口
        this.$message.success('删除成功')
        this.getList()
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    // 批量创建成功
    handleBatchCreateSuccess() {
      this.batchCreateVisible = false
      this.getList()
      this.$message.success('批量设置成功')
    },

    // 编辑成功
    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()
    },

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

    // 格式化日期
    formatDate(date) {
      if (!date) return ''
      return new Date(date).toLocaleString('zh-CN')
    }
  }
}
</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;
}

// 用户信息样式
.user-info {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  
  .user-icon {
    color: #409EFF;
    font-size: 16px;
  }
  
  span {
    font-weight: 500;
    color: #303133;
  }
}

// 门店信息样式
.store-code, .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;
  }
}

// 生命线项目样式
.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;
  }
}

// 提成比例样式
.ratio-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  gap: 6px;
  min-height: 40px;

  .ratio-icon {
    color: #67C23A;
    font-size: 16px;
  }

  .ratio {
    color: #67C23A;
    font-size: 12px;
    background: #f0f9ff;
    padding: 2px 6px;
    border-radius: 4px;
    font-weight: 500;
  }
}

// 备注样式
.remark-item {
  display: flex;
  align-items: center;
  gap: 6px;
  
  .remark-icon {
    color: #909399;
    font-size: 14px;
  }
  
  span {
    color: #606266;
  }
}

// 时间样式
.time-item {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  
  .time-icon {
    color: #909399;
    font-size: 14px;
  }
  
  span {
    color: #606266;
    font-size: 13px;
  }
}

// 操作按钮样式
.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>
