<template>
    <div class="communal-list"  v-loading.fullscreen.lock="fullscreenLoading">
        <div class="communal-title">
            <div>团组任务分配</div>
        </div>
        <el-dialog title="批量分配" :visible.sync="batchVisible"  :close-on-click-modal="false">
            <el-form ref="batch" :rules="batchs" :model="batch">
                <div class="batchbox">
                    <el-form-item prop="TimePeriod" label="时间段" :label-width="formLabelWidth">
                        <el-date-picker
                        style="width:250px;"
                        v-model="batch.TimePeriod"
                        @change="TimePeriodchange"
                        type="daterange"
                        align="right"
                        unlink-panels
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        :picker-options="pickerOptions">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item prop="category" label="权限类型" :label-width="formLabelWidth">
                        <el-select filterable multiple collapse-tags v-model="batch.category" placeholder="请选择权限类型">
                            <el-option v-for=" item1 in setData" :key=item1.id :label=item1.name :value=item1.id></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="person" label="人员" :label-width="formLabelWidth">
                        <el-select filterable multiple collapse-tags v-model="batch.person" placeholder="请选择人员">
                          <el-option v-for="(  item, index  ) in   user  " :key="index"  :label="item.name" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                </div>
                <div class="batch">
                    <el-button @click="CancelselectAll" size="mini">取消选择</el-button>
                    <el-button @click="selectAll" type="primary" size="mini">全选</el-button>
                </div>
                <div class="checkbox-box">
                    <el-checkbox-group @change="checkListchange" class="group-box" v-model="checkList">
                        <el-checkbox style="width:45%;margin-bottom: 5px;" v-for="(item,index) in protogenesischeckList" :key="index" :label="item.teamName"></el-checkbox>
                    </el-checkbox-group>
                </div>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="batchVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm('batch')">确 定</el-button>
            </div>
        </el-dialog>
        <div class="konzh" style="display: flex;justify-content: space-between;">
            <el-form style="display: flex;" label-width="70px" class="demo-form-inline">
                <el-form-item style="width: 300px;margin-right: 20px;" label="团组名称">
                    <el-select v-model="diId" filterable :filter-method="advancedFilter" clearable placeholder="请选择" style="width:230px;"
                        @change="diidChange()">
                        <el-option v-for="item1 in delegationInfoss" :key=item1.id :label=item1.name
                            :value=item1.id></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item style="width: 300px;margin-right: 20px;" label="操作分类">
                    <el-select v-model="ctId" filterable clearable placeholder="请选择" style="width:230px;"
                    @change="sdIdChange()">
                        <el-option v-for=" item1 in setData" :key=item1.id :label=item1.name :value=item1.id></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
                <!-- <div style="width: 240px;margin-right: 20px;">
                    <el-select v-model="diId" filterable clearable placeholder="请选择" style="width:100%;"
                        @change="diidChange()">
                        <el-option v-for="item1 in delegationInfos" :key=item1.id :label=item1.name
                            :value=item1.id></el-option>
                    </el-select>
                </div>
                <div style="width: 200px;">
                    <el-select v-model="ctId" filterable clearable placeholder="请选择" style="width:100%;"
                        @change="sdIdChange()">
                        <el-option v-for=" item1 in setData" :key=item1.id :label=item1.name :value=item1.id></el-option>
                    </el-select>
                </div> -->
  
            <div style="width: 30%;text-align: right;">
                <el-button type="primary" style="margin-left: 10px;" @click="batchbtn">批量添加</el-button>
                <el-button type="primary" style="margin-left: 10px;" @click="btn">保存</el-button>
            </div>
        </div>
        <div class="tzinif-info">
            <div class="tzinif-info-li">
                <label>团 号：</label>
                <span>{{ DelegationInfo.tourCode  }}</span>
            </div>
            <div class="tzinif-info-li">
                <label>客 户：</label>
                <span>{{ DelegationInfo.clientName }}</span>
            </div>
            <div class="tzinif-info-li">
                <label>出访国家：</label>
                <span>{{ DelegationInfo.visitCountry |filter_city}}</span>
            </div>
            <div class="tzinif-info-li">
                <label>起止日期：</label>
                <span>{{ DelegationInfo.visitStartDate|filter_time }}~{{ DelegationInfo.visitEndDate|filter_time}}</span>
            </div>
            <div class="tzinif-info-li">
                <label>天数/人数：</label>
                <span>{{ DelegationInfo.visitDays }}/{{ DelegationInfo.visitPNumber }}</span>
            </div>
        </div>
        <!-- <div class="tzinif">
            <span style="font-weight: bold;">团 号：</span>{{ DelegationInfo.tourCode }}
            <span style="font-weight: bold;">客 户：</span>{{ DelegationInfo.clientName }}
            <span style="font-weight: bold;">出访国家：</span>{{ DelegationInfo.visitCountry }}
            <span style="font-weight: bold;">起止日期：</span>{{ DelegationInfo.visitStartDate }} ～ {{
                DelegationInfo.visitEndDate }}
            <span style="font-weight: bold;">天数/人数：</span>{{ DelegationInfo.visitDays }}天/{{ DelegationInfo.visitPNumber }}人
        </div> -->
        <!-- <div>
            <div>人员安排</div>
        </div> -->
        <div style="margin-top: 10px;border-top: 1px solid #C0C4CC;">
            <div style="display: flex;flex-wrap: wrap;">
                <div v-for="(  item, index  ) in   user  " 
                :key="index" 
                style="width: 12.5%;margin: 10px 0;text-align: center;">
                    <el-checkbox :label="item.id" :value="userStr.indexOf(item.id) != -1" border @change="check(item.id)"
                        style="width: 120px;">{{
                            item.name
                        }}</el-checkbox>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            pickerOptions: {
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                    picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                    picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近三个月',
                    onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                    picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一年',
                    onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
                    picker.$emit('pick', [start, end]);
                    }
                }]
            },
            rules: {},
            token: '',
            userId: 0,
            delegationInfos: [],
            delegationInfoss: [],
            searchMode: 'character', // 'character': 字符匹配, 'fuzzy': 模糊匹配
            setData: [],
            user: [],
            diId: '',
            ctId: '',
            userStr: [],
            TaskAssignment: {},
            DelegationInfo: {},
            fullscreenLoading:false,
            formLabelWidth:"80px",
            batch:{
                TimePeriod:[],
                person:[],
                category:[]
            },
            batchs: {
                TimePeriod: [
                    { required: true, message: '请选着日期', trigger: 'blur' },
                ],
                person: [
                    { required: true, message: '请选择人员', trigger: 'blur' },
                ],
                category: [
                    { required: true, message: '请选择权限类型', trigger: 'blur' },
                ],
            },
            batchVisible:false,
            checkList:[],
            protogenesischeckList:[],
            uploadingcheckList:[]
        }
    },
    methods: {
        advancedFilter(query) {
            console.log(query);
            
            if (!query || query.trim() === '') {
                this.delegationInfoss = [...this.delegationInfos];
                return;
            }

            const trimmedQuery = query.trim();

            if (this.searchMode === 'character') {
                // 字符匹配模式：每个字都必须包含
                this.characterMatchFilter(trimmedQuery);
            } else {
                // 模糊匹配模式（默认的filterable行为）
                this.fuzzyMatchFilter(trimmedQuery);
            }
        },

        /*** 严格的字符匹配 - 每个查询字符都必须出现*/
        characterMatchFilter(query) {
            const queryChars = query.split('').filter(char => char.trim() !== '');

            this.delegationInfoss = this.delegationInfos.filter(item => {
                const groupName = item.name || '';
                return queryChars.every(char => groupName.includes(char));
            });
        },
        /*** 模糊匹配 - 包含整个查询字符串即可*/
        fuzzyMatchFilter(query) {
            const lowerQuery = query.toLowerCase();
            this.delegationInfoss = this.delegationInfos.filter(item => {
                const groupName = (item.name || '').toLowerCase();
                return groupName.includes(lowerQuery);
            });
        },
        GetTaskAssignmen() {
            this.fullscreenLoading=true;
            var that = this
            var url = "/api/Groups/GetTaskAssignmen";
            this.$axios({
                method: 'post',
                url: url,
                headers: {
                    Authorization: 'Bearer ' + this.token
                },
            }).then(function (res) {
                console.log(res)
                if (res.data.code == 200) {
                    that.delegationInfos = res.data.data.delegationInfos;
                    that.delegationInfoss = that.delegationInfos;
                    that.diId=res.data.data.delegationInfos[0].id;
                    that.setData = res.data.data.setData;
                    that.setData = that.setData.filter(function(item) {
                        return item.name !== "文档下载"&&item.name !== "会务相关"
                    });
                    that.ctId=res.data.data.setData[0].id;
                    that.user = res.data.data.user;
                    setTimeout(() => {
                        that.TaskAssignmenQuery();
                    }, 500);
                    console.log(that.setData)
                }
            })
        },
        //处理时间
        getdate(val){
            var date=new Date(val);
            var y=date.getFullYear();
            var m=date.getMonth()+1<10?'0'+(date.getMonth()+1):date.getMonth()+1;
            var d=date.getDate()<10?'0'+date.getDate():date.getDate();
            return y+'-'+m+'-'+d
        },
        //取消全选
        CancelselectAll(){
            this.checkList=[];
            this.uploadingcheckList=[];
        },
        //全选
        selectAll(){
            for(let i=0;i<this.protogenesischeckList.length;i++){
                this.checkList.push(this.protogenesischeckList[i].teamName)
            }
            this.acquireid()
        },
        //团组checkbox值改变
        checkListchange(){
            this.acquireid();
        },
        //时间段切换
        TimePeriodchange(){
            this.TaskAllocationGroupSelect()
        },
        //获取时间段数组
        TaskAllocationGroupSelect() {
            var that = this
            var url = "/api/Groups/TaskAllocationGroupSelect";
            this.$axios({
                method: 'post',
                url: url,
                data: {
                    portType: 1,
                    visitBeginDt: that.getdate(that.batch.TimePeriod[0]),
                    visitEndDt: that.getdate(that.batch.TimePeriod[1]),
                },
                headers: {
                    Authorization: 'Bearer '
                },
            }).then(function (res) {
                if (res.data.code == 200) {
                    that.protogenesischeckList=res.data.data;
                } else {
                    
                }
            })
        },
        //获取选择团组id
        acquireid(){
            this.uploadingcheckList=[];
            for(let j=0;j<this.checkList.length;j++){
                for(let i=0;i<this.protogenesischeckList.length;i++){
                    if(this.checkList[j]==this.protogenesischeckList[i].teamName){
                        this.uploadingcheckList.push(this.protogenesischeckList[i].id)
                    }
                }
            }
        },
        batchbtn(){
            this.batchVisible=true;
            this.batch.TimePeriod=[];
            this.batch.person=[];
            this.batch.category=[];
            this.checkList=[];
            this.protogenesischeckList=[];
            this.uploadingcheckList=[];
        },
        //保存api
        TaskAllocationBulkAdd() {
            if(this.uploadingcheckList.length<1){
                this.$message.error('保存失败！未选择团组。');
                return
            }
            var that = this
            var url = "/api/Groups/TaskAllocationBulkAdd";
            this.$axios({
                method: 'post',
                url: url,
                data: {
                    userIds: that.batch.person,
                    permissionTypeIds: that.batch.category,
                    groupIds: that.uploadingcheckList,
                    currUserId: that.userId,
                },
                headers: {
                    Authorization: 'Bearer ' + this.token
                },
            }).then(function (res) {
                if (res.data.code == 200) {
                    that.$message({
                        message: res.data.msg,
                        type: 'success'
                    });
                } else {
                    that.$message.error(res.data.msg);
                }
            })
        },
        //保存
        submitForm(batch) {
            this.$refs[batch].validate((valid) => {
                if (valid) {
                    this.TaskAllocationBulkAdd()
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        TaskAssignmenQuery() {
            var that = this
            var url = "/api/Groups/TaskAssignmenQuery";
            this.$axios({
                method: 'post',
                url: url,
                data: {
                    diId: that.diId,
                    ctId: that.ctId,
                },
                headers: {
                    Authorization: 'Bearer ' + this.token
                },
            }).then(function (res) {
                if (res.data.code == 200) {
                    that.userStr = res.data.data.userStr
                    that.TaskAssignment = res.data.data.taskAssignment
                    that.DelegationInfo = res.data.data.delegationInfo
                    that.fullscreenLoading=false;
                } else {
                    that.userStr = [];
                    that.TaskAssignment = {};
                    that.DelegationInfo = {}
                    that.fullscreenLoading=false;
                }
            })
        },
        btn() {
            var id = 0
            var that = this;
            if (that.TaskAssignment.id != undefined) {
                id = that.TaskAssignment.id;
            }
            var url = "/api/Groups/GetTaskAssignmenOp";
            this.$axios({
                method: 'post',
                url: url,
                data: {
                    diId: that.diId,
                    ctId: that.ctId,
                    uIdStr: that.userStr,
                    isEnable: 1,
                    createUserId: that.userId,
                    remark: ""
                },
                headers: {
                    Authorization: 'Bearer ' + that.token
                },
            }).then(function (res) {
                if (res.data.code == 200) {
                    that.$message({
                        message: '保存成功！',
                        type: 'success'
                    });
                } else {
                    that.$message.error('保存失败！' + res.data.msg);
                }
            })
        },
        diidChange() {
            this.userStr = [];
            this.TaskAssignmenQuery()
            console.log(this.userStr)
        },
        sdIdChange() {
            this.TaskAssignmenQuery()
            console.log(this.userStr)
        },
        check(id) {
            var index = this.userStr.indexOf(id)
            if (index == -1) {
                this.userStr.push(id)
            } else {
                this.userStr = this.userStr.filter((x) => x !== id)
            }
        }
    },
    filters:{
        filter_city(value){
            if(value){
                return value.replaceAll('|','、')
            }
        },
        filter_time(value){
            if(value){
                return value.split(" ")[0]
            }
        }
    },
    mounted() {
        this.token = JSON.parse(localStorage.getItem('userinif')).token;
        this.userId = JSON.parse(localStorage.getItem('userinif')).userInfo.userId
        this.GetTaskAssignmen();
    }
}
</script>
<style>
.communal-list {
    background-color: #fff;
    padding: 10px;
    box-shadow: 0 0 5px #0005;
    border-radius: 10px;
    min-height: 820px;
}

.communal-title {
    display: flex;
    font-size: 17px;
    font-weight: 600;
    color: #555;
    margin-bottom: 15px;
    justify-content: space-between;
    align-items: center;
}

.communal-box {
    display: flex;
}

.communal-box>button {
    margin-left: 10px;
    padding: 8px 20px;
}
.tzinif-info {
    display: flex;
    margin-top: 10px;
}

.tzinif-info-li {
    margin-right: 30px;
}

.tzinif-info-li label {
    color: #606266;
    font-size: 15px;
    font-weight: 600;
}

.tzinif-info-li span {
    color: #606266;
    font-size: 14px;
}
.konzh .el-form-item{
    margin-bottom: 0;
}
.batchbox{
    display: flex;
    justify-content: space-between;
}
.checkbox-box{
    padding: 10px;
    border: 1px solid #DCDFE6 ;
    height: 360px;
    overflow-y: auto;
}
.batch{
    text-align: right;
    margin-bottom: 10px;
}
.group-box{
    display: flex;
    flex-wrap: wrap;
    
}
</style>