<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <!-- <el-form-item label="关键字" prop="postName">
          <el-input
            v-model="queryParams.postName"
            placeholder="请输入关键字"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item> -->
        <el-form-item label="班组名称" prop="teamName">
          <el-input
            v-model="queryParams.teamName"
            placeholder="请输入班组名称"
            clearable
            @keyup.enter.native="handleQuery"
            maxlength="30"
          />
        </el-form-item>
        <el-form-item label="班组长" prop="teamLeader">
          <el-input
            v-model="queryParams.teamLeader"
            placeholder="请输入班组长"
            clearable
            @keyup.enter.native="handleQuery"
            maxlength="30"
          />
        </el-form-item>
        <!-- <el-form-item label="项目部" prop="roleCode">
          <el-input
            v-model="queryParams.roleCode"
            placeholder="请输入项目部"
            clearable
            @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="['basic:team:add']"
          >新增班组</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['basic:team:export']"
          >导出</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="['system:post: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="['system:post:remove']"
          >删除</el-button>
        </el-col>
        -->
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
  
      <el-table v-loading="loading" :data="teamList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="班组名称" align="center" prop="teamName" />
        <el-table-column label="所属工程 " align="center" prop="proName" />
        <el-table-column label="班组长" align="center" prop="teamLeader" />
        <el-table-column label="班组成员(在施\未施)" align="center" prop="workNum">
            <template slot-scope="scope">
                <div style="cursor: pointer;" @click="openTeamTable(scope.row)">
                    <span style="color: green;">{{ scope.row.workNum }}/</span><span>{{ scope.row.notWorkNum }}</span>
                </div>
                
            </template>
        </el-table-column>
        
        <el-table-column label="班组状态" align="center" prop="teamStatus">
            <template slot-scope="scope">
                <div v-if="scope.row.teamStatus==0" style="color: green;">{{ stateList[Number(scope.row.teamStatus)] }}</div>
                <div v-if="scope.row.teamStatus==1" style="color: red;">{{ stateList[Number(scope.row.teamStatus)] }}</div>
            </template>
        </el-table-column>
        <el-table-column label="创建日期" align="center" prop="createTime" width="180">
            <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
        </el-table-column>
        <el-table-column label="解散日期" align="center" prop="jsTime" width="180">
            <template slot-scope="scope">
                <span>{{ parseTime(scope.row.jsTime) || '- -' }}</span>
            </template>
        </el-table-column>
        <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"
              v-if="scope.row.teamStatus==0"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['basic:team:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['basic:team:del']"
            >删除</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              v-if="scope.row.teamStatus==0"
              @click="handleDissolution(scope.row)"
              v-hasPermi="['basic:team:dissolution']"
            >解散</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"
      />


<!-- -------------------分割线---------------------------------- -->

      <!-- 班组成员dialog -->
        <el-dialog title="班组成员" :visible.sync="openTeam" width="1000px" append-to-body>
            <!-- 搜索 -->
            <el-form :model="formQuery" ref="formQuery" size="small" :inline="true" label-width="68px">
                <el-form-item label="姓名" prop="name">
                    <el-input
                        v-model="formQuery.name"
                        placeholder="请输入姓名"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-select v-model="formQuery.sex" placeholder="性别" clearable>
                        <el-option
                        v-for="dict in dict.type.sys_user_sex"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                        />
                    </el-select>
                </el-form-item>
                
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleMemberQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetMemberQuery">重置</el-button>
            </el-form-item>
            </el-form>
            <!-- 表格 -->
            <el-table :data="memberList">
                <el-table-column label="序号" align="center" type="index" />
                <el-table-column label="姓名" align="center" prop="name" />
                <el-table-column label="性别" align="center" prop="sex" width="60">
                <template slot-scope="scope">
                        <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex"/>
                    </template>
                </el-table-column>
                <el-table-column label="身份证号" align="center" prop="idCard" width="180"/>
                <el-table-column label="电话" align="center" prop="phone" />
            
                <el-table-column label="状态" align="center" prop="workStatus">
                    <template slot-scope="scope">
                        <div v-if="scope.row.workStatus==0" style="color: green;">{{ workStateList[Number(scope.row.workStatus)] }}</div>
                        <div v-if="scope.row.workStatus==1" style="color: grey;">{{ workStateList[Number(scope.row.workStatus)] }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="手环编码" align="center" prop="braceletCode">
                    <template slot-scope="scope">
                        <div>{{ scope.row.braceletCode || '- -'}}</div>
                        
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <pagination
                v-show="memberTotal>0"
                :total="memberTotal"
                :page.sync="formQuery.pageNum"
                :limit.sync="formQuery.pageSize"
                @pagination="getTeamTable"
            />
            <div slot="footer" class="dialog-footer">
            <el-button @click="openTeam=false">取 消</el-button>
            </div>
        </el-dialog>
  
      <!-- 添加或修改班组对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="850px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
            <el-row :gutter="24">
                <el-col :span="12">
                    <el-form-item label="班组名称" prop="teamName">
                        <el-input v-model="form.teamName" placeholder="请输入班组名称" maxlength="20"/>
                    </el-form-item>
                </el-col>

                <el-col :span="12">
                    <el-form-item label="班组长" prop="teamLeaderId">
                        <el-select v-model="form.teamLeaderId" placeholder="请选择班组长" clearable filterable style="width: 100%;" @change="changeLeader">
                            <el-option
                            v-for="item in personList"
                            :key="item.id"
                            :label="item.name+'-'+item.phone"
                            :value="item.id"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="24">
                <el-col :span="12">
                    <el-form-item label="班组成员" prop="userIdArrIds">
                        <el-input v-model="form.userIdArrIds" v-show="false"/>
                        <span style="margin-left: 20px;color:aquamarine;cursor: pointer;" @click="openChosen()">选择成员</span>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="所属工程" prop="proId">
                        <el-select v-model="form.proId" placeholder="请选择所属工程" clearable style="width: 100%;">
                            <el-option
                            v-for="dict in proList"
                            :key="dict.id"
                            :label="dict.name"
                            :value="dict.id"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="24" style="display: flex;justify-content: center;">
                <el-col :span="23">
                <el-table :data="teamUserList" style="max-height: 300px;overflow-y: auto;">
                    <el-table-column label="序号" type="index" />
                    <el-table-column label="姓名" align="center" prop="name" />
                    <el-table-column label="身份证" align="center" prop="idCard" />
                    <el-table-column label="电话" align="center" prop="phone" />
                    <el-table-column label="操作" align="center" >
                        <template slot-scope="scope">
                            <el-button size="mini" type="text" @click="delUser(scope.row)" v-if="scope.row.isLeader!=0">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                </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>

      <!-- 选择添加成员弹窗 -->
      <el-dialog title="选择" :visible.sync="openPeople" width="700px" append-to-body>
        <div class="people-dialog" style="">
            <!-- 左侧人员 -->
            <div class="people-list-box">
                <div class="dialog-header">
                    <el-input style="width: 90%;" @input="searchUser(searchName)"
                        placeholder="请输入人员姓名"
                        prefix-icon="el-icon-search"
                        v-model="searchName">
                    </el-input>
                </div>
                <div style="height: 80%;overflow-y: auto">
                    <el-table :data="peopleList" :show-header="false" @select="selectTeamPeople" ref="peopleTable" :row-key="(row) => { return row.id }">
                        <el-table-column type="selection" width="45" align="center"  :reserve-selection="true"/>
                        <el-table-column label="姓名" align="center" prop="name" width="80"/>
                        <el-table-column label="身份证" align="center" prop="idCard" />
                        <el-table-column label="电话" align="center" prop="phone" />
                    </el-table>
                </div>
            </div>
            <!-- 右侧选中 -->
            <div class="chosen-list-box">
                <div class="dialog-header">已选择</div>
                <div class="chosen-list">
                    <div class="chosen-list-item" v-for="item in chosenUser" :key="item.id">
                        <div style="margin-left: 20px;">{{ item.name }}</div>
                        <div style="margin-right: 20px;cursor: pointer;" @click="delChosen(item)">
                            <i class="el-icon-close" />
                        </div>
                    </div>
                </div>
            </div>

        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitPeople">确 定</el-button>
          <el-button @click="cancelPeople">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { listTeam,getPersonList,addTeam,editTeam,getTeamInfo,delTeam,dissolutionTeam,exportTeam,getWorkPersonList } from "@/api/base/team";
  import { getProList } from "@/api/select";
  import { downloadFile } from '@/utils/download'
  export default {
    name: "Post",
    dicts: ['sys_normal_disable','sys_user_sex'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 班组表格数据
        teamList: [],
        proList: [],
        personList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        //班组成员
        openTeam:false,
        memberList:[],
        formQuery:{
            teamId:'',
            pageNum: 1,
            pageSize: 10,
            name: undefined,
            sex: undefined,
        },
        memberTotal: 0, // 总条数
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          teamName:'',
          teamLeader:'',
          roleCode: this.$store.getters.roleCode,
          departId: this.$store.getters.departId,
          teamId: this.$store.getters.teamId,
        },
        stateList:['正常','已解散'],
        workStateList:['在施工','未施工'],
        // 表单参数
        form: {},
        teamUserList:[],//新增编辑弹窗-班组成员
        leaderData:{},//新增编辑弹窗-班组长
        chosenUser:[],//人员列表右侧-选中人员
        peopleDataList:[],//接口获取-所有人员列表
        peopleList:[],//人员列表左侧-表格渲染
        checkList:[],//编辑-详情-已选组员
        searchName:'',//人员弹窗-搜索框变量
        openPeople: false,
        // 表单校验
        rules: {
            teamName: [
                { required: true, message: "班组名称不能为空", trigger: "blur" }
            ],
            teamLeaderId: [
                { required: true, message: "班组长不能为空", trigger: "change" }
            ],
            // userIdArrIds: [
            //     { required: true, message: "班组成员不能为空", trigger: "change" }
            // ],
            proId: [
                { required: true, message: "所属工程不能为空", trigger: "change" }
            ]
        }
      };
    },
     
    created() {
      this.getProList();
      this.getPersonList();
      this.getList();
    },
    methods: {
        //获取所属工程
        getProList(){
            getProList().then(response => {
               this.proList = response.data;
            });
        },
        // 获取人员列表
        getPersonList(){
            let param = {
                type:4,//1.全部人员 2.未分配人员 3.已分配人员 4.班组长
                roleCode: this.$store.getters.roleCode,
                departId: this.$store.getters.departId,
                teamId: this.$store.getters.teamId,
            }
            getPersonList(param).then(response => {
               this.personList = response.data;
            });
        },
        // 班组长下拉选
        changeLeader(val){
            console.log(val)
            this.personList.forEach(item=>{
                if(item.id==val){
                    this.form.teamLeader = item.name;
                    this.form.leaderPhone = item.phone;
                    this.leaderData=item;
                }
            })
            this.leaderData.isLeader=0;//是否班组长，0是1否
            if(this.teamUserList.length==0){
                this.teamUserList.push(this.leaderData)
            }else{
                var index = this.teamUserList.findIndex(uItem => {return uItem.isLeader == 0})
                if(index>-1){
                    this.teamUserList.splice(index,1)
                    this.teamUserList.unshift(this.leaderData)
                }else{
                    this.teamUserList.unshift(this.leaderData)
                }
            }
        },
        /** 查询班组列表 */
        getList() {
            this.loading = true;
            listTeam(this.queryParams).then(response => {
                this.teamList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.teamUserList = []
            this.form = {
                teamName: undefined,
                teamLeader: undefined,
                teamLeaderId: undefined,
                proId: undefined,
                userIdArr: undefined,
                userIdArrIds: undefined,
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.teamId)
            this.single = selection.length!=1
            this.multiple = !selection.length
        },
        //查看班组成员
        openTeamTable(row){
            // this.teamId = row.teamId;
            this.openTeam = true;
            this.formQuery = {
                teamId:row.teamId,
                pageNum: 1,
                pageSize: 10,
                name: undefined,
                sex: undefined,
            }
            this.getTeamTable()
        },
        //获取成员
        getTeamTable(){
            getWorkPersonList(this.formQuery).then(response => {
                this.memberList = response.rows;
                this.memberTotal = response.total;
            });
        },
        // 查询
        handleMemberQuery(){
            this.formQuery.pageNum = 1;
            this.getTeamTable();
        },
        // 重置
        resetMemberQuery(){
            this.resetForm("formQuery");
            this.handleMemberQuery();
        },
        //人员表格-删除
        delUser(row){   
            console.log(row)
            let sum = 0
            this.teamUserList.forEach((item, index) => {
                if (item.id == row.id) {
                    sum = index
                }
            })
            this.teamUserList.splice(sum, 1)
        },
        //打开选择人员
        openChosen(){
            this.openPeople = true;
            this.searchName = '';
            this.chosenUser = this.teamUserList.slice();
            let param = {
                type:2,//1.全部人员 2.未分配人员 3.已分配人员
                roleCode: this.$store.getters.roleCode,
                departId: this.$store.getters.departId,
                teamId: this.$store.getters.teamId,
            }
            getPersonList(param).then(response => {
                this.peopleDataList = this.checkList.concat(response.data);
                this.peopleList = this.peopleDataList;
                this.$nextTick(()=>{
                    this.$refs.peopleTable.clearSelection()
                    this.peopleList.forEach(row => {
                        for(let i=0;i<this.teamUserList.length;i++){
                            if(row.id==this.teamUserList[i].id){
                                this.$refs.peopleTable.toggleRowSelection(row,true);
                            }
                        }
                    }) 
                })
            });
        },
        // 搜索人员姓名
        searchUser(val){
            if(val!=''){
                this.peopleList = this.peopleDataList.filter(item => item.name.includes(val));
            }else{
                this.peopleList = this.peopleDataList;
            }
            
        },
        //勾选选择框
        selectTeamPeople(selection,row) {
            this.chosenUser = selection;
            // this.chosenIds = selection.map(item => item.userId)
        },
        //选择人员-右侧删除
        delChosen(obj){
            let sum = 0
            this.chosenUser.forEach((item, index) => {
                if (item.id == obj.id) {sum = index;}
            })
            //删除
            this.chosenUser.splice(sum, 1)
            // 取消勾选
            this.$nextTick(()=>{
                this.$refs.peopleTable.clearSelection()
                this.peopleList.forEach(row => {
                    for(let i=0;i<this.chosenUser.length;i++){
                        if(row.id==this.chosenUser[i].id){
                            this.$refs.peopleTable.toggleRowSelection(row,true);
                        }
                    }
                }) 
            })
            
        },
        //选择人员弹窗-关闭
        cancelPeople() {
            this.openPeople = false;
        },
        //选择人员弹窗-确认
        submitPeople(){
            // console.log(this.teamUserList)
            // console.log(this.chosenUser)
            this.teamUserList = this.chosenUser;
            this.teamUserList.unshift(this.leaderData)
            this.openPeople = false;
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.checkList = []
            this.open = true;
            this.title = "添加班组";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const teamId = row.teamId
            getTeamInfo({id:teamId}).then(response => {
                this.form = response.data;
                this.personList.forEach(item=>{
                    if(item.id==this.form.teamLeaderId){
                        this.leaderData=item;
                        this.leaderData.isLeader=0;
                    }
                })

                this.$set(this.form,'proId',response.data.proId+'')
                this.checkList = response.data.checkList;
                // this.$set(this.form,'sex',response.data.sex+'')
                this.teamUserList = response.data.checkList.slice();
                this.teamUserList.unshift(this.leaderData)
                this.open = true;
                this.title = "修改班组";
            });
        },
        /** 提交按钮 */
        submitForm: function() {
            this.form.userIdArr = this.teamUserList.map(item => item.id)
            this.form.userIdArrIds = this.form.userIdArr.join(',')
            this.$refs["form"].validate(valid => {
            if (valid) {
                if (this.form.teamId != undefined) {
                    editTeam(this.form).then(response => {
                        this.$modal.msgSuccess("修改成功");
                        this.open = false;
                        this.getList();
                    });
                } else {
                    console.log(this.form)
                    addTeam(this.form).then(response => {
                        this.$modal.msgSuccess("新增成功");
                        this.open = false;
                        this.getList();
                    });
                }
            }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const teamIds = row.teamId;
            this.$modal.confirm('是否确认删除班组编号为"' + teamIds + '"的数据项？').then(function() {
            return delTeam({id:teamIds});
            }).then(() => {
            this.getList();
            this.$modal.msgSuccess("删除成功");
            }).catch(() => {});
        },
         /** 解散按钮操作 */
         handleDissolution(row) {
            const teamIds = row.teamId;
            this.$modal.confirm('是否确认解散班组编号为"' + teamIds + '"的数据项？').then(function() {
            return dissolutionTeam({id:teamIds});
            }).then(() => {
            this.getList();
            this.$modal.msgSuccess("解散成功");
            }).catch(() => {});
        },
        /** 导出按钮操作 */
        handleExport() {
            exportTeam(this.queryParams).then(res => {
                downloadFile({ fileName: `班组_${new Date().getTime()}.xlsx`, fileData: res, fileType: 'application/vnd.ms-excel;charset=utf-8' })
            })
        }
    }
  };
  </script>
  
<style lang="scss" scoped>
    .people-dialog{
        width: 100%;height: 500px;display: flex; justify-content: space-between;
    }
    .people-list-box{
        width: 55%;height: 98%;border: 1px solid #e0e0e0;
    }
    .chosen-list-box{
        width: 40%;height: 98%;border: 1px solid #e0e0e0;
    }
    .chosen-list{
        height: 85%;overflow-y: auto;
    }
    .chosen-list-item{
        width: 100%;height: 40px;display: flex;justify-content: space-between;align-items: center;
    }
    .dialog-header{
        width: 100%;height: 60px;background-color: #F2F2F2;display: flex;align-items: center;justify-content: center;
    }
</style>