<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container head-container2" style="height:800px">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="用户名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入用户名称"
              clearable
              size="small"
              style="width: 140px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary"  size="mini" @click="handleQuery">搜索</el-button>
            <el-button plain size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
          <br>
          <el-form-item>
            <el-button plain size="mini" @click="peopleChange()">配餐员批量处理</el-button>
            <el-button plain size="mini" @click="allPeople">查看所有配送员</el-button>
          </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange" >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="sid" align="center" key="sid" prop="sid" v-if="columns[0].visible"  show-overflow-tooltip />
          <el-table-column label="用户名称" align="center" key="userName" prop="name" v-if="columns[1].visible"  show-overflow-tooltip  />
          <el-table-column label="部门" align="center" key="deptName" prop="deptName" v-if="columns[3].visible"  show-overflow-tooltip  />
          <el-table-column label="配送员设置" align="center" key="people" v-if="columns[5].visible" >
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.people"
                active-value="1"
                inactive-value="0"
                @change="handlePeople('row',scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
            <el-table-column label="公众号推送设置" align="center" key="isSend" v-if="columns[5].visible" >
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.isSend"
                active-value="1"
                inactive-value="0"
                @change="handleSend(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
        </el-table>
        <!-- 添加或修改参数配置对话框 -->
        <el-dialog   :title="title" :visible.sync="open" width="750px" append-to-body :before-close="cancel" :close-on-click-modal="false"  >
          <el-form ref="form" :model="form"  label-width="140px" >
            <el-row>
                <el-col :span="12">
                  <el-form-item label="配送员设置：" prop="people">
                    <el-switch
                        v-model="form.people"
                        active-value="1"
                        inactive-value="0"
                        @change="handlePeople('form',form)"
                        >
                      </el-switch>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="公众号推送信息：" prop="isSend">
                    <el-switch
                        v-model="form.isSend"
                        active-value="1"
                        inactive-value="0"
                        >
                      </el-switch>
                  </el-form-item>
                </el-col>
              </el-row>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm(1)" v-if="!loading">确 定</el-button>
            <el-button :loading="loading" type="primary" @click="submitForm" v-else>提交中...</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
        <!-- 全部配送人员对话框 -->
        <el-dialog   :title="title2" :visible.sync="open2" width="750px" append-to-body :before-close="cancel2" :close-on-click-modal="false" >
          <el-form :model="queryParams2" ref="queryForm2" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="用户名称" prop="name">
              <el-input
                v-model="queryParams2.name"
                placeholder="请输入用户名称"
                clearable
                size="small"
                style="width: 140px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery2">搜索</el-button>
            <el-button type="primary" icon="el-icon-refresh" size="mini" @click="resetQuery2">重置</el-button>
            <el-button type="warning" icon="el-icon-circle-plus-outline" size="mini" @click="peopleChange()" style="margin:-50px 10px 30px">配餐员批量处理</el-button>
            <!-- <el-button
              type="success"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              :loading="exportLoading"
              style="margin-left:0px;"
            >配送人员导出</el-button> -->
          </el-form-item>
          </el-form>


          <el-table v-loading="loading" :data="userList2" @selection-change="handleSelectionChange" height="60vh">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="sid" align="center" key="sid" prop="sid" v-if="columns[0].visible"  show-overflow-tooltip />
            <el-table-column label="用户名称" align="center" key="userName" prop="name" v-if="columns[1].visible"  show-overflow-tooltip  />
            <el-table-column label="部门" align="center" key="deptName" prop="deptName" v-if="columns[3].visible"  show-overflow-tooltip  />
            <el-table-column label="配送员设置" align="center" key="people" v-if="columns[5].visible" >
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.people"
                  active-value="1"
                  inactive-value="0"
                  @change="handlePeople('row',scope.row)"
                ></el-switch>
              </template>
            </el-table-column>
            <el-table-column label="公众号推送设置" align="center" key="isSend" v-if="columns[5].visible" >
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.isSend"
                  active-value="1"
                  inactive-value="0"
                  @change="handleSend(scope.row)"
                ></el-switch>
              </template>
            </el-table-column>
          </el-table>
        </el-dialog>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.current"
          :limit.sync="queryParams.size"
          @pagination="getList"
        />
      </el-col>
    </el-row>


  </div>
