<template>
  <div class="app-container">
    <!-- Search Form -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <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: 200px"
          v-model="queryParams.phone"
          placeholder="请输入手机号码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!--      <el-form-item label="状态" prop="status">-->
      <!--        <el-select style="width: 200px" v-model="queryParams.status" placeholder="请选择状态" clearable size="small">-->
      <!--          <el-option-->
      <!--            v-for="item in statusOptions"-->
      <!--            :key="item.dictValue"-->
      <!--            :label="item.dictLabel"-->
      <!--            :value="item.dictValue"-->
      <!--          />-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="看课状态" prop="watchCourseType">-->
      <!--        <el-select style="width: 200px" v-model="queryParams.watchCourseType" placeholder="请选择看课状态" clearable size="small">-->
      <!--          <el-option label="全部" value="0" />-->
      <!--          <el-option label="未看过课" value="1" />-->
      <!--          <el-option label="正常看课" value="2" />-->
      <!--          <el-option label="停止看课" value="3" />-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="缺课状态" prop="missCourseStatus">-->
      <!--        <el-select style="width: 200px" v-model="queryParams.missCourseStatus" placeholder="请选择缺课状态" clearable size="small">-->
      <!--          <el-option label="全部" value="0" />-->
      <!--          <el-option label="已缺课" value="1" />-->
      <!--          <el-option label="未缺课" value="2" />-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="标签" prop="tagIds">-->
      <!--        <el-select style="width: 200px" v-model="queryParams.tagIds" placeholder="请选择标签" clearable size="small" multiple>-->
      <!--          <el-option-->
      <!--            v-for="item in tagOptions"-->
      <!--            :key="item.tagId"-->
      <!--            :label="item.tagName"-->
      <!--            :value="item.tagId"-->
      <!--          />-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
      <el-form-item label="注册时间">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
      </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>

    <!-- Tab Selection -->
    <!--    <el-tabs v-model="queryParams.tabValue" @tab-click="handleTabChange">-->
    <!--      <el-tab-pane label="全部" name="0"></el-tab-pane>-->
    <!--      <el-tab-pane label="今日新增" name="1"></el-tab-pane>-->
    <!--      <el-tab-pane label="今日完播" name="2"></el-tab-pane>-->
    <!--      <el-tab-pane label="未看过课" name="3"></el-tab-pane>-->
    <!--    </el-tabs>-->

    <!-- Toolbar -->
    <el-row :gutter="10" class="mb8">
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="primary"-->
      <!--          plain-->
      <!--          icon="el-icon-plus"-->
      <!--          size="mini"-->
      <!--          @click="handleAdd"-->
      <!--          v-hasPermi="['user:fsUser:add']"-->
      <!--        >新增</el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="success"-->
      <!--          plain-->
      <!--          icon="el-icon-edit"-->
      <!--          size="mini"-->
      <!--          :disabled="single"-->
      <!--          @click="handleUpdate"-->
      <!--          v-hasPermi="['user:fsUser:edit']"-->
      <!--        >编辑</el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="danger"-->
      <!--          plain-->
      <!--          icon="el-icon-delete"-->
      <!--          size="mini"-->
      <!--          :disabled="multiple"-->
      <!--          @click="handleDelete"-->
      <!--          v-hasPermi="['user:fsUser:remove']"-->
      <!--        >删除</el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--          plain-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['user:fsUser:export']"-->
      <!--        >导出</el-button>-->
      <!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- User Table -->
    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="项目会员id" align="center" prop="id" />-->
      <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="昵称" align="center" prop="nickname" />
      <el-table-column label="头像" align="center" width="80">
        <template slot-scope="scope">
          <el-popover
            placement="right"
            title=""
            trigger="hover"
          >
            <img slot="reference" :src="scope.row.avatar" width="50">
            <img :src="scope.row.avatar" style="max-width: 120px;">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="手机号码" align="center" prop="phone" />
      <el-table-column label="积分" align="center" prop="integral" v-if="false" />
      <el-table-column label="看课数量" align="center" prop="watchCourseCount" />
      <el-table-column label="缺课数量" align="center" prop="missCourseCount" />
      <el-table-column label="参与营期数量" align="center" prop="partCourseCount" />
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '正常' : '禁止' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="看课状态" align="center" width="80px">
        <template slot-scope="scope">
          <el-tag :type="getCourseStatusType(scope.row.courseCountStatus)">
            {{ getCourseStatusText(scope.row.courseCountStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="标签" align="center" prop="tag" show-overflow-tooltip />
      <el-table-column label="最后看课时间" align="center" prop="lastWatchDate" width="160" />
<!--      <el-table-column label="停课天数" align="center" prop="stopWatchDays" />-->
      <el-table-column label="注册时间" align="center" prop="createTime" width="160" />
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
      <el-table-column label="所属员工" align="center" prop="companyUserNickName" />
      <el-table-column label="会员积分" align="center" prop="integral" />
      <el-table-column label="是否购买" align="center" prop="isBuy">
        <template slot-scope="scope">
          <span>{{ scope.row.isBuy === 1 ? '是' : '否' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['store:user:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleAudit(scope.row)"
            v-if="scope.row.isCurrentCompanyUser === 1 && scope.row.status === 0"
          >审核会员</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handledetails(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"
    />

    <!-- Edit User Dialog -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="用户头像" prop="avatar">
          <el-popover
            placement="right"
            title=""
            trigger="hover"
          >
            <img slot="reference" :src="form.avatar" width="80">
            <img :src="form.avatar" style="max-width: 120px;">
          </el-popover>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" :disabled="true" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" disabled placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="最后登录IP" prop="lastIp" v-if="form.lastIp">
          <el-input v-model="form.lastIp" disabled placeholder="最后一次登录IP" />
        </el-form-item>
        <el-form-item label="看课数量" prop="watchCourseCount" v-if="form.watchCourseCount">
          <el-input v-model="form.watchCourseCount" disabled placeholder="看课数量" />
        </el-form-item>
        <el-form-item label="缺课数量" prop="missCourseCount" v-if="form.missCourseCount">
          <el-input v-model="form.missCourseCount" disabled placeholder="缺课数量" />
        </el-form-item>
        <!-- <el-form-item label="标签" prop="tagIds">
          <el-select v-model="form.tagIds" disabled placeholder="请选择标签" clearable multiple>
            <el-option
              v-for="item in tagOptions"
              :key="item.tagId"
              :label="item.tagName"
              :value="item.tagId"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="标签" prop="tag">
          <el-input v-model="form.tag" disabled  clearable >
          </el-input>
        </el-form-item>
        <el-form-item label="所属员工" prop="companyUserId">
          <el-select v-model="form.companyUserId" disabled placeholder="请选择所属员工" clearable>
            <el-option
              v-for="item in companyUserList"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入用户备注" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁止</el-radio>
          </el-radio-group>
        </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-drawer
        :with-header="false"
        size="75%"
          :title="show.title" :visible.sync="show.open">
      <userDetails  ref="userDetails" />
    </el-drawer>

  </div>
</template>

<script>
import {
  listUser,
  getMemberUser,
  addUser,
  updateUser,
  delUser,
  exportUser,
  auditUser,
  updateMemberUser
} from '@/api/user/fsUser'
import {getUserList} from "@/api/company/companyUser";
import userDetails from '@/views/store/components/userDetails.vue';
export default {
  name: "FsUser",
  components: {userDetails},
  data() {
    return {
      show:{
        open:false,
      },
      rowInfo:null,
      cusTransfer: {
        targetUserId: [{required: true, message: '请选择转移至销售', trigger: 'change'}],
        content: [{required: true, message: '请选择转移至销售', trigger: 'change'}]
      },
      companyUserList: [],
      openTransferDialog: false,
      transferForm: {
        targetUserId: null,
        content: null
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [],
      // 标签选项
      tagOptions: [],
      // 销售员工选项
      salesOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nickname: null,
        isMyFsUser:false,
        phone: null,
        // status: null,
        tagIds: [],
        tabValue: "0",
        watchCourseType: "0",
        missCourseStatus: "0",
        continueMissCourseSort: "0",
        registerStartTime: null,
        registerEndTime: null,
        projectId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // nickname: [
        //   { required: true, message: "昵称不能为空", trigger: "blur" }
        // ],
        // phone: [
        //   { required: true, message: "手机号码不能为空", trigger: "blur" },
          // { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
        // ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ]
      },
      projectOptions: []
    };
  },
  created() {
    getUserList().then(res=>{
      if(res.code === 200) {
        this.companyUserList = res.data
      }
    });
    this.getList();
    this.getDicts("user_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("sys_course_project").then(response => {
      this.projectOptions = response.data;
    });
    this.getTagOptions();
    this.getSalesOptions();
  },
  methods: {
    handledetails(row){
            this.show.open=true;
            setTimeout(() => {
                 this.$refs.userDetails.getDetails(row.userId);
            }, 1);
     },
    // 重置表单
    resetForm() {
      this.linkForm={
        days:null,
        courseId:null,
        videoId:null
      }
    },
    /** 转移按钮操作 */
    handleTransfer(row) {

      const userIds = row.userId ? [row.userId] : this.ids;
      if (userIds.length === 0) {
        this.$message.warning("请至少选择一个客户进行转移");
        return;
      }
      this.resetTransferForm();
      this.openTransferDialog = true;
    },
    resetTransferForm() {
      this.transferForm = {
        targetUserId: null,
        content: null
      };
      this.resetForm("transferForm"); // 假设 transferForm 是 el-form 的 ref
    },
    cancelTransfer() {
      this.openTransferDialog = false;
      this.resetTransferForm();
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true;

      // 处理日期范围
      if (this.dateRange && this.dateRange.length > 0) {
        this.queryParams.registerStartTime = this.dateRange[0];
        this.queryParams.registerEndTime = this.dateRange[1];
      } else {
        this.queryParams.registerStartTime = null;
        this.queryParams.registerEndTime = null;
      }

      listUser(this.queryParams).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 获取标签选项 */
    getTagOptions() {
      this.tagOptions = [
        { tagId: "1", tagName: "VIP会员" },
        { tagId: "2", tagName: "普通会员" },
        { tagId: "3", tagName: "新用户" },
        { tagId: "4", tagName: "高频用户" }
      ];
    },

    /** 获取销售员工选项 */
    getSalesOptions() {
      getUserList().then(res=>{
        if(res.code === 200) {
          this.salesOptions = res.data
        }
      });
    },

    /** 获取看课状态类型 */
    getCourseStatusType(status) {
      if (status === 1) return "success";
      if (status === 2) return "danger";
      if (status === 3) return "info";
      return "";
    },

    /** 获取看课状态文本 */
    getCourseStatusText(status) {
      if (status === 1) return "正常看课";
      if (status === 2) return "停止看课";
      if (status === 3) return "未看过课";
      return "未知状态";
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        userId: null,
        nickname: null,
        avatar: null,
        phone: null,
        status: 1,
        tagIds: [],
        companyUserId: null,
        remark: null
      };
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** Tab切换操作 */
    handleTabChange() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.rowInfo=row;
      this.reset();
      const id = row.id;
      getMemberUser(id).then(response => {
        this.form = response.data;

        // 处理标签数据，将字符串转为数组
        if (this.form.tagIds && typeof this.form.tagIds === 'string') {
          this.form.tagIds = this.form.tagIds.split(',');
        }

        this.open = true;
        this.title = "修改用户";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const updateForm={
            id: this.rowInfo.id,
            status: this.form.status,
            remark: this.form.remark
          }
          updateMemberUser(updateForm).then(response => {
            if (response.code === 200) {
              this.$message.success("修改成功");
              this.open = false;
              this.getList();
            }
          });
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$confirm('是否确认删除用户编号为"' + userIds + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return delUser(userIds);
      }).then(() => {
        this.getList();
        this.$message.success("删除成功");
      }).catch(() => {});
    },

    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有用户数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return exportUser(queryParams);
      }).then(response => {
        this.download(response.msg);
      }).catch(() => {});
    },

    /** 审核会员操作 */
    handleAudit(row) {
      this.$confirm('是否确认将其移除小黑屋？', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        auditUser([row.userId]).then(response => {
          if (response.code === 200) {
            this.msgSuccess("审核成功");
            this.getList();
          }
        });
      }).catch(() => {});
    },
    /** 获取项目对应名称 */
    getProjectLabel(projectId) {
      return this.projectOptions.find(item => parseInt(item.dictValue) === projectId)?.dictLabel;
    },
  }
};
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 5px;
}
.mb8 {
  margin-bottom: 8px;
}
</style>
