<template>
    <div style="position:relative;">
        <el-form v-if="showType == 'adjust' || showType == 'adjust1'" ref="form" label-position="left" :model="formData"
            label-width="150px" style="margin-left: 3%; margin-top: 10px;">
            <el-row>
                <el-col :span="24">
                    <el-form-item label="选择接收人员">
                        <el-cascader class="u-item-width-normal" size="small" ref="myCascader"
                            v-model="cascaderAgencyId" @change="handleChangeAgency" :options="orgOptions"
                            :props="orgOptionProps" :show-all-levels="false" clearable></el-cascader>
                        <el-select v-model.trim="formData.receiverIds" placeholder="请选择" size="small" clearable
                            class="cell-width-1" collapse-tags style="margin-left: 10px;" @change="changeTag">
                            <el-option v-for="item in workPersonnelList" :key="item.value" :label="item.name"
                                :value="item.staffId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item :label="`已选（${selfTag.length}）人`">
                        <div>
                            <el-tag v-for="tag in selfTag" :key="tag.staffId" closable @close="removeTag(tag)"
                                style="margin-right: 10px;">
                                <span> {{ tag.name }}</span>
                            </el-tag>
                        </div>

                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <el-table v-if="showType == 'info'" :data="tableData" border class="m-table-item" style="width: 80%;">
            <el-table-column label="序号" fixed="left" type="index" align="center" width="80" />
            <el-table-column prop="userName" align="center" :show-overflow-tooltip="true" label="第一接收人">
            </el-table-column>
            <el-table-column prop="renwu" align="center" :show-overflow-tooltip="true" label="转派给">
            </el-table-column>
        </el-table>
        <el-form v-if="showType == 'edit'" ref="formData " label-position="left" :model="formData" label-width="150px"
            style="margin-left: 3%; margin-top: 10px;">
            <el-row>
                <!-- <el-form-item prop="taskTitle" label="任务主题">
                    <el-input v-model="formData.taskTitle" placeholder="请输入内容" clearable class="cell-width-1"></el-input>
                </el-form-item> -->
                <el-form-item label="任务要求" prop="taskIntroduction" style="display: block">
                    <el-input class="cell-width-2" type="textarea" maxlength="500" show-word-limit :rows="5"
                        placeholder="请输入事件内容，不超过500字" v-model.trim="formData.taskIntroduction"></el-input>
                </el-form-item>

            </el-row>
        </el-form>
        <span v-if="showType == 'adjust' || showType == 'edit' || showType == 'adjust1'" slot="footer" class="dialog-footer"
            style="margin-left: 40%;">
            <el-button @click="handleCancel">取 消</el-button>
            <el-button type="primary" @click="handleConfirm">确 定</el-button>
        </span>
    </div>
</template>

