<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="销售昵称" prop="companyUserId">
        <el-input
          v-model="queryParams.companyUserName"
          placeholder="请输入所属销售昵称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="微信昵称" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入微信昵称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="微信号" prop="weixinId">
        <el-input
          v-model="queryParams.weixinId"
          placeholder="请输入微信号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="组别" prop="groupName">
        <el-input
          v-model="queryParams.groupName"
          placeholder="请输入分组名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </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>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-s-flag"
          @click="handleSendGroup()">
          分组管理
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          @click="addUserGroup"
          v-hasPermi="['company:wxUser:addGroup']"
        >批量设置分组</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          @click="delUserGroup"
          v-hasPermi="['company:wxUser:delGroup']"
        >批量移除分组</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['company:wxUser:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="wxUserList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="所属销售" align="center" prop="companyUserName" />
      <el-table-column label="微信昵称" align="center" prop="nickName" />
      <el-table-column label="微信号" align="center" prop="weixinId" />
      <el-table-column label="状态 1正常 0禁用" align="center" prop="status" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="头像" align="center" prop="avatar" />
      <el-table-column label="组别" align="center" prop="groupId">
        <template slot-scope="scope">
          <div v-for="i in JSON.parse(scope.row.groupId)" :key="i" style="display: inline;">
            <el-tag type="success" v-for="ii in wxUserGroupList" :key="ii.id" style="margin: 3px;" v-if="ii.groupId==i">{{ii.groupName}}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="是否绑定小程序用户" width="110px" fixed="right">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.fsUserId"
            type="success"
            size="mini"
            plain>
            已绑定
          </el-button>
          <el-button
            v-else
            type="danger"
            size="mini"
            plain>
            未绑定
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120px" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit-outline"
            @click="handleUpdateUser(scope.row)"
          >
            <span v-if="scope.row.fsUserId">换绑小程序</span>
            <span v-else>绑定小程序用户</span>
          </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"
    />

    <!-- 添加或修改个微用户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属销售ID" prop="companyUserId">
          <el-input v-model="form.companyUserId" placeholder="请输入所属销售ID" />
        </el-form-item>
        <el-form-item label="微信昵称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入微信昵称" />
        </el-form-item>
        <el-form-item label="微信号" prop="weixinId">
          <el-input v-model="form.weixinId" placeholder="请输入微信号" />
        </el-form-item>
        <el-form-item label="状态 1正常 0禁用">
          <el-radio-group v-model="form.status">
            <el-radio label="1">请选择字典生成</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-input v-model="form.avatar" 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="userBind.title" :visible.sync="userBind.open" width="800px" append-to-body>
      <selectUser ref="selectUser" @bindMiniCustomerId="bindMiniCustomerId"></selectUser>
    </el-dialog>

    <el-dialog :title="sendGroup.title" :visible.sync="sendGroup.open" width="800px" append-to-body>
      <wx-user-group ref="wxUserGroup" ></wx-user-group>
    </el-dialog>

    <el-dialog title="批量添加分组" :visible.sync="groupOpen" width="600px" append-to-body>
      <el-form ref="form" :model="addGroupForm"  label-width="100px">
        <div style="margin: 10px">
          <a v-for="item in wxUserGroupList" :key="item.groupId" class="tag-box"
             @click="groupSelection(item)" :class="{'tag-selectd': item.isSelected==true}" >{{item.groupName}}</a>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addGroupSubmitForm()">确 定</el-button>
        <el-button @click="groupCancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="批量移除分组" :visible.sync="groupDelOpen" width="500px" append-to-body>
      <el-form ref="form" :model="addGroupForm"  label-width="80px">
        <div style="margin: 10px">
          <a v-for="item in wxUserGroupList" :key="item.groupId" class="tag-box"
             @click="groupSelection(item)" :class="{'tag-selectd': item.isSelected==true}" >{{item.groupName}}</a>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="delGroupSubmitForm()">确 定</el-button>
        <el-button @click="delGroupCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listWxUser, getWxUser, delWxUser, addWxUser, updateWxUser, exportWxUser,bindMiniUserId,addGroup,delGroup } from "@/api/wxUser/wxUser";
import wxUserGroup from "@/views/company/wxUserGroup/wxUserGroup.vue";
import {listWxUserGroup} from "@/api/wxUser/wxUserGroup";


export default {
  name: "WxUser",
  components: {wxUserGroup},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 个微用户表格数据
      wxUserList: [],
      // 弹出层标题
      title: "",
      //小程序绑定个微
      userForm:{
        userId:null,
        fsUserId:null,
      },

      //批量添加分组的数据
      addGroupForm:{
        userIds:[],
        groupIds:[]
      },
      //分组弹窗
      groupOpen:false,

      // 查询参数取消分组的弹窗
      groupDelOpen:false,

      //绑定小程序
      userBind:{
        open:false,
        title:"绑定小程序"
      },
      //设置分组
      sendGroup:{
        open:false,
        title:"分组管理"
      },
      // 个微 分组表格数据
      wxUserGroupList: [],

      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyId: null,
        companyUserName: null,
        nickName: null,
        weixinId: null,
        status: null,
        avatar: null,
        groupName:null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询个微用户列表 */
    getList() {
      this.loading = true;
      listWxUser(this.queryParams).then(response => {
        this.wxUserList = response.rows;
        this.total = response.total;
        this.loading = false;
      });

      listWxUserGroup().then(response => {
        this.wxUserGroupList = response.rows;
        for (let i = 0; i < this.wxUserGroupList.length; i++) {
          this.wxUserGroupList[i].isSelected=false;
        }

      });

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: null,
        companyId: null,
        companyUserId: null,
        nickName: null,
        weixinId: null,
        status: 0,
        remark: null,
        createTime: null,
        avatar: null
      };
      this.resetForm("form");
    },

    //绑定小程序客户
    handleUpdateUser(row){
      this.userBind.title="小程序客户"
      this.userBind.open=true;
      this.userForm.userId=row.userId;
    },

    //分组选择
    groupSelection(row){
      row.isSelected= !row.isSelected;
      this.$forceUpdate();
    },

    //绑定小程序id
    bindMiniCustomerId(row){

      this.userForm.fsUserId=row;
      bindMiniUserId(this.userForm).then(res=>{
        if (res.code==200){
          this.$message.success('绑定成功')
        }else {
          this.$message.error('绑定失败:',res.msg)
        }
        this.getList()
        this.userBind.open=false;
      })
    },

    //设置分组
    handleSendGroup(){
      this.sendGroup.open=true;
    },

    //批量设置分组
    addUserGroup(){

      if(this.ids==null||this.ids==""){
        return  this.$message('请选择需要添加标签的客户');
      }

      this.groupOpen = true;

    },
    //批量添加分组
    addGroupSubmitForm(){

      for (let i = 0; i < this.wxUserGroupList.length; i++) {
          if(this.wxUserGroupList[i].isSelected==true){
            this.addGroupForm.groupIds.push(this.wxUserGroupList[i].groupId)
          }
      }

      if(this.addGroupForm.groupIds==[]||this.addGroupForm.groupIds==null||this.addGroupForm.groupIds==""){
        return  this.$message('请选择分组');
      }

      this.addGroupForm.userIds=this.ids;

      addGroup(this.addGroupForm).then(response => {
        this.msgSuccess(response.msg);
        this.groupOpen = false;
        this.addGroupForm={
          userIds:[],
          groupIds:[]
        };
        this.getList()
      });
    },


    //批量移除分组
    delGroupSubmitForm(){
      for (let i = 0; i < this.wxUserGroupList.length; i++) {
          if(this.wxUserGroupList[i].isSelected==true){
            this.addGroupForm.groupIds.push(this.wxUserGroupList[i].groupId)
          }
      }

      if(this.addGroupForm.groupIds==[]||this.addGroupForm.groupIds==null||this.addGroupForm.groupIds==""){
        return  this.$message('请选择分组');
      }

      this.addGroupForm.userIds=this.ids;

      delGroup(this.addGroupForm).then(response => {
        this.msgSuccess(response.msg);
        this.groupDelOpen = false;
        this.addGroupForm={
          userIds:[],
          groupIds:[]
        };
        this.getList()
      });
    },

    //取消
    groupCancel(){
      this.groupOpen = false;
      this.addGroupForm={
        userIds:[],
        groupIds:[]
      };
    },

    //取消批量
    delGroupCancel(){
      this.groupDelOpen = false;
      this.addGroupForm={
        userIds:[],
        groupIds:[]
      };
    },

    //批量删除分组
    delUserGroup(){
      if(this.ids==null||this.ids==""){
        return  this.$message('请选择需要移除分组的客户');
      }
      this.groupDelOpen = true;
    },

    /** 搜索按钮操作 */
    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
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加个微用户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const userId = row.userId || this.ids
      getWxUser(userId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改个微用户";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.userId != null) {
            updateWxUser(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWxUser(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$confirm('是否确认删除个微用户编号为"' + userIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delWxUser(userIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有个微用户数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportWxUser(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
<style scoped>
.tag-box{
  margin: 10px;
  padding: 5px;
  background-color: #f0f0f0 ;
  border-radius: 4px;
}
.tag-selectd{
  background-color: rgb(231, 244, 255) ;
  border: 1px solid rgb(24, 144, 255) ;
}
</style>
