<template>
    <div class="page">
        <headNav title="新增乡镇检查"></headNav>

        <div class="content">
            <van-cell-group>
                <van-cell required title="检查单位" is-link :value="orgName" @click="chooseCompany"/>
                <van-field required v-model="taskName" label="任务名称" input-align="right" placeholder="请输入(50字符以内)" />
                <van-cell class="noLine" required title="任务内容" />
                <div class="desc">
                    <van-field
                        v-model="taskDesc"
                        rows="4"
                        autosize
                        type="textarea"
                        maxlength="300"
                        placeholder="请输入"
                        show-word-limit
                    />
                </div>
                <van-cell required title="协查人员" is-link :value="userName?userName:'请选择'" @click="showPicker = true" />
            </van-cell-group>
            <div class="mg">
                <van-button round block type="info" @click="onSubmit">保存</van-button>
            </div>
        </div>

        <van-popup v-model="showPicker" position="bottom">
            <van-picker
                show-toolbar
                :columns="userList"
                value-key="title"
                @confirm="onConfirm"
                @cancel="showPicker = false"
            />
        </van-popup>

        <v-mask :showOverLay="showOverLay" tipMsg="保存数据中..."></v-mask>
    </div>
</template>

<script>
import headNav from "@/components/headNav.vue"
import mask_overLay from "@/components/overLay_xy.vue";
import { post, get } from '@/utils/http.js';
import { getInfo } from '@/utils/auth';
import BUS from '@/bus';
import { isEmpty } from '@/utils/tool';
import { Notify } from 'vant';

export default {
    components: {
        headNav,
        "v-mask": mask_overLay,
    },
    inject: ['reload'],
	beforeRouteEnter: (to, from, next) => {
		if (from.name === 'town') {
			next(vm => {
				vm.resetForm();
			});
		} else {
			next();
		}
	},
    data () {
        return {
            showOverLay: false,
            orgId: null,
            orgName: '',
            taskName: '',
            taskDesc: '',
            userId: null,
            userName: '',
            userList: [],
            showPicker: false,
        }
    },
    computed: {
        userInfo() {
            return getInfo();
        },
        userOrgId() {
            return this.userInfo && this.userInfo.enforce_org_id || '';
        },
        userOrgName() {
            return this.userInfo && this.userInfo.enforce_org_name || '';
        },
        currentUserId() {
            return this.userInfo && this.userInfo.uid || '';
        }
    },
    mounted () {
        if (this.userOrgId) {
            this.loadUsers()
        }
    },
    methods: {
        resetForm() {
            this.orgId = null;
            this.orgName = null;
            this.taskName = null;
            this.taskDesc = null;
            this.userId = null;
            this.userName = null;
        },
        loadUsers() {
            get('/v2/api/sys_user', {
                    page: 1,
                    size: 10000,
                    sort: 'create_time desc',
                    query: `enforce_org_id==${this.userOrgId}`
            }).then(res => {
                if (res && res.data) {
                    let list = res.data || [];
                    if (this.currentUserId) {
                        list = list.filter(item => this.currentUserId != item.uid);
                    }
                    list.map(item => {
                        item.title = `${item.name}[${item.account}]`;
                    })
                    this.userList = list;
                }
            });
        },
        onConfirm(v) {
            this.userId = v.uid;
            this.userName = v.name;
            this.showPicker = false;
        },
        chooseCompany() {
            this.$router.push('/chooseCompany');
            const vm = this;
            BUS.$on('choose', function(res) {
                if (res) {
                    vm.orgId = res.id;
                    vm.orgName = res.name;
                }
            });
        },
        onSubmit() {
            if (isEmpty(this.orgId)) {
                Notify({ type: 'warning', message: '请选择检查单位' });
                return;
            }
            if (isEmpty(this.taskName)) {
                Notify({ type: 'warning', message: '请输入任务名称' });
                return;
            }
            if (this.taskName.length > 50) {
                Notify({ type: 'warning', message: '任务名称不能超过50字符' });
                return;
            }
            if (isEmpty(this.taskDesc)) {
                Notify({ type: 'warning', message: '请输入任务内容' });
                return;
            }
            if (this.taskDesc.length > 300) {
                Notify({ type: 'warning', message: '任务内容不能超过300字符' });
                return;
            }
            if (isEmpty(this.userId)) {
                Notify({ type: 'warning', message: '请选择协查人员' });
                return;
            }
            this.showOverLay = true;
            const executor = [this.currentUserId, this.userId];
            const params = {
                job_name: this.taskName,
                job_type: 'TOWNS',
                job_source: 'CREATED',
                job_desc: this.taskDesc,
                enforce_obj_id: this.orgId,
                enforce_obj_name: this.orgName,
                executor_ids: executor.join(','),
                executor_names: `${this.userInfo.name}, ${this.userName}`,
                enforce_org_id: this.userOrgId,
                enforce_org_name: this.userOrgName,
            }
            post('/v2/api/enforce-job', params).then(res => {
                this.showOverLay = false;
                if (res) {
                    this.$toast.success('保存成功');
                    this.$router.replace(`/town/detail/${res.id}`);
                }
                else {
                    this.$toast.fail(res.msg || '保存失败，请重试！')
                }
            }).catch(err => {
                this.showOverLay = false;
            });
        }
    }
}
</script>

<style lang="scss" scoped>
.desc {
    border: 1px solid #f0f0f0;
    border-radius: 6px;
    margin: 0 16px 10px;
}
.noLine {
    border-bottom: none !important;
}
.noLine::after {
    border-bottom: none !important;
}
</style>