<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="销售" prop="salesName">
        <el-select v-model="queryParams.companyUserId" remote placeholder="请选择" filterable clearable  style="width: 100%;" @keyup.enter.native="handleQuery">
          <el-option
            v-for="dict in companyUserList"
            :key="`${dict.nickName} - ${dict.userName}`"
            :label="`${dict.nickName} - ${dict.userName}`"
            :value="dict.userId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input
          style="width: 220px"
          v-model="queryParams.phone"
          placeholder="请输入手机号码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" 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="warning"
          icon="el-icon-d-arrow-right"
          size="mini"
          :disabled="multiple"
          @click="handleTransfer"
          v-hasPermi="['company:user:transfer']"
        >转移</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table height="500" border v-loading="loading" :data="customerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="客户ID" align="center" prop="userId" />
      <el-table-column label="昵称" align="center" prop="nickname" />
      <el-table-column label="所属销售" align="center" prop="companyUserName" />
      <el-table-column label="手机号码" align="center" prop="phone" />
      <el-table-column label="状态" align="center" prop="statusText" >
        <template slot-scope="scope">
          <el-tag :type="scope.row.statusText === '正常' ? 'success' : 'danger'">{{ scope.row.statusText }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </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="客户转移" :visible.sync="openTransferDialog" width="500px" append-to-body>
      <el-form ref="transferForm" :model="transferForm" label-width="100px" :rules="cusTransfer">
        <el-alert
          title="会经过总后台审核后才进行转移"
          type="warning">
        </el-alert>
        <el-form-item label="转移至销售" prop="targetUserId">
          <el-select v-model="transferForm.targetUserId" remote placeholder="请选择" filterable clearable>
            <el-option
              v-for="dict in companyUserList"
              :key="`${dict.nickName} - ${dict.userName}`"
              :label="`${dict.nickName} - ${dict.userName}`"
              :value="dict.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="转移原因" prop="content">
          <el-input type="textarea" v-model="transferForm.content" placeholder="转移原因"></el-input>
        </el-form-item>
        <p>确定要转移选中的 <strong>{{ ids.length }}</strong> 个客户吗？</p>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" @click="submitTransfer">提交申请</el-button>
        <el-button @click="cancelTransfer">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listUser, transferUser} from "@/api/users/user";
import {parseTime} from "../../../utils/common";
import {getUserList} from "@/api/company/companyUser"; // 假设API文件路径

export default {
  name: "CustomerTransfer",
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      openTransferDialog: false,
      total: 0,
      customerList: [],
      companyUserList: [],
      transferForm: {
        targetUserId: null,
        content: null
      },
      cusTransfer: {
        targetUserId: [{required: true, message: '请选择转移至销售', trigger: 'change'}],
        content: [{required: true, message: '请选择转移至销售', trigger: 'change'}]
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        salesName: null,
        phoneNumber: null,
      },
    };
  },
  created() {
    getUserList().then(res=>{
      if(res.code === 200) {
        this.companyUserList = res.data
      }
    });

    this.getList();
  },
  methods: {
    parseTime,
    /** 查询客户列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
        this.customerList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    cancelTransfer() {
      this.openTransferDialog = false;
      this.resetTransferForm();
    },
    resetTransferForm() {
      this.transferForm = {
        targetUserId: null,
        content: null
      };
      this.resetForm("transferForm"); // 假设 transferForm 是 el-form 的 ref
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /** 转移按钮操作 */
    handleTransfer(row) {
      const userIds = row.userId ? [row.userId] : this.ids;
      if (userIds.length === 0) {
        this.$message.warning("请至少选择一个客户进行转移");
        return;
      }

      this.resetTransferForm();
      this.openTransferDialog = true;
    },

    /** 提交转移按钮 (如果使用对话框) */

    submitTransfer() {
      this.$refs["transferForm"].validate(valid => {
        if (valid) {
          transferUser({
            userIds: this.ids,
            targetCompanyUserId: this.transferForm.targetUserId,
            content: this.transferForm.content
          }).then(response => {
            if (response.code === 200) {
              this.msgSuccess(response.msg);
              this.openTransferDialog = false;
              this.getList();
            } else {
              this.msgError(response.msg || "转移失败");
            }
          }).catch(() => {
             this.msgError("转移请求失败");
          });
        }
      });
    },


    /** 导出按钮操作 */

    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有符合条件的客户数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          // 调用 exportCustomer API
          return exportCustomer(queryParams);
        }).then(response => {
          // 处理下载
          this.download(response.msg); // RuoYi 提供的下载方法
        }).catch(function() {});
    }

  }
};
</script>

<style scoped>
/* 可以添加一些自定义样式 */
.mb8 {
  margin-bottom: 8px;
}
</style>
