<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      
      <el-form-item label="模糊条件" prop="searchValue">
        <el-input
          v-model="queryParams.searchValue"
          placeholder="请输入ID、昵称、手机号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker v-model="dateRange" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </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="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:appUser:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:appUser:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:appUser:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:appUser:export']"
        >导出</el-button>
      </el-col> -->
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="30" align="center" />
      <el-table-column label="昵称" align="center" prop="nickName" />
      <el-table-column label="头像" align="center" >
        <template scope="scope">
            <img width="40" height="40" slot="reference" :src="baseUrl + scope.row.avatar" />
        </template>
      </el-table-column>
      <el-table-column
        label="性别"
        align="center"
        prop="gender"
        :formatter="genderFormat"
        width="50"
      />
      <el-table-column label="手机号码" align="center" prop="mobile" />
      <el-table-column
        label="已加入家族"
        align="center"
        prop="joins"
        :formatter="joinsFormat"
        width="100"
      />
      <el-table-column label="IP地址" align="center" prop="loginIp" />
      <el-table-column label="最后登录时间" align="center" prop="loginTime" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.loginTime) }}</span>
            </template>
          </el-table-column>
      <el-table-column label="操作" width="210">
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:appUser:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:appUser:remove']"
          >删除</el-button> -->
          <el-row style="margin-bottom: 3px;">
          <el-button
            size="mini"
            type="primary"
            @click="myPage(scope.row)"
            v-hasPermi="['system:appUser:query']"
          >个人页</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="myPublish(scope.row)"
            v-hasPermi="['system:appUser:query']"
          >个人发表</el-button>
          </el-row>
          <el-row>
          <el-button
            size="mini"
            type="primary"
            @click="myFriend(scope.row)"
            v-hasPermi="['system:appUser:query']"
          >好友</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="myFamily(scope.row)"
            v-hasPermi="['system:appUser:query']"
          >家族</el-button>
          </el-row>
        </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="750px" append-to-body :close-on-click-modal=false>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="0" type="flex" justify="start">
          <el-col :span="8">
            <el-form-item label="昵称" prop="nickName">
              <el-input v-model="form.nickName" placeholder="请输入昵称" />
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
              <el-input v-model="form.mobile" placeholder="请输入手机号码" :readonly="readonly" />
            </el-form-item>
            <el-form-item label="页面模板" prop="templateId">
              <el-input v-model="form.templateId" placeholder="请选择页面模板" />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="性别">
              <el-select v-model="form.gender" placeholder="请选择">
                <el-option v-for="dict in genderOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="状态">
              <el-select v-model="form.state" placeholder="请选择">
                <el-option v-for="dict in stateOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label-width="0px" prop="avatar">
              <div class="text-center">
                <appUserAvatar :personal="form" :key="reFresh" />
                ID: {{form.qrcode}}
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="请输入内容" />
        </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="friendsOpen" width="520px" append-to-body :close-on-click-modal=false>
      <el-table v-loading="friendLoading" :data="friendList" >
        <el-table-column label="序号" type="index" width="50" />
        <el-table-column label="昵称" align="center" prop="nickName" />
      </el-table>
      <br />
      <el-pagination small
        v-show="ftotal>0"
        :page-size="friendsParams.pageSize"
        :current-page="friendsParams.pageNum"
        :total="ftotal"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="friendBack">返回</el-button>
      </div>
    </el-dialog>

    <!-- 我的家族 -->
    <el-dialog title="家族列表" :visible.sync="familyOpen" width="520px" append-to-body :close-on-click-modal=false>
      <el-table v-loading="familyLoading" :data="familyList" >
        <el-table-column label="序号" type="index" width="50" />
        <el-table-column label="家族" align="center" prop="fullName" />
        <el-table-column label="家族ID" align="center" prop="code" />
        <el-table-column label="创建地" align="center" prop="address" />
      </el-table>
      <br />
      <el-pagination small
        v-show="mtotal>0"
        :page-size="familyParams.pageSize"
        :current-page="familyParams.pageNum"
        :total="mtotal"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="familyBack">返回</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listUser,pageUser, getUser, delUser, addUser, updateUser, exportUser } from "@/api/system/appUser";
