<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="6" :xs="24">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>个人信息</span>
          </div>
          <div>
            <div class="text-center">
              <userAvatar :user="user" />
            </div>
            <ul class="list-group list-group-striped">
              <li class="list-group-item">
                <svg-icon icon-class="user" />用户名称
                <div class="pull-right">{{ user.userName }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="phone" />手机号码
                <div class="pull-right">{{ user.phonenumber }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="email" />用户邮箱
                <div class="pull-right">{{ user.email }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="tree" />所属部门
                <div class="pull-right" v-if="user.dept">{{ user.dept.deptName }} / {{ postGroup }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="peoples" />所属角色
                <div class="pull-right">{{ roleGroup }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="date" />创建日期
                <div class="pull-right">{{ user.createTime }}</div>
              </li>
            </ul>
            <div class="text-center" style="margin-top: 20px;">
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-user"
                @click="handleBindMember"
                v-if="!user.fsUserId"
              >绑定会员</el-button>

              <div v-if="user.fsUserIdArray && user.fsUserIdArray.length > 0" style="margin-top: 10px;">
                <el-tag type="success">已绑定会员</el-tag>
                <div style="margin-top: 10px;">
                  <div
                    v-for="(fsUserId, index) in user.fsUserIdArray"
                    :key="index"      style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 5px;"
                  >
                    <span style="font-size: 12px; color: #666;">会员ID: {{ fsUserId }}</span>
                    <el-button
                      size="mini"
                      type="danger"
                      icon="el-icon-delete"
                      @click="handleUnbindSpecificMember(fsUserId)"
                    >
                      解绑
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
            <div class="text-center" style="margin-top: 20px;" v-if="needWxTemplateMsg">
              <div v-if="user.wechatBindStatus">
                <el-tag type="success">已绑定服务号通知</el-tag>
              </div>
              <div v-else>
                <el-button type="primary" @click="openWechatBindDialog">
                  订阅服务号通知
                </el-button>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="18" :xs="24">
        <el-card>
          <div slot="header" class="clearfix">
            <span>基本资料</span>
          </div>
          <el-tabs v-model="activeTab">
            <el-tab-pane label="基本资料" name="userinfo">
              <userInfo :user="user" />
            </el-tab-pane>
            <el-tab-pane label="修改密码" name="resetPwd">
              <resetPwd :user="user" />
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>

    <!-- 绑定会员对话框 -->
    <el-dialog  v-if="member && member.hasOwnProperty('title')" :title="member.title" :visible.sync="member.open" width="600px" append-to-body>
      <!-- 添加筛选表单 -->
      <el-form :model="memberQueryParams" :inline="true" @submit.native.prevent>
        <el-form-item label="会员ID">
          <el-input
            v-model="memberQueryParams.userId"
            placeholder="请输入会员ID"
            clearable      style="width: 160px;"
            @keyup.enter.native="handleMemberQuery"
          />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input
            v-model="memberQueryParams.nickName"
            placeholder="请输入昵称"
            clearable            style="width: 160px;"
            @keyup.enter.native="handleMemberQuery"
          />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input
            v-model="memberQueryParams.phone"
            placeholder="请输入手机号"
            clearable            style="width: 160px;"
            @keyup.enter.native="handleMemberQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" size="mini" @click="handleMemberQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetMemberQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <div style="height: 300px; margin-top: 10px;">
        <el-table
          :data="memberList"
          height="220"
          highlight-current-row
          @current-change="selectMember"
          v-loading="loading"
        >
          <el-table-column property="userId" label="ID" width="80"></el-table-column>
          <el-table-column property="nickName" label="昵称" width="120"></el-table-column>
          <el-table-column property="phone" label="手机号" width="120"></el-table-column>
          <el-table-column property="status" label="绑定状态" width="100">
            <template slot-scope="scope">
              <el-tag
                :type="scope.row.status === 1 ? 'success' : 'info'"
                size="mini">
                {{ scope.row.status === 1 ? '已绑定' : '未绑定' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <pagination
          v-show="memberTotal > 0"
          :total="memberTotal"
          :page.sync="memberQueryParams.pageNum"
          :limit.sync="memberQueryParams.pageSize"
          @pagination="getMemberList"          style="margin-top: 10px; text-align: center;"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelBindMember">取 消</el-button>
        <el-button type="primary" @click="confirmBindMember">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="订阅服务号通知"
      :visible.sync="bindDialogVisible"
      width="360px"
      :close-on-click-modal="false"
    >
      <div class="text-center">
        <img v-if="wechatQrcode" :src="wechatQrcode" style="width: 260px; height: 260px;" />
        <p style="margin-top: 10px;">请使用微信扫码绑定服务号通知</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="bindDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import userAvatar from "./userAvatar";
import userInfo from "./userInfo";
import resetPwd from "./resetPwd";
import { getUserProfile,getSaleBindUserList, bindSaleAndFsUser, unbindSaleAndFsUser } from "@/api/company/companyUser";
import { getWechatBindQrcode, checkWechatBindStatus } from "@/api/wechat";
export default {
  name: "Profile",
  components: { userAvatar, userInfo, resetPwd },
  data() {
    return {
      user: {},
      roleGroup: {},
      postGroup: {},
      activeTab: "userinfo",
      bindDialogVisible: false,
      wechatQrcode: "",
      wechatBindTimer: null,
      needWxTemplateMsg: false,
      // 绑定会员相关数据
      member: {
        open: false,
        title: "绑定会员"
      },
      memberList: [],
      selectedMember: null,
      currentCompanyId: null,
      memberTotal: 0,
      loading: false,
      // 添加筛选参数
      memberQueryParams: {
        nickName: null,
        phone: null,
        userId: null,
        pageNum: 1,
        pageSize: 10
      },
    };
  },
  created() {
    if (process.env.VUE_APP_COMPANY_NAME ==="河北红德堂医药连锁有限公司保定第五十七分公司"){
      this.needWxTemplateMsg = true
    }
    this.getUser();
  },
  methods: {
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.roleGroup = response.roleGroup;
        this.postGroup = response.postGroup;
        // 将 fsUserId 字符串拆分为数组
        if (this.user.fsUserId) {
          this.user.fsUserIdArray = this.user.fsUserId.split(',').map(id => id.trim());
        } else {
          this.user.fsUserIdArray = [];
        }
      });
    },
    /**
     * 绑定会员按钮操作
     */
    handleBindMember() {
      // 设置当前用户的ID
      this.currentCompanyId = this.user.userId;
      // 重置筛选参数
      this.memberQueryParams = {
        nickName: null,
        phone: null,
        pageNum: 1,    // 重置为第一页
        pageSize: 10   // 保持每页数量
      };
      this.selectedMember = null;
      this.member.open = true;
      this.getMemberList();
    },

    /**
     * 解绑指定会员
     * @param {string} fsUserId - 要解绑的会员ID
     */
    handleUnbindSpecificMember(fsUserId) {
      // 弹出确认框
      this.$confirm(`确定要解除与会员 ${fsUserId} 的绑定吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          // 构造解绑参数
          const unbindData = {
            companyUserId: this.user.userId, // 销售ID
            userId: fsUserId                 // 会员ID
          };

          // 调用解绑接口
          unbindSaleAndFsUser(unbindData)
            .then(response => {
              if (response.code === 200) {
                this.$message.success("解绑成功");
                // 刷新用户信息
                this.getUser();
              } else {
                this.$message.error(response.msg || "解绑失败");
              }
            })
            .catch(error => {
              console.error("解绑失败:", error);
              this.$message.error("解绑失败");
            });
        })
        .catch(() => {
          this.$message.info("已取消解绑");
        });
    },
    /**
     * 获取会员列表
     */
    getMemberList() {
      this.loading = true;
      // 调用指定的接口获取会员列表
      getSaleBindUserList({
        pageNum: this.memberQueryParams.pageNum,
        pageSize: this.memberQueryParams.pageSize,
        nickName: this.memberQueryParams.nickName,
        phone: this.memberQueryParams.phone,
        userId: this.memberQueryParams.userId
      })
        .then(response => {
          this.memberList = response.rows || [];
          this.memberTotal = response.total || 0;
        })
        .catch(error => {
          console.error('获取会员列表失败:', error);
          this.$message.error('获取会员列表失败');
        })
        .finally(() => {
          this.loading = false;
        });
    },

    /**
     * 会员搜索按钮操作
     // */
    handleMemberQuery() {
      this.memberQueryParams.pageNum = 1;
      this.getMemberList();
    },

    /**
     * 会员重置按钮操作
     */
    resetMemberQuery() {
      this.memberQueryParams = {
        nickName: null,
        phone: null,
        userId: null,
        pageNum: 1,
        pageSize: 10
      };
      this.getMemberList();
    },

    /**
     * 选择会员
     */
    selectMember(member) {
      if (member) {
        this.selectedMember = member;
      }
    },

    /**
     * 确认绑定会员
     */
    confirmBindMember() {
      if (!this.selectedMember) {
        this.$message.warning('请选择要绑定的会员');
        return;
      }

      // 这里需要根据实际接口调整参数
      const bindData = {
        companyUserId: this.currentCompanyId,
        userId: this.selectedMember.userId // 使用实际的用户ID字段
      };

      // 发起绑定请求
      bindSaleAndFsUser(bindData).then(response => {
        if (response.code === 200) {
          this.$message.success('绑定会员成功');
          this.cancelBindMember();
          // 刷新用户信息
          this.getUser();
        } else {
          this.$message.error(response.msg || '绑定失败');
        }
      })
        .catch(error => {
          console.error('绑定会员失败:', error);
          this.$message.error('绑定会员失败');
        });
    },

    /**
     * 取消绑定会员
     */
    cancelBindMember() {
      this.member.open = false;
      this.memberList = [];
      this.selectedMember = null;
      this.currentCompanyId = null;
      this.memberQueryParams = {
        nickName: null,
        phone: null
      };
    },
    openWechatBindDialog() {
      getWechatBindQrcode().then(res => {
        console.log(res)
        this.wechatQrcode = res.data.qrcodeUrl;
        this.bindDialogVisible = true;
        this.startCheckWechatBind(res.data.sceneId);
      });
    },
    startCheckWechatBind(sceneId) {
      // 清除旧定时器
      if (this.wechatBindTimer) clearInterval(this.wechatBindTimer);

      this.wechatBindTimer = setInterval(() => {
        checkWechatBindStatus(sceneId).then(res => {
          if (res.data === true) {
            this.$message.success("绑定成功！");
            clearInterval(this.wechatBindTimer);
            this.bindDialogVisible = false;
            this.getUser(); // 刷新绑定状态
          }
        });
      }, 2000);
    }
  },
  beforeDestroy() {
    if (this.wechatBindTimer) clearInterval(this.wechatBindTimer);
  }
};
</script>
