<template>
  <div class="app-container">
    <h4 class="form-header h4">基本信息</h4>
<!--    <el-form ref="form" :model="form" label-width="80px">-->
<!--      <el-row>-->
<!--        <el-col :span="8" :offset="2">-->
<!--          <el-form-item label="用户昵称" prop="nickName">-->
<!--            <el-input v-model="form.nickName" disabled />-->
<!--          </el-form-item>-->
<!--        </el-col>-->
<!--        <el-col :span="8" :offset="2">-->
<!--          <el-form-item label="登录账号" prop="userName">-->
<!--            <el-input v-model="form.userName" disabled />-->
<!--          </el-form-item>-->
<!--        </el-col>-->
<!--      </el-row>-->
<!--    </el-form>-->

    <h4 class="form-header h4">门店信息</h4>
    <el-table v-loading="loading" :row-key="getRowKey" @row-click="clickRow" ref="table" @selection-change="handleSelectionChange" :data="(stores || []).slice((pageNum-1)*pageSize,pageNum*pageSize)">
      <el-table-column label="序号" type="index" align="center">
        <template slot-scope="scope">
          <span>{{ (pageNum - 1) * pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column type="selection" :reserve-selection="true" :selectable="checkSelectable" width="55" />
      <el-table-column label="门店ID" align="center" prop="storeId" />
      <el-table-column label="门店名称" align="center" prop="storeName" />
      <el-table-column label="门店编码" align="center" prop="storeCode" />
      <el-table-column label="联系电话" align="center" prop="contactPhone" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize" />

    <el-form label-width="100px">
      <el-form-item style="text-align: center;margin-left:-120px;margin-top:30px;">
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="close">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { storeApi } from '@/api/store'
import { parseTime } from "@/utils/ruoyi"

export default {
  name: 'UserStores',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 分页信息
      total: 0,
      pageNum: 1,
      pageSize: 10,
      // 选中门店编号
      storeIds: [],
      // 门店信息
      stores: [],
      // 用户信息
      form: {},
      userId: '',
    }
  },
  created() {
    const userId = this.$route.params && this.$route.params.userId
    if (userId) {
      this.loading = true
      storeApi.getUserStore(userId).then((response) => {
        console.log("111111",response)
        // 获取API响应数据
        const responseData = response.data.data || {}

        // 处理用户信息（如果有）
        this.form = responseData.user || {}

        // 获取关联门店数据和所有门店数据
        const associatedStores = responseData.stores || []
        this.stores = responseData.allStores || []
        this.userId =response.data.data.userId
        this.total = this.stores.length
        console.log("22222",this.stores)
        console.log("关联门店:", associatedStores)
        console.log("ididid----", this.userId)
        // 提取关联门店的ID列表
        const associatedStoreIds = associatedStores.map(store => store.storeId)

        // 回显已选中的门店
        this.$nextTick(() => {
          this.stores.forEach((row) => {
            // 检查当前门店是否在关联门店列表中
            if (associatedStoreIds.includes(row.storeId)) {
              this.$refs.table.toggleRowSelection(row, true)
            }
          })
        })
        this.loading = false
      }).catch(error => {
        console.error('获取门店信息失败:', error)
        this.loading = false
      })
    }
  },
  methods: {
    /** 单击选中行数据 */
    clickRow(row) {
      if (this.checkSelectable(row)) {
        this.$refs.table.toggleRowSelection(row)
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.storeIds = selection.map((item) => item.storeId)
    },
    // 保存选中的数据编号
    getRowKey(row) {
      return row.storeId
    },
    // 检查门店状态：API返回数据中没有status字段，所有门店都可以选择
    checkSelectable(row) {
      return true
    },
    /** 提交按钮 */
    submitForm() {
      const userId = this.$route.params.userId
      // 直接传递数组，后端期望Long数组类型
      const storeIds = this.storeIds
      console.log("00000000", userId)
      console.log("99999",storeIds)
      storeApi.updateUserStore({ userId: userId, storeIds: storeIds }).then(() => {
        this.$message.success("授权成功")
        this.close()
      }).catch((error) => {
        console.error('门店分配失败:', error)
        this.$message.error("授权失败")
      })
    },
    /** 关闭按钮 */
    close() {
      this.$router.push("/system/user")
    },
    // 日期格式化
    parseTime
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.form-header {
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
  margin-bottom: 20px;
  font-weight: 600;
}
</style>
