<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="链接名称" prop="linkName">
        <el-input
          v-model="queryParams.linkName"
          placeholder="请输入链接名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="企业微信" prop="corpName">
        <el-input
          v-model="queryParams.corpName"
          placeholder="请输入企业微信"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list" border>
      <el-table-column label="链接名称" align="center" prop="linkName" />
      <el-table-column label="企业微信" align="center" prop="corpName" />
      <el-table-column label="渠道链接" align="center" prop="url" show-overflow-tooltip />
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="最后修改人" align="center" prop="updateBy" />
      <el-table-column label="修改时间" align="center" prop="updateTime" />
      <el-table-column label="今日添加数" align="center" prop="toDayAddNum" />
      <el-table-column label="累积添加数" align="center" prop="countAddNum" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleViewChannel(scope.row)">查看渠道</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="链接名称" prop="linkName">
          <el-input v-model="form.linkName" placeholder="请输入链接名称" />
        </el-form-item>
        <el-form-item label="企业微信" prop="corpId">
          <el-select v-model="form.corpId" placeholder="请选择企业微信" @change="handleCorpChange">
            <el-option v-for="item in qwCompanyList" :key="item.corpId" :label="item.corpName" :value="item.corpId" />
          </el-select>
        </el-form-item>
        <el-form-item label="自动通过好友" prop="skipVerify">
          <div style="display: flex; align-items: center; height: 32px;">
            <el-switch v-model="form.skipVerify" :active-value="1" :inactive-value="0" />
          </div>
        </el-form-item>
        <el-form-item label="员工选择" prop="linkUser">
          <div>
            <el-button
              size="medium"
              icon="el-icon-circle-plus-outline"
              plain
              @click="handleSelectUser">请选择员工</el-button>
          </div>
          <div style="margin-top: 10px;">
            <el-table :data="personnelList" border size="small" style="margin-top: 10px;">
              <el-table-column label="企微号" align="center" prop="qwUserId" width="120px" />
              <el-table-column label="企微姓名" align="center" prop="qwUserName" width="120px" />
              <el-table-column label="操作" align="center" width="80px">
                <template slot-scope="scope">
                  <el-button type="danger" size="mini" icon="el-icon-delete" @click="handleRemovePersonnel(scope.row)"></el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看渠道链接对话框 -->
    <el-dialog title="查看渠道链接" :visible.sync="channelDialogOpen" width="900px" append-to-body @close="cancelChannel">
      <!-- 查询表单 -->
      <el-form :model="channelQueryParams" ref="channelQueryForm" :inline="true" v-show="channelShowSearch" label-width="68px">
        <el-form-item label="渠道名称" prop="linkName">
          <el-input
            v-model="channelQueryParams.linkName"
            placeholder="请输入渠道名称"
            clearable
            size="small"
            @keyup.enter.native="getChannelList"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="getChannelList">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetChannelQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAddChannel"
          >新增</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="channelShowSearch" @queryTable="getChannelList"></right-toolbar>
      </el-row>

      <!-- 渠道列表 -->
      <el-table v-loading="channelLoading" :data="channelList" border>
        <el-table-column label="渠道名称" align="center" prop="linkName" />
        <el-table-column label="渠道链接" align="center" prop="url" show-overflow-tooltip />
        <el-table-column label="今日添加数" align="center" prop="toDayAddNum" />
        <el-table-column label="累积添加数" align="center" prop="countAddNum" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteChannel(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="channelTotal>0"
        :total="channelTotal"
        :page.sync="channelQueryParams.pageNum"
        :limit.sync="channelQueryParams.pageSize"
        @pagination="getChannelList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelChannel">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 新增渠道对话框 -->
    <el-dialog title="选择渠道" :visible.sync="selectChannelDialogOpen" width="900px" append-to-body>
      <el-row :gutter="20">
        <!-- 左侧：分组和渠道选择 -->
        <el-col :xs="24" :sm="12">
          <div style="border-right: 1px solid #dcdfe6; padding-right: 20px;">
            <h4 style="margin-top: 0; margin-bottom: 15px;">分组管理</h4>
            <div style="margin-bottom: 15px;">
              <el-input 
                v-model="selectChannelQueryParams.channelName" 
                placeholder="搜索分组"
                clearable
                size="small"
                @input="loadGroupList"
              />
            </div>
            <div style="border: 1px solid #dcdfe6; border-radius: 4px; max-height: 400px; overflow-y: auto;">
              <div 
                v-for="item in groupList" 
                :key="item.id"
                :class="['group-item', { active: selectedGroupId === item.id }]"
                @click="selectGroup(item)"
                style="padding: 10px 15px; cursor: pointer; border-bottom: 1px solid #f0f0f0; user-select: none;"
              >
                <span>{{ item.channelName }}</span>
              </div>
              <div v-if="groupList.length === 0" style="padding: 20px; text-align: center; color: #909399;">暂无分组</div>
            </div>
          </div>
        </el-col>
    
        <!-- 中间：渠道列表 -->
        <el-col :xs="24" :sm="12">
          <div style="padding: 0 20px;">
            <h4 style="margin-top: 0; margin-bottom: 15px;">渠道模板</h4>
            <div v-if="!selectedGroupId" style="padding: 40px 0; text-align: center; color: #909399;">
              请上方选择分组
            </div>
            <div v-else>
              <div style="border: 1px solid #dcdfe6; border-radius: 4px; max-height: 400px; overflow-y: auto;">
                <div 
                  v-for="item in selectChannelList" 
                  :key="item.id"
                  style="padding: 10px 15px; border-bottom: 1px solid #f0f0f0; display: flex; align-items: center; user-select: none; cursor: pointer; background-color: #fff; transition: all 0.3s;"
                  :style="{ backgroundColor: isChannelSelected(item) ? '#e6f7ff' : '#fff' }"
                  @click="toggleChannelSelection(item)"
                >
                  <el-checkbox 
                    :value="isChannelSelected(item)"
                    style="margin-right: 8px;"
                  />
                  <span>{{ item.channelName }}</span>
                </div>
                <div v-if="selectChannelList.length === 0" style="padding: 20px; text-align: center; color: #909399;">暂无渠道</div>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    
      <!-- 右侧：已选渠道 -->
      <div style="margin-top: 20px; padding-top: 20px; border-top: 1px solid #dcdfe6;">
        <h4 style="margin-top: 0; margin-bottom: 10px;">已选渠道（{{ selectedChannels.length }}）</h4>
        <div style="border: 1px solid #dcdfe6; border-radius: 4px; padding: 10px; min-height: 80px; max-height: 150px; overflow-y: auto;">
          <el-tag 
            v-for="(item, index) in selectedChannels" 
            :key="item.channelId || index"
            closable
            @close="removeSelectedChannel(item)"
            style="margin: 5px; cursor: pointer;"
          >
            {{ item.channelName }}
          </el-tag>
          <div v-if="selectedChannels.length === 0" style="color: #909399; text-align: center; padding: 20px 0;">未选择任何渠道</div>
        </div>
      </div>
    
      <div slot="footer" class="dialog-footer">
        <el-button @click="selectChannelDialogOpen = false">取 消</el-button>
        <el-button type="primary" @click="confirmAddChannel">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 选择员工对话框 -->
    <el-dialog :title="selectUserDialog.title" :visible.sync="selectUserDialog.open" width="1300px" append-to-body>
      <qwUserList ref="QwUserList" @selectUserList="selectUserList"></qwUserList>
    </el-dialog>
  </div>
</template>

<script>
import {
  pageCustomerLink,
  getCustomerLink,
  createOrUpdateCustomerLink,
  deleteCustomerLink,
  pageCustomerLinkChannel,
  createCustomerLinkChannel,
  deleteCustomerLinkChannel
} from '@/api/qw/customerLink'
import { getMyQwCompanyList, listUser } from '@/api/qw/user'
import { pageProject } from '@/api/adv/channel'
import qwUserList from '@/views/qw/user/qwUserList.vue'
import Pagination from '@/components/Pagination'
import RightToolbar from '@/components/RightToolbar'

export default {
  name: 'CustomerLink',
  components: {
    qwUserList,
    Pagination,
    RightToolbar
  },
  data() {
    return {
      // 加载状态
      loading: false,
      channelLoading: false,
      // 是否显示查询表单
      showSearch: true,
      channelShowSearch: true,
      // 列表数据
      list: [],
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        linkName: undefined,
        corpName: undefined
      },
      // 表单参数
      form: {},
      // 表单验证规则
      rules: {
        linkName: [
          { required: true, message: '请输入链接名称', trigger: 'blur' }
        ],
        corpId: [
          { required: true, message: '请选择企业微信', trigger: 'change' }
        ],
        linkUser: [
          { required: true, message: '请选择员工', trigger: 'change' }
        ]
      },
      // 对话框
      open: false,
      title: '',
      // 企业微信列表
      qwCompanyList: [],
      // 企业微信员工列表
      qwUserList: [],
      // 分配规则人员列表
      personnelList: [],
      // 选择员工对话框
      selectUserDialog: {
        title: "选择员工",
        open: false
      },
      
      // 渠道链接对话框
      channelDialogOpen: false,
      channelList: [],
      channelTotal: 0,
      channelQueryParams: {
        pageNum: 1,
        pageSize: 10,
        linkName: undefined,
        sysLinkId: undefined
      },
      // 新增渠道对话框
      selectChannelDialogOpen: false,
      selectChannelParams: {
        channelId: undefined
      },
      channelOptions: [],
      currentSysLinkId: undefined,
      
      // 渠道选择相关数据
      groupList: [],  // 分组列表
      selectedGroupId: null,  // 选中的分组ID
      selectChannelList: [],  // 当前分组的渠道列表
      selectChannelLoading: false,  // 渠道列表加载中
      selectedChannels: [],  // 已选择的渠道列表（右侧）
      selectChannelPageNum: 1,
      selectChannelPageSize: 10,
      selectChannelTotal: 0,
      selectChannelQueryParams: {
        channelName: ''
      }
    }
  },
  created() {
    this.getList()
    this.loadQwCompanyList()
  },
  methods: {
    // 查询列表
    getList() {
      this.loading = true
      pageCustomerLink(this.queryParams).then(response => {
        this.list = response.data.records || []
        this.total = response.data.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 搜索
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置查询
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 新增
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新增渠道管理'
    },
    // 编辑
    handleUpdate(row) {
      this.reset()
      this.open = true
      this.title = '编辑渠道管理'
      // 调用详情接口获取按键数据
      getCustomerLink(row.id).then(response => {
        this.form = response.data
        // 从 qwCustomerLinkUsers 映射到 personnelList
        if (this.form.qwCustomerLinkUsers && Array.isArray(this.form.qwCustomerLinkUsers)) {
          this.personnelList = this.form.qwCustomerLinkUsers.map(user => ({
            sysQwUserId: user.sysQwUserId,
            qwUserName: user.qwUserName,
            qwUserId: user.qwUserId
          }))
          // 同步 linkUser
          this.form.linkUser = this.personnelList
        }
        this.loadQwUserList(this.form.corpId)
      })
    },
    // 删除
    handleDelete(row) {
      this.$confirm('确定删除该渠道吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteCustomerLink(row.id).then(response => {
          this.$message.success('删除成功')
          this.getList()
        })
      }).catch(() => {})
    },
    // 查看渠道链接
    handleViewChannel(row) {
      this.channelDialogOpen = true
      this.currentSysLinkId = row.id
      this.channelQueryParams.sysLinkId = row.id
      this.getChannelList()
    },
    // 查询渠道链接列表
    getChannelList() {
      this.channelLoading = true
      pageCustomerLinkChannel(this.channelQueryParams).then(response => {
        this.channelList = response.data.records || []
        this.channelTotal = response.data.total || 0
        this.channelLoading = false
      }).catch(() => {
        this.channelLoading = false
      })
    },
    // 重置渠道查询
    resetChannelQuery() {
      this.channelQueryParams = {
        pageNum: 1,
        pageSize: 10,
        linkName: undefined,
        sysLinkId: this.currentSysLinkId
      }
      this.getChannelList()
    },
    // 新增渠道链接
    handleAddChannel() {
      this.selectChannelDialogOpen = true
      this.selectedChannels = []
      this.selectedGroupId = null
      this.selectChannelList = []
      this.selectChannelQueryParams.channelName = ''
      this.loadGroupList()
    },
    // 加载分组列表
    loadGroupList() {
      const params = { pageNum: 1, pageSize: 1000, parentId: 0 }
      pageProject(params).then(response => {
        this.groupList = response.data.records || []
      }).catch(() => {
        this.groupList = []
      })
    },
    // 选择分组
    selectGroup(group) {
      this.selectedGroupId = group.id
      this.selectChannelPageNum = 1
      this.getSelectChannelList()
    },
    // 获取渠道列表
    getSelectChannelList() {
      if (!this.selectedGroupId) return
      this.selectChannelLoading = true
      const params = { pageNum: this.selectChannelPageNum, pageSize: this.selectChannelPageSize, parentId: this.selectedGroupId }
      if (this.selectChannelQueryParams.channelName) {
        params.channelName = this.selectChannelQueryParams.channelName
      }
      pageProject(params).then(response => {
        this.selectChannelList = response.data.records || []
        this.selectChannelTotal = response.data.total || 0
        this.selectChannelLoading = false
      }).catch(() => {
        this.selectChannelLoading = false
      })
    },
    // 勾选渠道
    toggleChannelSelection(channel) {
      const index = this.selectedChannels.findIndex(item => item.channelId === channel.id)
      if (index > -1) {
        // 已选中，取消选择
        this.selectedChannels.splice(index, 1)
      } else {
        // 未选中，添加选择
        this.selectedChannels.push({ channelId: channel.id, channelName: channel.channelName })
      }
    },
    // 判断渠道是否已选择
    isChannelSelected(channel) {
      return this.selectedChannels.some(item => item.channelId === channel.id)
    },
    // 删除已选渠道
    removeSelectedChannel(channel) {
      const index = this.selectedChannels.findIndex(item => item.channelId === channel.channelId)
      if (index > -1) {
        this.selectedChannels.splice(index, 1)
      }
    },
    // 加载渠道选项
    loadChannelOptions() {
      // 这里需要加载渠道列表，根据实际接口调整
      // 暂时使用空数组，需要后续实现
      this.channelOptions = []
    },
    // 确认新增渠道
    confirmAddChannel() {
      if (this.selectedChannels.length === 0) {
        this.$message.error('请选择渠道')
        return
      }
      const data = {
        sysLinkId: this.currentSysLinkId,
        channelList: this.selectedChannels
      }
      createCustomerLinkChannel(data).then(response => {
        this.$message.success('新增成功')
        this.selectChannelDialogOpen = false
        this.getChannelList()
      })
    },
    // 删除渠道链接
    handleDeleteChannel(row) {
      this.$confirm('确定删除该渠道链接吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteCustomerLinkChannel(row.id).then(response => {
          this.$message.success('删除成功')
          this.getChannelList()
        })
      }).catch(() => {})
    },
    // 关闭渠道链接对话框
    cancelChannel() {
      this.channelDialogOpen = false
      this.currentSysLinkId = undefined
    },
    // 表单提交
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 将 personnelList 赋值给 form.linkUser
          this.form.linkUser = this.personnelList.map(p => ({
            sysQwUserId: p.sysQwUserId,
            qwUserName: p.qwUserName,
            qwUserId: p.qwUserId
          }))
          const data = {
            linkName: this.form.linkName,
            corpId: this.form.corpId,
            corpName: this.form.corpName,
            skipVerify: this.form.skipVerify,
            linkUser: this.form.linkUser
          }
          if (this.form.id) {
            data.id = this.form.id
          }
          createOrUpdateCustomerLink(data).then(response => {
            this.$message.success(this.form.id ? '编辑成功' : '新增成功')
            this.open = false
            this.getList()
          })
        }
      })
    },
    // 重置表单
    reset() {
      this.form = {
        linkName: undefined,
        corpId: undefined,
        corpName: undefined,
        skipVerify: 0,
        linkUser: []
      }
      this.personnelList = []
      this.qwUserList = []
      if (this.$refs.form) {
        this.$refs.form.clearValidate()
      }
    },
    // 取消
    cancel() {
      this.open = false
      this.reset()
    },
    // 加载企业微信列表
    loadQwCompanyList() {
      getMyQwCompanyList().then(response => {
        this.qwCompanyList = response.data || []
      }).catch(() => {
        this.qwCompanyList = []
      })
    },
    // 企业微信改变
    handleCorpChange(corpId) {
      this.personnelList = []
      this.form.linkUser = []
      this.qwUserList = []
      const selectedCompany = this.qwCompanyList.find(item => item.corpId === corpId)
      if (selectedCompany) {
        this.form.corpName = selectedCompany.corpName
      }
      // 不加载员工列表，等待用户点击"请选择员工"按钮时再加载
    },
    // 加载企业微信员工列表
    loadQwUserList(corpId) {
      if (!corpId) {
        this.qwUserList = []
        return
      }
      listUser({ corpId: corpId }).then(response => {
        this.qwUserList = response.rows || []
      }).catch(() => {
        this.qwUserList = []
      })
    },
    // 选择员工
    handleSelectUser() {
      if (!this.form.corpId) {
        this.$message.warning('请先选择企业微信')
        return
      }
      this.selectUserDialog.open = true
      this.$nextTick(() => {
        // 传递 corpId 给 qwUserList 组件，确保加载正确的企业微信员工
        this.$refs.QwUserList.getDetails(this.form.corpId, null, null, null)
      })
    },

    /** 接收选中的员工 */
    selectUserList(selectUsers) {
      this.selectUserDialog.open = false
      if (selectUsers && selectUsers.length > 0) {
        selectUsers.forEach(user => {
          const exists = this.personnelList.find(p => p.sysQwUserId === user.id)
          if (!exists) {
            this.personnelList.push({
              sysQwUserId: user.id,
              qwUserName: user.qwUserName,
              qwUserId: user.qwUserId
            })
          }
        })
        // 更新 form.linkUser
        this.form.linkUser = this.personnelList.map(p => ({
          sysQwUserId: p.sysQwUserId,
          qwUserName: p.qwUserName,
          qwUserId: p.qwUserId
        }))
      }
    },

    /** 移除员工 */
    handleRemovePersonnel(item) {
      const index = this.personnelList.findIndex(p => p.qwUserId === item.qwUserId)
      if (index > -1) {
        this.personnelList.splice(index, 1)
      }
    },
    // 表单重置
    resetForm(refName) {
      if (this.$refs[refName]) {
        this.$refs[refName].resetFields()
      }
    }
  }
}
</script>

<style scoped>
</style>
