<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <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"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['danger:group: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="['danger:group: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="['danger:group:remove']"
        >删除</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="['danger:group:export']"
        >导出</el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="组名" align="center" prop="groupName" />
      <el-table-column label="成员" align="center" prop="memberName" />
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="备注" align="center" prop="remarks" />
      <el-table-column label="操作" align="center" 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="['danger:group:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['danger:group:remove']"
          >删除</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="1000px" append-to-body destroy-on-close :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <div class="title">基本信息</div>
        <el-row>
          <el-col :span="12">
            <el-form-item label="组名" prop="groupName">
              <el-input v-model="form.groupName" placeholder="请输入组名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组类型" prop="type">
              <el-select
                v-model="form.type"
                placeholder="请选择组类型"
                style="width: 100%"
                @change="changeType"
              >
                <el-option label="巡检组" value="1"/>
                <el-option label="维修班" value="2"/>
                <el-option label="网格班" value="3"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remarks">
              <el-input type="textarea" v-model="form.remarks" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>

        <div class="title">成员信息</div>
        <el-row style="height: 400px">
          <el-col :span="24" style="height: 100%">
            <div class="choice-title">
              <div class="choice-title-item" style="flex: 2.1">待选组员</div>
              <div class="choice-title-item">已选组员</div>
              <div class="choice-title-item">已选组长: {{ leaderName ? leaderName : "未选择" }}</div>
            </div>
            <div class="person-choice">
              <div class="person-choice-left">
                <div style="padding: 0px 1px 7px 0px;">
                  <el-input
                    v-model="personParam.nickName"
                    placeholder="姓名"
                    clearable
                    size="small"
                    style="width: 250px;margin-right: 10px"
                  />
                  <el-button
                    type="primary"
                    size="small"
                    icon="el-icon-search"
                    @click="queryPersonList"
                  >
                    搜索
                  </el-button>
                </div>

                <el-table
                  v-loading="loading"
                  :data="personList"
                  ref="personTable"
                  @select="select"
                  @select-all="selectAll"
                >
                  <el-table-column type="selection"></el-table-column>
                  <el-table-column label="姓名" align="center" prop="nickName" :show-overflow-tooltip="true" />
                  <el-table-column label="电话" align="center" prop="phonenumber" :show-overflow-tooltip="true"/>
                  <el-table-column label="所在部门" align="center" prop="deptName" :show-overflow-tooltip="true"/>
                </el-table>
              </div>

              <div class="person-choice-middle">
                <div>>></div>
              </div>

              <div class="person-choice-right">

                <div class="select-box">
                  <div
                    class="person-select"
                    v-for="(person,index) in form.memberInfoList"
                  >
                    <input class="person-radio" v-model="leaderId" type="radio" :value="person.userId" @change="leaderChange">
                    <el-tooltip class="item" effect="dark" :content="person.nickName" placement="bottom-start">
                      <div class="person-name">{{ person.nickName }}</div>
                    </el-tooltip>

                    <div class="person-delete" @click="deletePerson(person,index)">X</div>
                  </div>
                </div>

                <div class="bottom-text">已选择{{ form.memberInfoList.length }}人</div>

              </div>
            </div>
          </el-col>
        </el-row>


      </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>
  </div>
</template>

<script>
  import { listInfo, getInfo, delInfo, addInfo, updateInfo, exportInfo } from "@/api/checktask/dangerGroup";
  import { selectRectifyUserByPostCode } from "@/api/checktask/dangerGroupMember";
  export default {
    name: "Info",
    components: {
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        groupNames: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 人员分组信息表格数据
        infoList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          groupName: null,
          isDel: null,
          remarks: null
        },
        // 表单参数
        form: {
          memberInfoList: [],
        },
        // 表单校验
        rules: {
          groupName: [
            { required: true, message: "组名不能为空", trigger: "blur" },
          ],
          type: [
            { required: true, message: "请选择组类型", trigger: "change" },
          ]
        },
        personParam: {
          nickName: null,
          groupId: null,
        },
        personList: [],
        leaderId: null,
        leaderName: null
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询人员分组信息列表 */
      getList() {
        this.loading = true;
        listInfo(this.queryParams).then(response => {
          this.infoList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          groupId: null,
          groupName: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          isDel: null,
          remarks: null,
          memberInfoList: [],
        };
        this.personParam = {
          nickName: null,
          groupId: null,
        },
        this.leaderName = "";
        this.leaderId = null;
        this.resetForm("form");
        this.personList = [];
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.groupId);
        this.groupNames = selection.map(item => item.groupName);
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加人员分组信息";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const groupId = row.groupId || this.ids
        getInfo(groupId).then(response => {
          this.form = response.data;
          /*if("1" == this.form.type){
            this.personParam.postCode = "linepatrol";
          }else if("2" == this.form.type){
            this.personParam.postCode = "repair";
          }else{
            this.personParam.postCode = "grid";
          }*/
          this.personParam.groupId = groupId;
          this.queryPersonList();
          this.open = true;
          this.title = "修改人员分组信息";
        });
      },
      /** 提交按钮 */
      submitForm() {
        if(!this.leaderId){
          this.$message.error("未选择组长！")
          return
        }
        let leadeInfo = this.form.memberInfoList.find(item => item.userId == this.leaderId);
        leadeInfo.post = '1';
        this.$refs["form"].validate(valid => {
          if (valid) {
            if(this.validateMemberInfo()) return;
            if (this.form.groupId != null) {
              updateInfo(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addInfo(this.form).then(response => {
                this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
              });
            }
          }
        });
      },
      validateMemberInfo(){
        if(this.form.memberInfoList.length == 0){
          this.msgError("成员不能为空！");
          return true;
        }
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const groupIds = row.groupId || this.ids;
        const groupNames = row.groupName || this.groupNames;
        this.$confirm('是否确认删除人员分组组名为"' + groupNames + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delInfo(groupIds);
        }).then(() => {
          this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有人员分组信息数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
        return exportInfo(queryParams);
      }).then(response => {
          this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {});
      },
      //全选
      selectAll(all){
        //删除所有
        if (all.length == 0 || (all.length == 1 && [0] == undefined)){
          this.form.memberInfoList = [];
          this.leaderId = null;
          this.leaderName = "";
        }
        //全选
        if(all.length >0){
          all.forEach((item) => {
            let index = this.form.memberInfoList.findIndex(person => person.userId ==  item.userId);
            if(index == -1){
              let data = {userId: item.userId, nickName: item.nickName, groupId: this.form.groupId};
              if(this.form.groupId){
                data.groupId = this.form.groupId;
              }
              this.form.memberInfoList.push(data);
            }
          })
        }

      },
      //选中
      select(all,row){
        let index = this.form.memberInfoList.findIndex(item => item.userId == row.userId);
        if(index >= 0) {
          this.form.memberInfoList.splice(index, 1);
          if(row.userId == this.leaderId){
            this.leaderId = null;
            this.leaderName = "";
          }
        }else{
          let data = {userId: row.userId, nickName: row.nickName, groupId: this.form.groupId};
          if(this.form.groupId){
            data.groupId = this.form.groupId;
          }
          this.form.memberInfoList.push(data);
        }
      },
      deletePerson(person,index){
        this.form.memberInfoList.splice(index, 1);
        let item = this.personList.find(item => item.userId == person.userId);
        this.$refs.personTable.toggleRowSelection(item,false);
        //删除的是组长置空
        if(this.leaderId == person.userId){
          this.leaderId = null;
          this.leaderName = "";
        }
      },
      queryPersonList(){
        selectRectifyUserByPostCode(this.personParam).then(res =>{
          if(res.code == 200){
              this.personList = res.data;
              if(this.form.memberInfoList){
                this.form.memberInfoList.forEach(item => {
                  if(item.post == '1'){
                      this.leaderId = item.userId;
                      this.leaderName = item.nickName;
                  }
                  let person = this.personList.find(person => person.userId == item.userId);
                  if(person){
                    this.$nextTick(() => {
                      this.$refs.personTable.toggleRowSelection(person,true);
                    })
                  }
                })
              }
          }
        })
      },
      // 切换类型
      changeType(val){
        /*if("1" == val){
          this.personParam.postCode = "linepatrol";
        }else if("2" == val){
          this.personParam.postCode = "repair";
        }else{
          this.personParam.postCode = "grid";
        }*/
        this.queryPersonList();
        this.form.memberInfoList = [];
        this.leaderId = null;
        this.leaderName = "";
      },
      leaderChange(){
        let leaderInfo = this.form.memberInfoList.find(item => item.userId == this.leaderId);
        this.leaderName = leaderInfo ? leaderInfo.nickName : "";
      }
    }
  };
</script>
<style lang="scss" scoped>
  .person-choice{
    display: flex;
    padding: 0px 10px 5px 10px;
    height: 100%;
  }

  .choice-title{
    display: flex;
    .choice-title-item{
      flex: 1;
      padding: 0px 0px 6px 12px;
      font-size: 13px;
      color: #82848a;
    }
  }

  .person-choice-left{
    border: 1px solid #e5e6eb;
    width: 48%;
    height: 100%;
    padding: 13px;
    overflow-y: auto;
    &::-webkit-scrollbar {
      width: 3px;
      background:  #dfe4ed;
      position: absolute;
      top: 0;
    }
    &::-webkit-scrollbar-thumb {
      /*滚动条里面小方块*/
      // border-radius: 10px;
      // box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
      background: #cccccc;
      border-radius: 5px;
    }
  }

  .person-choice-middle{
    height: 100%;
    width: 4%;
    align-items: center;
    justify-content: center;
    display: flex;
    color: #1890ff;
  }

  .person-choice-right{
    border: 1px solid #e5e6eb;
    height: 100%;
    width: 48%;
    .select-box{
      padding: 10px;
      display: flex;
      flex-wrap: wrap;
      align-content: flex-start;
      overflow-y: auto;
      height: 94%;
      width: 100%;
      &::-webkit-scrollbar {
        width: 3px;
        background:  #dfe4ed;
        position: absolute;
        top: 0;
      }
      &::-webkit-scrollbar-thumb {
        /*滚动条里面小方块*/
        // border-radius: 10px;
        // box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
        background: #cccccc;
        border-radius: 5px;
      }
      .person-select{
        border: 1px solid #a3d3ff;
        border-radius: 3px;
        height: 40px;
        width: 48%;
        display: flex;
        padding: 5px;
        margin: 3px;
        color: #3d3d3d;
        font-size: 12px;
        .person-name{
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          line-height: 26px;
          width: 79%;
          text-align: center;
        }
        .person-delete{
          line-height: 26px;
          cursor: pointer;
        }
        .person-radio{
          height: 19px
        }
      }
    }

    .bottom-text {
      padding: 8px 5px 0px 0px;
      font-size: 14px;
      height: 20px;
      line-height: 3px;
      text-align: right;
      color: #1890ff;
    }
  }

  .title{
    font-size: 16px;
    font-weight: 700;
    margin-bottom: 20px;
  }
</style>