import appUserAvatar from "./detail/appUserAvatar";
import { listFriends } from "@/api/system/friends";
import { listFamilyByUid } from "@/api/system/family";

export default {
  name: "AppUser",
  components: {
    appUserAvatar
  },
  data() {
    return {
      baseUrl: null,
      // 遮罩层
      loading: true,
      friendLoading: true,
      familyLoading: true,
      // 选中数组
      ids: [],
      nicknames: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 会员表格数据
      userList: [],
      friendList: [],
      familyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 加入 数据字典
      joinsOptions: [],
      // 性别 数据字典
      genderOptions: [],
      // 状态 数据字典
      stateOptions: [],
      readonly: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        enable: 0,
        searchValue: null,
      },
      friendsOpen: false,
      familyOpen: false,
      ftotal: 0,
      mtotal: 0,
      friendsParams: {
        pageNum: 1,
        pageSize: 10,
        appUserId: null,
      },
      familyParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
      },
      reFresh: 1,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        nickName: [
          { required: true, message: "昵称不能为空", trigger: "blur" },
        ],
        gender: [
          { required: true, message: "性别不能为空", trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
      }
    };
  },
  watch:{
    // 监听form值，只要有改变，则key值reFresh变更。
    // 然后自定义上传图片组件apUserAvatar重新渲染
    form(){
      ++this.reFresh
    }
  },
  created() {
    this.baseUrl = process.env.VUE_APP_BASE_API;
    this.getList();
    this.getDicts("sys_yes_no").then(response => {
      this.joinsOptions = response.data;
    });
    this.getDicts("sys_user_sex").then((response) => {
      this.genderOptions = response.data;
    });
    this.getDicts("app_member_state").then((response) => {
      this.stateOptions = response.data;
    });
  },
  methods: {
    /** 查询会员列表 */
    getList() {
      this.loading = true;
      pageUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 加入 字典翻译
    joinsFormat(row, column) {
      return this.selectDictLabel(this.joinsOptions, row.joins);
    },
    // 性别 字典翻译
    genderFormat(row, column) {
      return this.selectDictLabel(this.genderOptions, row.gender);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        templateId: null,
        nickName: null,
        avatar: null,
        qrcode: null,
        mobile: null,
        openid: null,
        verCode: null,
        remark: null,
        gender: null,
        state: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.nicknames = selection.map(item => item.nickName)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.readonly = false;
      this.reset();
      this.open = true;
      this.title = "添加会员";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.readonly = true;
      this.reset();
      const id = row.userId || this.ids;
      getUser(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改会员";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.userId != undefined) {
            updateUser(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addUser(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.userId || this.ids;
      const nicknames = row.nickName || this.nicknames;
      this.$confirm('是否确认删除会员[' + nicknames + ']?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delUser(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有会员数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportUser(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    }
    ,
    myPage(row) {

    },

    myPublish(row) {
      this.$router.push({ 
        path:'/my/publish',
        query: {
            uid: row.userId
        }
      })
    },

    getMyFriends(){
      this.friendLoading = true;
      listFriends(this.friendsParams).then(res => {
        this.friendList = res.rows;
        this.ftotal = res.total;
        this.friendLoading = false;
      });
    },
    myFriend(row) {
      this.friendsOpen = true;
      this.friendsParams.appUserId = row.userId;
      this.getMyFriends();
    },
    friendBack(){
      this.friendsOpen = false;
    },

    myFamily(row) {
      this.familyOpen = true;
      this.familyLoading = true;
      this.familyParams.userId = row.userId;
      listFamilyByUid(this.familyParams).then(res => {
        this.familyList = res.rows;
        this.mtotal = res.total;
        this.familyLoading = false;
      });
    },
    familyBack(){
      this.familyOpen = false;
    },
  }
};
</script>
