<template>
  <div class="addAudiences">
    <p class="basicInformation">基本信息</p>
    <el-form label-position="right" label-width="80px" ref="form" :model="form" :rules="rules">
      <el-form-item label="名称:" prop="name">
        <el-input placeholder="请填写名称" v-model="form.name" maxlength="50"></el-input>
      </el-form-item>
      <el-form-item label="描述:">
        <el-input placeholder="请填写描述" type="textarea" :autosize="{ minRows: 4, maxRows: 4 }" v-model="form.description" maxlength="200"></el-input>
      </el-form-item>
    </el-form>
    <p class="basicInformation">人员信息</p>
    <div class="action">
      <el-input style="width: 20%" clearable placeholder="请输入姓名或工号" v-model="searchValue"></el-input>
      <el-button type="primary" class="findBtn" size="medium" @click="queryTableData">搜索</el-button>
      <el-button type="primary" size="medium" @click="tableDataReset">重置</el-button>
      <el-button type="primary" size="medium" @click="openDialog">添加</el-button>
      <el-button type="primary" size="medium" @click="openImportDialog">导入</el-button>
      <el-button type="primary" size="medium" @click="deleteTableData">批量删除</el-button>
    </div>
    <el-table ref="multipleTable" :data="tableDataShow" tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" align="center" width="55"> </el-table-column>
      <el-table-column label="姓名" prop="realName" align="center" ></el-table-column>
      <el-table-column prop="userNo" label="工号"  align="center"></el-table-column>
      <el-table-column prop="departName" label="部门" align="center"></el-table-column>
      <!-- <el-table-column prop="position" label="岗位" align="center"></el-table-column> -->
    </el-table>
    <div class="publish">
      <el-button @click="saveBack" type="primary" size="large">取消</el-button>
      <el-button @click="saveBack(0)" type="primary" size="large">保存</el-button>
      <el-button @click="saveBack(1)" type="primary" size="large">保存并发布</el-button>
    </div>
    <el-dialog title="添加人员" :visible.sync="addUserShow" :close-on-click-modal="false" width="800px" custom-class="g-dialog">
        <el-row style="height: 400px;">
          <el-col :span="6" style="height: 380px;display: block;overflow-y: scroll;">
            <el-tree
              ref="treeRef"
              node-key="id"
              :lazy="true"
              :props="departProps"
              :load="loadNode"
              @node-click="handleDepartNodeClick"
              :expand-on-click-node="false"
              :default-expanded-keys="['-1']">
            </el-tree>
          </el-col>
          <el-col :span="18">
            <div class="action">
              <el-input clearable style="width: 30%;margin-left: 10px;" v-model="userQueryForm.keyword" placeholder="请输入姓名或工号"></el-input>
              <el-button type="primary"  size="medium" @click="queryUserData">搜索</el-button>
              <el-button type="primary" class="findBtn"  size="medium" @click="reset">重置</el-button>
            </div>
            <el-table ref="userTable"  :data="userData" v-loading="userDataLoading" tooltip-effect="dark"  @selection-change="userSelectionChange">
              <el-table-column type="selection" align="center"  width="55"></el-table-column>
              <el-table-column label="姓名" prop="realName" align="center"></el-table-column>
              <el-table-column prop="userNo" label="工号" align="center"></el-table-column>
              <el-table-column prop="departName" label="部门" align="center"></el-table-column>
              <!-- <el-table-column prop="duty" label="岗位" align="center"></el-table-column> -->
            </el-table>
            <div style="text-align: center;margin-top: 20px;">
              <el-pagination layout="prev, pager, next" background :total="userDataPage.total" :current-page.sync="userDataPage.pageIndex"
                :page-size="userDataPage.pageSize" @current-change="userDataCurrentChange"></el-pagination>
            </div>
          </el-col>
        </el-row>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addUserShow= false">取 消</el-button>
          <el-button type="primary" @click="addUserToForm">添加人员</el-button>
        </span>
    </el-dialog>
    <el-dialog center custom-class="g-dialog" title="导入人员数据" :close-on-click-modal="false" :visible.sync="importUserShow">
      <div style="padding: 10px 0px;color: #009ae7; ">注：单个导入文件受众成员请勿超过5000条记录，以员工号为准。必须是本系统人员</div>
      <el-row type="flex" align="middle" justify="start" style="margin-bottom: 10px;">
        文件名称：<el-input style="width: 200px;" disabled v-model="selectFile"></el-input>
        <!-- <el-upload
          class="upload-demo"
          ref="upload"
          action="/systemapi/xboe/usergroup/import"
          :headers="{'XBOE-Access-Token':token}"
          accept=".xlsx"
          name="file"
          :on-change="selectFileFun"
          :limit="1"
          :on-exceed="uploadExceed"
          :on-success="uploadSuccess"
          :file-list="fileList"
          :show-file-list="false"
          :auto-upload="false"
          > -->
          <el-upload
            class="upload-demo"
            ref="upload"
            :action="importUrl"
            :headers="{'token':token}"
            accept=".xlsx"
            name="userExcel"
            :on-change="selectFileFun"
            :limit="1"
            :on-exceed="uploadExceed"
            :on-success="uploadSuccess"
            :file-list="fileList"
            :show-file-list="false"
            :auto-upload="false"
            >
          <el-button slot="trigger" style="margin-left: 10px;" size="small" type="primary">选择</el-button>
          <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">{{uploadBtnValue}}</el-button>
        </el-upload>
        <el-link style="margin-left:auto" @click="downloadTemplate">下载模板文件</el-link>
      </el-row>
      <el-row>
         <el-table ref="userTable" :max-height="500" :min-height="200" :data="importUserData" tooltip-effect="dark" style="width: 100%;">
            <el-table-column label="姓名" prop="realName" align="center" ></el-table-column>
            <el-table-column prop="userNo" label="工号" align="center" ></el-table-column>
            <el-table-column label="检查结果" align="center" >
             <template slot-scope="scope">
               <span v-if="scope.row.isSuccess" style="color: green;">正确</span>
               <span v-else style="color: red;">错误</span>
              </template>
            </el-table-column>
             <el-table-column label="说明" prop="exception" align="center" ></el-table-column>
           <!-- <el-table-column prop="departName" label="部门" align="center" ></el-table-column>
            <el-table-column prop="duty" label="岗位" align="center"></el-table-column> -->
          </el-table>
          <div v-if="importResultStatus == false" style="color: red;padding: 10px 0px;">{{importRepeatUsers}}</div>
          <div v-if="importResultStatus" style="color: green;padding: 10px 0px;">{{importRepeatUsers}}</div>
      </el-row>
      <template #footer>
        <el-button @click="importUserShow = false">取 消</el-button>
        <el-button type="primary" @click="addImportUserToForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
  import { getToken } from '@/utils/token'
  import usergroupApi from "@/api/modules/usergroup";
  import userApi from "@/api/system/user";
  import orgApi from "@/api/system/organiza";
  import apiUserBasic from "@/api/boe/userbasic";
  import apiAudience from "@/api/boe/audience.js";
  export default{
    data(){
      return{
        token:getToken(),
        form:{
          id:'',
          name: '',
          gtype: 1,
          description:'',
          userGroupItems:[]
        },
        uploadBtnValue:'上传',
        isUpdate:false,
        importUrl:process.env.VUE_APP_AUDIENCE_IMPORT_URL,
        searchValue:'',
        tableData:[],
        tableDataShow:[],
        oldUserGroupItems:[],
        rules: {
          name: [{ required: true, message: "请输入名称", trigger: "blur" }]
        },
        multipleSelection:[],
        userSelection:[],
        addUserShow:false,
        departData:[],
        departProps: {
          children: 'children',
          label: 'name'
        },
        userData:[],
        userQueryForm:{keyword:'',departId:''},
        userDataLoading:false,
        userDataPage:{
          total:0,
          pageSize:5,
          pageIndex:1
        },
        importUserShow:false,
        importUserData:[],
        importRepeatUsers:'',
        importResultStatus: false,  // false: 导入失败；true: 导入成功
        selectFile:'',
        fileList:[],
      }
    },
    mounted() {
      let that = this;
      if (that.$route.query.id) {
        let req = {audienceId:that.$route.query.id}
        this.isUpdate = true;
        apiAudience.detail(req).then((res) => {
          if (res.status == 200) {
            that.form = res.result;
            that.tableData = res.result.memberList;
            that.queryTableData();
          }
        });
        // usergroupApi.detail(that.$route.query.id).then((res) => {
        //     if (res.status == 200) {
        //       that.form = res.result;
        //       // that.oldUserGroupItems = JSON.parse(JSON.stringify( res.result.userGroupItems ));
        //       that.tableData = res.result.userGroupItems;
        //       that.queryTableData();
        //     }
        // });
      }
    },
    methods:{
      loadNode(node, resolve) {
        var parentId = null;
        if (node.level === 0) {
          resolve([{name:'组织机构树',id:'-1'}]);
        }else{
          let $this=this;
          if(node.level === 1){
              parentId = '-1';
              apiUserBasic.findOrgsByKeyword('').then(rs=>{
                  let treeList=[];
                  rs.result.forEach(item=>{
                    let node={
                      id:item.id,
                      name:item.name,
                      hrbpId:item.hrbpId,
                      children:[]
                    }
                    treeList.push(node);
                  });
                  resolve(treeList);
              });
          }else{
              parentId = node.data.id;

              apiUserBasic.getOrgInfo(parentId).then(rs=>{
                if(rs.status==200){
                  let treeList=[];
                  if(rs.result.directChildList){
                      rs.result.directChildList.forEach(item=>{
                        let node={
                          id:item.id,
                          name:item.name,
                          hrbpId:item.hrbpId,
                          children:[]
                        }
                        treeList.push(node);
                      });
                    }
                    resolve(treeList);
                 }else{
                   resolve([]);
                 }
              });
          }
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      openDialog(){
        this.addUserShow = true;
        this.userQueryForm.keyword = '';
        this.userQueryForm.departId = '';
        // orgApi.treeList({}).then(res => {
        //   if (res.status == 200) {
        //     this.departData = res.result;
        //   }
        // });
        //默认不查询
        //this.loadUserData(this.userDataPage);
        this.queryUserData();
      },
      reset() {
        this.userQueryForm.keyword = '';
        this.userQueryForm.departId = '';
        this.userDataPage.pageIndex = 1;
        this.loadUserData(this.userDataPage, this.userQueryForm);
      },
      userSelectionChange(val) {
        this.userSelection = val;
      },

      //搜索员工事件
      queryUserData(){
        this.userDataPage.pageIndex = 1;
        this.loadUserData(this.userDataPage, this.userQueryForm);
      },
      loadUserData(page, params = {}){
        this.userDataLoading = true;
        params.pageIndex = page.pageIndex;
        params.pageSize = page.pageSize;

        let req = {
          page:page.pageIndex,
          pageSize:page.pageSize,
          keyword:this.userQueryForm.keyword,
          departId:this.userQueryForm.departId
        }
        apiAudience.userList(req).then(res => {
          if (res.status == 200) {
            console.log("搜索用户信息");
            console.log(res);
            this.userData = res.result.userInfoList;
            this.userDataPage.total = res.result.totalPage;
            this.userDataLoading = false;
          }
        })

        // userApi.list(Object.assign(params, this.userQueryForm)).then(res => {
        //   if (res.status == 200) {
        //     this.userData = res.result.list;
        //     this.userDataPage.total = res.result.count;
        //     this.userDataLoading = false;
        //   }
        // })
      },
      userDataCurrentChange(pageIndex){
        this.userDataPage.pageIndex = pageIndex;
        this.loadUserData(this.userDataPage,this.userQueryForm);
      },
      handleDepartNodeClick(data){
        this.userQueryForm.departId = data.id;
        this.loadUserData(this.userDataPage);
      },
      addUserToForm(){
        if(this.userSelection.length == 0){
          this.$message({ type: "error", message: '请先选择人员' ,offset:50});
          return;
        }
        for(let i = 0; i < this.userSelection.length; i++){
          let isAdd = true;
          for(let j = 0; j < this.tableData.length; j++){
            if(this.userSelection[i].id == this.tableData[j].id){
              isAdd = false;
              break;
            }
          }
          if(isAdd){
            let userItem = {}
            userItem.aid = this.userSelection[i].id;
            userItem.id = this.userSelection[i].id;
            userItem.realName = this.userSelection[i].realName;
            userItem.userNo = this.userSelection[i].userNo;
            userItem.departId = this.userSelection[i].departId;
            userItem.departName = this.userSelection[i].departName;
            userItem.position = this.userSelection[i].duty;
            this.tableData.push(userItem);
            console.log(111);
            console.log(this.tableData);
          }
        }
        this.queryTableData();
        this.addUserShow = false;
      },
      tableDataReset(){
        this.searchValue = '';
        this.queryTableData();
        // this.tableData = JSON.parse(JSON.stringify( this.oldUserGroupItems ));
        // this.queryTableData();
      },
      queryTableData(){
        if(this.searchValue){
          let tableDataTemp = this.tableData;
          this.tableDataShow = this.handleTableDataShow(tableDataTemp,this.searchValue);
        }else{
          this.tableDataShow = this.tableData;
        }
      },
      // 表格过滤
      handleTableDataShow(tableDataTemp, searchValue) {
        if (!tableDataTemp || tableDataTemp.length === 0) {
            return [];
          }
          const array = [];
          for (let i = 0; i < tableDataTemp.length; i += 1) {
            let match = false;
            if(tableDataTemp[i]['realName'] || tableDataTemp[i]['userNo']){
              match |= (tableDataTemp[i]['realName'].includes(searchValue) || tableDataTemp[i]['userNo'].includes(searchValue));
            }
            if ( match ) {
              array.push({
                ...tableDataTemp[i]
              });
            }
          }
        return array;
      },
      deleteTableData(){
        if(this.multipleSelection.length == 0){
          this.$message({ type: "error", message: '请先选择要删除的数据' ,offset:50});
        }
        for (let i = 0; i < this.multipleSelection.length; i++) {
          for (let j = 0; j < this.tableData.length; j++) {
            if (this.tableData[j].aid === this.multipleSelection[i].aid) {
              this.tableData.splice(j, 1)
              break
            }
          }
        }
        this.queryTableData();
      },
      openImportDialog(){
        this.selectFile = '';
        this.importUserData = [];
        this.importRepeatUsers='';
        this.fileList = [];
        this.importUserShow = true;
      },
      downloadTemplate(){
        let fileName = "受众人员导入模板.xlsx";
        // usergroupApi.downloadTemplate().then(
        // (response) => {
        //     let blob = new Blob([response], {
        //       type: 'application/octet-stream',
        //     })
        //     if (window.navigator.msSaveOrOpenBlob) {
        //       navigator.msSaveBlob(blob, fileName)
        //     } else {
        //       var link = document.createElement('a')
        //       link.href = window.URL.createObjectURL(blob)
        //       link.download = fileName
        //       link.click()
        //       //释放内存
        //       window.URL.revokeObjectURL(link.href)
        //     }
        // },
        // (err) => {
        //     this.$message({
        //       type: 'error',
        //       message: '文件下载失败，请重试！',offset:50
        //     })
        // }
        // )
       let link = document.createElement('a'); //创建a标签
      link.style.display = 'none'; //使其隐藏
      link.download = this.webBaseUrl+'/template/usergroup_template.xlsx';
      link.setAttribute('target', '_blank');
      link.href = this.webBaseUrl+'/template/usergroup_template.xlsx'; //赋予文件下载地址
      link.setAttribute('download', fileName); //设置下载属性 以及文件名
      document.body.appendChild(link); //a标签插至页面中
      link.click(); //强制触发a标签事件
      document.body.removeChild(link);

      },




      selectFileFun(file){
        this.selectFile = file.name;
      },
      uploadExceed(files, fileList) {
          this.$set(fileList[0], 'raw', files[0]);
          this.$set(fileList[0], 'name', files[0].name);
          this.$refs['upload'].clearFiles();//清除文件
          this.$refs['upload'].handleStart(files[0]);//选择文件后的赋值方法
      },
      submitUpload(){
        if(this.selectFile){this.uploadBtnValue = '上传中';}
        this.$refs.upload.submit();
      },
      uploadSuccess(res){
        console.log(111);
        if(res.status == 200){
          this.importUserData = res.result;
          this.importResultStatus = true;
          this.importRepeatUsers=res.message;
        }else{
          this.importResultStatus = false;
          this.importRepeatUsers = "导入失败";
          this.$message({ type: "error", message: res.message ,offset:50});
        }
        this.uploadBtnValue = '上传';
      },
      addImportUserToForm(){
        if(this.importUserData.length == 0){
          this.$message({ type: "error", message: '请先导入人员' ,offset:50});
          return;
        }
        for(let i = 0; i < this.importUserData.length; i++){
          let udata=this.importUserData[i];
          if(!udata.isSuccess){
             continue;
          }
          let isAdd = true;
          for(let j = 0; j < this.tableData.length; j++){
            if(udata.id == this.tableData[j].id){
              isAdd = false;
              break;
            }
          }
          if(isAdd){
            let userItem = {}
            // userItem.aid = udata.id;
            userItem.id = udata.id;
            userItem.realName = udata.realName;
            userItem.userNo = udata.userNo;
            userItem.departId = udata.departId;
            userItem.departName = udata.departName;
            userItem.position = udata.duty;
            this.tableData.push(userItem);
          }
        }
        this.queryTableData();
        this.importUserShow = false;
      },

      // 保存、保存并发布事件
      saveBack(status){
        if(status === 1 || status === 0){
          this.form.status = status;
        }else{
          this.$router.push('/manage/ugroups');
          return;
        }
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.form.userGroupItems = [];
            if(this.tableData.length > 0){
              for(let i = 0; i < this.tableData.length; i++){
                // this.form.userGroupItems.push({aid:this.tableData[i].aid});
                this.form.userGroupItems.push(this.tableData[i].id);
              }
            }
            if (this.form.id != null && this.form.id != "") {   // 修改受众
              let req = {
                audienceId:this.form.id,
                audienceName:this.form.name,
                description:this.form.description,
                type:this.form.gtype,
                status:this.form.status,
                memberIdList:this.form.userGroupItems
              }
              apiAudience.update(req).then((res) => {
                if (res.status == 200) {
                  this.$message({ type: "success", message: "修改成功",offset:50 });
                  this.$router.push('/manage/ugroups');
                }else{
                  console.log("更新受众异常");
                }
              })

              // usergroupApi
              //   .update(this.form)
              //   .then((res) => {
              //     if (res.status == 200) {
              //       this.$message({ type: "success", message: "修改成功",offset:50 });
              //       this.$router.push('/manage/ugroups');
              //     }
              //   })
              //   .catch((res) => {
              //     this.$message({ type: "error", message: res.message ,offset:50});
              //   });
            } else {    // 新增受众

              let req = {
                audienceId:this.form.id,
                audienceName:this.form.name,
                description:this.form.description,
                type:this.form.gtype,
                status:this.form.status,
                memberIdList:this.form.userGroupItems
              }
              apiAudience.update(req).then((res) => {
                if (res.status == 200) {
                  this.$message({ type: "success", message: "新增成功",offset:50 });
                  this.$router.push('/manage/ugroups');
                }else{
                  console.log("新增受众异常");
                }
              })


              // usergroupApi
              //   .save(this.form)
              //   .then((res) => {
              //     if (res.status == 200) {
              //       this.$message({ type: "success", message: "新增成功" ,offset:50});
              //       this.$router.push('/manage/ugroups');
              //     }
              //   })
              //   .catch((res) => {
              //     this.$message({ type: "error", message: res.message ,offset:50});
              //   });
            }
          }
        });
      }
    }
  }
</script>

<style lang="scss" scoped>
::v-deep .el-tree-node:focus>.el-tree-node__content {
    background-color:#cddef8;
}
  .addAudiences{
    .basicInformation{
      margin: 0;
      padding: 15px 0;
      border-bottom: 1px solid rgb(219, 219, 219);
    }
    .el-form{
      margin-top:20px;
    }
    .action{
      margin: 20px 0;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      .el-input{
        margin-right: 10px;
      }
      .findBtn{
        margin-right: auto;
      }
    }
    .publish{
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 10px 0;
    }
  }
</style>