<script>
import options from "@/utils/luckysheetConfig.js";
import { requestPost, requestGet } from "@/js/dai/request";
export default {
    data() {
        return {
            tableData: [],
            formData: {
                taskTitle: '',//任务主题
                taskType: '1',//任务类型
                taskPeriod: 'once',//任务周期
                completeLimitDay: '',//完成时限 一次性时传日期，周期性时传天数
                completeLimitHour: '',//完成时限 周期或者一次性都传小时
                receiverIds: '',//分发人员
                moduleUrl: '',//上传模板
                taskIntroduction: '',//任务要求
                wordBookId: ''//工作簿id
            },
            workPersonnelList: [],
            cascaderAgencyId: "",
            orgOptions: [],
            orgOptionProps: {
                multiple: false,
                value: 'agencyId',
                label: 'agencyName',
                children: 'subAgencyList',
                checkStrictly: true
            },
            selfTag: [],
            sarr: [],
            agencyId: '',
            agencylevel: '',
            showType: "",
            pageNo: 1,
            pageSize: 10
        };
    },
    created() { },
    methods: {
        handleConfirm() {
            let userIdList = this.selfTag.map(item => {
                return item.staffId
            })
            if (this.showType == "adjust") {
                let parms = {
                    userIdList: userIdList,
                    taskId: this.taskId,
                }
                this.updateState()
                requestPost('/actual/base/communityOneTablePeriodPublish/changeAssignWorker', parms).then(res => {
                    if (res.code === 0) {
                        this.$message.success('转派成功')
                        return this.$emit('handelPersonel')
                    } else {
                        this.$message.error(res.internalMsg)
                    }
                });
            } else if (this.showType == "adjust1") {
                let parms = {
                    userId: userIdList.toString(),
                    id: this.taskId,
                    reassignedReason: ""
                }
                this.updateState()
                requestPost('/actual/base/communityOneTablePeriodPublish/reAssignWorker', parms).then(res => {
                    if (res.code === 0) {
                        this.$message.success('转派成功')
                        return this.$emit('handelPersonel')
                    } else {
                        this.$message.error(res.internalMsg)
                    }
                });
            }
            else {
                let parms = {
                    userIdList: userIdList,
                    id: this.taskId,
                    taskIntroduction: this.formData.taskIntroduction

                }
                requestPost('/actual/base/communityOneTablePublish/update', parms).then(res => {
                    return this.$emit('handelPersonel')
                });
            }

        },
        async updateState() {
            const url = '/actual/base/communityOneTablePeriodPublish/update'
            console.log(this.formDatas);
            const { id, taskId, taskTitle, taskPeriod, taskType, taskIntroduction } = this.formDatas;
            const parm = { id, taskId, taskTitle, taskPeriod, taskType, taskIntroduction }
            parm.taskState = 'reassigned';
            const { code, msg } = await requestPost(url, parm)
            if (code === 0) {
                // this.$message.success('转派成功')
            } else {
                console.log(msg);
            }
        },

        getPeriodPublish() {
            let parms = {
                pageNo: this.pageNo,
                pageSize: this.pageSize,
                taskId: this.taskId,
                taskNum: 0
            }
            requestGet('/actual/base/communityOneTablePeriodPublish/page', parms).then(res => {
                this.tableData = res.data.list
            });
        },
        getLastItem(list, vals, key) {
            let LIST = list || [];
            for (let item of LIST) {
                for (let i of vals) {
                    if (item[key] === i) {
                        this.sarr.push(item);
                    } else {
                        this.getLastItem(item.subAgencyList, vals, key);
                    }
                }
            }
        },
        removeTag(val) {
            this.selfTag = this.selfTag.filter(item => item.staffId != val.staffId);
        },
        changeTag(val) {
            let obj = this.workPersonnelList.find(item => item.staffId === val);
            obj.agencyId = this.agencyId
            if (obj) {
                let exists = this.selfTag.some(tag => tag.agencyId === obj.agencyId);
                this.selfTag.push(obj);

            } else {
                console.error('未找到对应的人员信息');
            }
        },
        getStafflist() {
            let parms = {
                orgId: this.agencyId,
                orgType: 'agency',
                pageNo: 1,
                pageSize: 100,
            };
            this.$http.post("data/aggregator/org/stafflist", parms).then((resp) => {
                this.workPersonnelList = resp.data.data.staffList;
            });
        },
        async handleChangeAgency(val) {
            this.sarr = []
            this.getLastItem(
                this.orgOptions,
                val,
                "agencyId"
            );
            this.agencylevel = this.sarr[this.sarr.length - 1].level;
            this.agencyId = this.sarr[this.sarr.length - 1].agencyId;
            this.formData.receiverIds = ''
            this.getStafflist()
        },
        getOrgTreeList() {
            this.$http
                .post('/gov/org/customeragency/agencygridtree', {})
                .then(({ data: res }) => {
                    if (res.code !== 0) {
                        return this.$message.error(res.msg)
                    } else {
                        this.orgOptions = []
                        this.orgOptions.push(res.data)
                    }
                })
                .catch(() => {
                    return this.$message.error('网络错误')
                })
        },

        handleCancel() {
            this.$emit('handelPersonel')
        },

    },
    mounted() {
        console.log(this.showType, this.taskId, "sdlfkl;sdf");
        this.getOrgTreeList()
        this.getPeriodPublish()
    },
    props: {
        taskId: {
            type: String,
            default: ''
        },
        showType: {
            type: String,
            default: ''
        },
        formDatas: {
            type: Object,
            default: () => { }
        }

    },
    components: {},
    computed: {

    },
    watch: {},
}
</script>

<style lang='scss' scoped>
.dialog-footer {}
</style>