<template>
  <div class="session-layout">
    <!-- 左侧：客户列表 -->
    <div class="left-panel">
      <div class="left-panel-content">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">
          <el-form-item label="企微主体" prop="corpId">
            <el-select
              v-model="queryParams.corpId"
              placeholder="企微主体"
              size="small"
              clearable
              @change="handleCorpChange"
            >
              <el-option
                v-for="corp in corpList"
                :key="corp.corpId"
                :label="corp.corpName"
                :value="corp.corpId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="企微员工" prop="qwUserId">
            <el-select
              v-model="queryParams.qwUserId"
              placeholder="请选择员工"
              size="small"
              clearable
              filterable
              :disabled="!queryParams.corpId"
            >
              <el-option
                v-for="staff in staffList"
                :key="staff.id"
                :label="staff.qwUserName"
                :value="staff.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          </el-form-item>
        </el-form>

        <div class="left-table-wrapper">
          <el-table
            v-loading="loading"
            :data="externalContactList"
            border
            highlight-current-row
            @row-click="handleRowClick"
            height="100%"
          >
            <el-table-column label="头像" align="center" width="80px">
              <template slot-scope="scope">
                <el-popover placement="right" trigger="hover">
                  <img slot="reference" :src="scope.row.avatar" width="40px" style="border-radius:50%" />
                  <img :src="scope.row.avatar" style="max-width:200px" />
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column label="客户名称" prop="name" width="100px" />
            <el-table-column label="销售昵称" prop="qwUserName" width="100px" />
            <el-table-column label="添加时间" prop="createTime" width="100px" />
          </el-table>
        </div>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>

    <!-- 右侧：会话详情面板 -->
    <div class="right-panel">
      <ConversationPanel
        v-if="queryParams.corpId"
        :key="conversationPanelKey"
        :corpId="queryParams.corpId"
        :customerId="selectedCustomerId"
        :customerAvatar="selectedCustomerAvatar"
        :staffUserId="selectedStaffQwUserId"
        @logout="handleConversationLogout"
        @login-success="handleConversationLoginSuccess"
      />
      <div v-else class="empty-tip">
        <i class="el-icon-info"></i>
        <p>请先选择企微主体</p>
      </div>
    </div>
  </div>
</template>

<script>
import { listExternalContact } from "@/api/qw/externalContact";
import { getCompanyList } from "@/api/company/company";
import { getAllUserlist } from "@/api/company/companyUser";
import { allCorp } from "@/api/qw/qwCompany";
import { listAllQwUserList } from "@/api/qw/user";
import ConversationPanel from "./ConversationPanel.vue";

export default {
  name: "CompanySession",
  components: { ConversationPanel },
  data() {
    return {
      loading: false,
      total: 0,
      externalContactList: [],
      companyUserNameList: [],
      corpList: [],
      selectedCustomerId: null,
      selectedCustomerAvatar: null,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyId: null,
        companyUserName: null,
        corpId: null,
        extId: null,
        qwUserId: null
      },
      qwCompanyList: [],
      staffList: [],
      conversationPanelKey: 0,
      isInitialized: false,
      _logoutLock: false
    };
  },
  computed: {
    selectedStaffQwUserId() {
      if (!this.queryParams.qwUserId) return null;
      const staff = this.staffList.find(s => s.id === this.queryParams.qwUserId);
      return staff ? staff.qwUserId : null;
    }
  },
  created() {
    this.initData();
  },
  activated() {
    if (this.isInitialized) {
      this.conversationPanelKey++;
    }
  },
  methods: {
    async initData() {
      try {
        const [companyRes, corpRes] = await Promise.all([
          getCompanyList(),
          allCorp()
        ]);

        this.qwCompanyList = companyRes.data || [];
        if (this.qwCompanyList.length > 0) {
          this.queryParams.companyId = this.qwCompanyList[0].companyId;
          this.getAllUserlist(this.queryParams.companyId);
        }

        this.corpList = corpRes.data || [];
        if (this.corpList.length > 0) {
          this.queryParams.corpId = this.corpList[0].corpId;
          await this.fetchQwUserList(this.queryParams.corpId);
        }

        this.$nextTick(() => {
          this.isInitialized = true;
        });
      } catch (e) {
        console.error('初始化数据失败', e);
        this.isInitialized = true;
      }
    },

    handleConversationLogout() {
      if (this._logoutLock) return;
      this._logoutLock = true;

      this.selectedCustomerId = null;
      this.selectedCustomerAvatar = null;
      this.queryParams.qwUserId = null;
      this.externalContactList = [];
      this.total = 0;
      this.conversationPanelKey++;

      setTimeout(() => {
        this._logoutLock = false;
      }, 1000);
    },

    handleConversationLoginSuccess() {
      if (this.queryParams.corpId) {
        this.fetchQwUserList(this.queryParams.corpId);
      }
      if (this.queryParams.qwUserId) {
        this.handleQuery();
      }
    },

    handleCorpChange(corpId) {
      if (!this.isInitialized) return;

      this.queryParams.qwUserId = null;
      this.selectedCustomerId = null;
      this.selectedCustomerAvatar = null;
      this.externalContactList = [];
      this.total = 0;

      if (corpId) {
        this.fetchQwUserList(corpId);
      } else {
        this.staffList = [];
      }

      this.conversationPanelKey++;
    },

    async fetchQwUserList(corpId) {
      try {
        const res = await listAllQwUserList({ corpId });
        if (res.code === 200 && Array.isArray(res.data)) {
          this.staffList = res.data;
        } else if (Array.isArray(res)) {
          this.staffList = res;
        } else if (res.data && Array.isArray(res.data.list)) {
          this.staffList = res.data.list;
        } else {
          this.staffList = [];
        }
      } catch (e) {
        console.error('获取员工列表异常', e);
        this.staffList = [];
      }
    },

    getAllUserlist(companyId) {
      if (companyId) {
        getAllUserlist({ companyId }).then(response => {
          this.companyUserNameList = response.data || [];
        });
      }
    },

    getList() {
      if (!this.queryParams.corpId || !this.queryParams.qwUserId) {
        this.$message.warning('请完整选择企微主体和员工');
        return;
      }
      this.loading = true;
      listExternalContact(this.queryParams).then(response => {
        this.externalContactList = response.rows || [];
        this.total = response.total || 0;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    handleQuery() {
      if (!this.queryParams.qwUserId) {
        this.$message.warning('请先选择企微员工');
        return;
      }
      this.queryParams.pageNum = 1;
      this.getList();
    },

    handleRowClick(row) {
      this.selectedCustomerId = row.externalUserId;
      this.selectedCustomerAvatar = row.avatar;
    },
  }
};
</script>

<style scoped>
.session-layout {
  display: flex;
  height: calc(100vh - 90px);
  overflow: hidden;
}
.left-panel {
  width: 460px;
  min-width: 400px;
  flex-shrink: 0;
  border-right: 1px solid #e8e8e8;
  background: #fff;
  display: flex;
  flex-direction: column;
}
.left-panel-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 16px;
  box-sizing: border-box;
}
.left-table-wrapper {
  flex: 1;
  overflow: hidden;
  margin-bottom: 12px;
}
.right-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
}
.empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
  font-size: 16px;
}
.empty-tip i {
  font-size: 48px;
  margin-bottom: 16px;
}
</style>
