<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
      <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="projectId">
        <el-select  v-model="queryParams.projectId" placeholder="请选择项目" clearable size="small" >
          <el-option
            v-for="item in projectOptions"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="会员ID" prop="userId">
        <el-input
          style="width: 200px"
          v-model="queryParams.userId"
          placeholder="请输入会员ID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="会员昵称" prop="nickname">
        <el-input
          style="width: 200px"
          v-model="queryParams.nickname"
          placeholder="请输入会员昵称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </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 label="创建时间" prop="createTimeText">
        <el-date-picker
          v-model="createTimeText"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          @change="createChange"
          :default-time="['00:00:00', '23:59:59']"
        />
      </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="projectId">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.projectId !== null">{{ getProjectLabel(scope.row.projectId) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="会员ID" align="center" prop="userId" />
      <el-table-column label="昵称" align="center" prop="nickname" />
      <el-table-column label="头像" align="center">
        <template slot-scope="scope">
          <img  :src="scope.row.avatar" style="width:50px;height:50px" />
        </template>
      </el-table-column>
      <el-table-column label="所属销售" align="center" prop="companyUserNickName" />
      <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 {
      createTimeText: '',
      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,
        sTime:null,
        eTime:null,
      },
      projectOptions: [],
      selectedUser: [],
    };
  },
  created() {
    this.getDicts("sys_course_project").then(response => {
      this.projectOptions = response.data;
    });
    getUserList().then(res=>{
      if(res.code === 200) {
        this.companyUserList = res.data
      }
    });

    this.getList();
  },
  methods: {
    parseTime,
    formatDate(date) {
      if (!date) return ''

      // 确保 date 是 Date 对象
      let dateObj = date
      if (typeof date === 'string') {
        dateObj = new Date(date)
      }

      // 如果转换失败，返回空字符串
      if (!(dateObj instanceof Date) || isNaN(dateObj.getTime())) {
        return ''
      }

      // 使用更安全的格式化方法
      const year = dateObj.getFullYear()
      const month = String(dateObj.getMonth() + 1).padStart(2, '0')
      const day = String(dateObj.getDate()).padStart(2, '0')
      const hours = String(dateObj.getHours()).padStart(2, '0')
      const minutes = String(dateObj.getMinutes()).padStart(2, '0')
      const seconds = String(dateObj.getSeconds()).padStart(2, '0')

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    createChange(createTime) {
      if (createTime && createTime.length >= 2) {
        if(!this.checkDateRangeLimit(createTime)){
          this.createTimeText = null;
          this.queryParams.sTime=null;
          this.queryParams.eTime=null;
          return;
        }
        // this.createTimeText = this.formatDateRange(createTime);
        this.queryParams.sTime = this.formatDate(createTime[0]) || null;
        this.queryParams.eTime = this.formatDate(createTime[1]) || null;
      } else {
        this.createTimeText = '';
        this.queryParams.sTime = null;
        this.queryParams.eTime = null;
      }
    },
    checkDateRangeLimit(dateRange) {
      if (dateRange && dateRange.length >= 2) {
        const startDate = new Date(dateRange[0]);
        const endDate = new Date(dateRange[1]);

        // 设置时间为当天开始，避免时间部分影响计算
        startDate.setHours(0, 0, 0, 0);
        endDate.setHours(0, 0, 0, 0);

        const timeDiff = Math.abs(endDate - startDate);
        const diffDays = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));

        if (diffDays > 31) { // maxDays-1 因为包含起始日
          this.$message.warning('时间区间不能超过一个月');
          return false;
        }
      }
      return true;
    },
    /** 查询客户列表 */
    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.createTimeText = '';
      this.queryParams.sTime = null;
      this.queryParams.eTime = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.selectedUser = selection.map(item => {return {userId: item.userId, projectId: item.projectId}})
      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.selectedUser,
            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() {});
    },
    /** 获取项目对应名称 */
    getProjectLabel(projectId) {
      return this.projectOptions.find(item => parseInt(item.dictValue) === projectId)?.dictLabel;
    },

  }
};
</script>

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