</template>

<script>
import { getPeople, updataPeople,bumen, people, staffExport} from "@/api/recharge/cateringManagement";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "User",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      zid:[],
      userName:[],
      openid:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "人员配送信息处理",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 状态数据字典


      defaultProps: {
        children: "children",
        label: "label"
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
      },
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        name: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined
      },
      // 查询参数2
      queryParams2: {
        current: 1,
        size: 500,
        name: undefined,
      },
      // 列信息
      columns: [
        { key: 0, label: `用户编号`, visible: true },
        { key: 1, label: `用户名称`, visible: true },
        { key: 2, label: `用户昵称`, visible: true },
        { key: 3, label: `部门`, visible: true },
        { key: 4, label: `手机号码`, visible: true },
        { key: 5, label: `状态`, visible: true },
        { key: 6, label: `创建时间`, visible: true }
      ],
      form:{
        isSend:"1",
        people:"1",
      },
      title2:"全部配餐人员信息",
      open2:false,
      userList2:[],



    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getTreeselect();
    this.getList();
  },
  methods: {
    //强制el-input刷新
    onInput(){
        this.$forceUpdate();
    },
    changeUnit() {
      this.$forceUpdate();
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      people(this.queryParams).then(response => {
        let data1 = response.data.records
        for(let i =0;i<data1.length;i++){
          data1[i].deptName = JSON.parse(data1[i].dept).name
          data1[i].isSend = "0"
          data1[i].people = "0"
          data1[i].dreUserId = undefined
          data1[i].openId = data1[i].openId
          data1[i].userName = data1[i].name || ''
        }
        if(data1.length>0){
          getPeople({current:1,size:500}).then(res => {
            let data2 = res.data.records
            if(data2.length>0){
              for(let i =0;i<data2.length;i++){
                for(let a=0;a<data1.length;a++){
                  if(data1[a].sid == data2[i].sid ){
                    data1[a].isSend = data2[i].isSend ? "1" : "0"
                    data1[a].delFlag = data2[i].delFlag ? "1" : "0"
                    data1[a].dreUserId = data2[i].dreUserId
                    data1[a].openId = data2[i].dreOpenId ? data2[i].dreOpenId : data2[i].openId ? data2[i].openId ? data1[a].openId : data1[a].openId : ''
                    data1[a].people = "1"
                  }
                }
              }
            }else{
              for(let i =0;i<data1.length;i++){
                data1[i].isSend = 0
              }
            }
            this.userList = data1;
          })
        }else{
          this.userList = response.data.records
        }
        setTimeout(()=>{
          console.log(this.userList)
        },1000)
        this.total = response.data.total;
        this.loading = false;
      })
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      bumen({current:1}).then(response => {
        this.deptOptions = response.data;
      });
      // treeselect().then(response => {
      //   this.deptOptions = response.data;
      // });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.getList();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      setTimeout(()=>{
        this.reset();
      })
    },
    // 取消按钮
    cancel2() {
      this.open2 = false;
      setTimeout(()=>{
        this.reset();
      })
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined,
        postIds: [],
        roleIds: [],
        postId: undefined,
        roleId: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.currnt = 1;
      this.getList();
    },
    /** 搜索按钮操作 */
    handleQuery2() {
      // this.queryParams2.currnt = 1;
      // this.queryParams2.size = 500;
      this.allPeopleShow();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    resetQuery2(){
      this.resetForm("queryForm2");
      this.handleQuery2();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.sid);
      this.zid = selection.map(item => item.dreUserId);
      this.userName = selection.map(item => item.userName);
      this.openid = selection.map(item => item.openid);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleResetPwd":
          this.handleResetPwd(row);
          break;
        case "handleAuthRole":
          this.handleAuthRole(row);
          break;
        default:
          break;
      }
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 人员批量处理button */
    peopleChange(){
      if(this.ids.length>0){
          this.open = true
          this.form = {isSend:"1",people:"1"}
      }else{
        this.$message.error('请勾选需要批量处理的人员选项')
      }
    },
     /** 人员批量处理*/
    submitForm(){
      if(this.open){
        let data = []
        for(let i =0;i<this.ids.length;i++){
          data[i] = {userId:undefined,isSend:undefined,delFlag:undefined,id:undefined,userName:'',openId :''}
          data[i].userId = this.ids[i]
          data[i].isSend = this.form.isSend == '1' ? 1 : 0
          data[i].delFlag = this.form.people == "1" ? true : false
          data[i].userName = this.userName[i]  || ''
          data[i].openId  = this.openid[i]  || ''
          data[i].id = this.zid[i]
        }
        updataPeople(data).then(response =>{
          this.msgSuccess(`人员批量处理完成`)
          this.loading = false;
          this.open = false
          this.getList();
          if(this.open2){
            this.allPeopleShow()
          }
        }).catch(err=>{
          this.open = false
          this.loading = false;
        })
      }


    },
    /** 查看所有配送员按钮 */
    allPeople(){
      this.open2 = true
      this.allPeopleShow()
    },
    /** 查看所有配送员 */
    allPeopleShow(){
      getPeople(this.queryParams2).then(res => {
        let data = res.data.records
        for(let i =0;i<data.length;i++){
           data[i].deptName = JSON.parse(data[i].dept).name
           data[i].people = "1"
           data[i].isSend = data[i].isSend ? "1" : "0"
           data[i].id = data[i].dreUserId
           data[i].userName = data[i].name  || ''
           data[i].openId = data[i].dreOpenId ? data[i].dreOpenId : data[i].openId
           if(!data[i].openId){
             data[i].openId = ""
           }
        }
        this.userList2 = data

      })
    },
    /**配送员单独设置 */
    handlePeople(name,row){
      if(name == "form"){
        if(row.people == "0"){
          row.isSend = "0"
        }
      }else{
        let data = [{userId:undefined,delFlag:undefined,isSend:undefined,id:undefined,userName:'',openId :''}]
        if(row.people == "1"){
          data[0].isSend=  row.isSend
          data[0].delFlag = true
        }else{
          data[0].isSend = 0
          data[0].delFlag = false
        }
        data[0].id = row.dreUserId
        data[0].userId = row.sid
        data[0].userName = row.userName || ''
        data[0].openId  = row.openId  || ''
        updataPeople(data).then(response =>{
          if(data[0].delFlag){
            this.msgSuccess(`人员绑定完成`)
          }else{
            this.msgSuccess(`人员解绑完成`)
          }
          this.getList();
          if(this.open2){
            this.allPeopleShow()
          }
        }).catch(err=>{
          this.getList();
        })
      }
    },
    /**公众号推送单独设置 */
    handleSend(row){
        let data = [{userId:undefined,delFlag:undefined,isSend:undefined,id:undefined,userName:'',openId :''}]
        if(row.isSend == "1"){
          data[0].isSend = 1
          if(row.people == "0"){
            row.people == "1"
            data[0].delFlag= true
          }else{
            data[0].delFlag= true
          }
        }else{
          data[0].delFlag = row.people == "1" ? true : false
          data[0].isSend= 0
          data[0].delFlag= row.people == "1" ? true : false
        }
        data[0].id = row.dreUserId
        data[0].userId = row.sid
        data[0].userName = row.userName || ''
        data[0].openId = row.openId  || ''
        updataPeople(data).then(response =>{
          if(data[0].delFlag){
            this.msgSuccess(`公众号推送绑定完成`)
          }else{
            this.msgSuccess(`公众号推送解绑完成`)
          }
          this.getList();
          if(this.open2){
            this.allPeopleShow()
          }
        }).catch(err=>{
          this.getList();
          if(this.open2){
            this.allPeopleShow()
          }
        })
    },
  }
};
</script>
<style scoped>
.head-container2{
  overflow-y: scroll;
}
</style>
