<template>
  <div class="container">
    <el-card>
      <!-- 搜索表单 -->
      <el-form :model="query" inline class="search-form">
        <el-form-item label="客户名称">
          <el-input
            v-model="query.orgname"
            placeholder="请输入客户名称"
            size="small"
            clearable
            @keyup.enter.native="handleSearch">
          </el-input>
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input
            v-model="query.contactor_phone"
            placeholder="请输入联系方式"
            size="small"
            clearable
            @keyup.enter.native="handleSearch">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="handleSearch">搜索</el-button>
          <el-button size="small" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 客户表格 -->
      <el-table
        v-loading="loading"
        ref="table"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        height="calc(100vh - 320px)">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="orgname" label="客户名称">
          <template slot-scope="scope">
            {{ scope.row.orgname || scope.row.contactor_phone || '未知客户' }}
          </template>
        </el-table-column>
        <el-table-column label="联系方式" prop="contactor_phone"></el-table-column>
        <el-table-column prop="address" label="地址" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.address || '未填写地址' }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="query.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="query.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>

      <!-- 操作按钮 -->
      <div class="button-container">
        <el-button @click="selectSales()" size="small" type="primary" :disabled="!hasSelection" class="action-button">
          选择销售
        </el-button>
        <el-button @click="cancelSelection()" size="small" type="primary" :disabled="!hasSelection"
          class="action-button">
          取消选择
        </el-button>
      </div>
    </el-card>

    <!-- 选择销售对话框 -->
    <el-dialog class="myDialog" title="选择销售人员" :visible.sync="isShow" width="30%" :before-close="handleClose">
      <el-form ref="form" :model="form" label-width="130px">
        <el-form-item label="请选择销售人员:" style="width: 100%;" prop="sales">
          <div class="radio-group-container">
            <el-radio-group v-model="form.id">
              <div class="radio-item" v-for="(item, index) in salesData" :key="index">
                <el-radio :label="item.id">{{ item.username }}</el-radio>
              </div>
            </el-radio-group>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="cancel()">取 消</el-button>
        <el-button size="small" type="primary" @click="salesSubmit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getNoinvitationcodeAPI, getSalesAPI, addUserCustomerAPI } from "@/api/sales/sales";

export default {
  data() {
    return {
      loading: false,
      tableData: [],
      salesData: [],
      isShow: false,
      total: 0,
      form: {
        username: '',
        id: ''
      },
      customerid: [], // 客户的id
      hasSelection: false, // 跟踪是否有选中项
      userId: sessionStorage.getItem("userId"),
      orgid: sessionStorage.getItem("orgid"),
      query: {
        page: 1,
        size: 10,
        orgid: this.orgid,
        orgname: '',
        contactor_phone: ''
      },
    };
  },
  created() {
    this.loading = true;
    this.getNoinvitationcode();
  },
  methods: {
    getNoinvitationcode() { // 获取全部客户
      this.loading = true;
      getNoinvitationcodeAPI(this.query).then(res => {
        this.loading = false;
        this.tableData = res.data.rows;
        this.total = res.pagination.total;
      }).catch(() => {
        this.loading = false;
      });
    },
    getSales() { // 展示所有销售人员
      getSalesAPI({ role: "销售", userid: this.userId }).then(res => {
        if (res.data && res.data.length > 0) {
          this.salesData = res.data.map((item) => {
            return {
              username: item.username,
              id: item.id,
            };
          });
        } else {
          this.salesData = [];
        }
      });
    },
    selectSales() {
      this.getSales();
      this.isShow = true;
    },
    handleSelectionChange(val) {
      // 更新选中的客户ID数组
      this.customerid = val.map(item => item.id);
      // 更新是否有选中项的状态
      this.hasSelection = this.customerid.length > 0;
    },
    cancelSelection() {
      this.$refs.table.clearSelection();
      this.hasSelection = false;
      this.customerid = [];
    },
    handleClose() {
      this.isShow = false;
    },
    salesSubmit() {
      // 确保至少选择了一个客户和一个销售
      if (this.customerid.length === 0) {
        this.$message({
          message: '请至少选择一个客户!',
          type: 'warning'
        });
        return;
      }
      if (!this.form.id) {
        this.$message({
          message: '请选择销售人员!',
          type: 'warning'
        });
        return;
      }

      let formData = new FormData();
      // API 期望 customerid 是 JSON 字符串化的数组
      formData.append('customerid', JSON.stringify(this.customerid));
      formData.append('salemanid', this.form.id);

      addUserCustomerAPI(formData).then(res => {
        if (res.status == true) {
          this.isShow = false;
          this.getNoinvitationcode(); // 刷新客户列表
          // 清空选择状态
          this.$refs.table.clearSelection();
          this.hasSelection = false;
          this.customerid = [];
          this.form.id = ''; // 清空已选销售
          this.$message({
            message: '分配成功!',
            type: 'success'
          });
        } else {
          this.$message({
            message: res.message || '分配失败!',
            type: 'error'
          });
        }
      }).catch(error => {
        this.$message({
          message: '分配请求出错: ' + error.message,
          type: 'error'
        });
      });
    },
    cancel() {
      this.isShow = false;
    },
    handleSearch() {
      this.query.page = 1; // 搜索时重置到第一页
      this.getNoinvitationcode();
    },
    handleReset() {
      this.query = {
        page: 1,
        size: 10,
        orgid: this.orgid,
        orgname: '',
        contactor_phone: ''
      };
      this.getNoinvitationcode();
    },
    handleSizeChange(size) {
      this.query.size = size;
      this.getNoinvitationcode();
    },
    handleCurrentChange(page) {
      this.query.page = page;
      this.getNoinvitationcode();
    }
  }
};
</script>

<style lang="less" scoped>
.container {
  padding: 20px;

  .search-form {
    margin-bottom: 20px;

    .el-form-item {
      margin-bottom: 10px;
      margin-right: 15px;
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }

  .button-container {
    margin-top: 20px;
    display: flex;
    gap: 10px;

    .action-button {
      padding: 8px 16px;
      font-size: 14px;
      border-radius: 4px;
    }
  }

  .myDialog {
    .radio-group-container {
      max-height: 200px;
      overflow-y: auto;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      padding: 10px;
    }

    .radio-item {
      margin-bottom: 8px;
      padding: 5px;
      border-radius: 4px;
      transition: background-color 0.3s;

      &:hover {
        background-color: #f5f7fa;
      }

      &:last-child {
        margin-bottom: 0;
      }
    }

    .dialog-footer {
      display: flex;
      justify-content: center;
    }
  }
}
/deep/.el-table__row{
  height: 62px!important;
}
</style>
