<template>
    <div class="info">
        <el-form :model="formData" :rules="rules" ref="formData" label-width="100px" class="custom-form">
            <el-row>
                <el-col :span="10">
                    <el-form-item label="检查单位" prop="enforce_obj_name">
                        <el-select v-model="formData.enforce_obj_name" placeholder="选择被检查单位"
                                   @focus="showChooseResource=true"></el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="10">
                    <el-form-item label="任务编号" prop="job_no">
                        <el-input v-model="formData.job_no" :disabled="true"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="10">
                    <el-form-item label="单位名称">
                        <el-input v-model="formData.enforce_obj_name" :disabled="true"/>
                    </el-form-item>
                </el-col>
                <el-col :span="10">
                    <el-form-item label="单位地址" prop="enforce_obj_address">
                        <el-input v-model="formData.enforce_obj_address" suffix-icon="el-icon-place"
                                  @focus="showMap=true"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>


            <el-row>
                <el-col :span="10">
                    <el-form-item label="单位类型" prop="enforce_obj_type">
                        <!--                        <el-input v-model="formData.enforce_obj_type" :disabled="true"/>-->
                        <el-select v-model="formData.enforce_obj_type" disabled placeholder="">
                            <el-option
                                v-for="item in this.unitSize"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="10">
                    <el-form-item label="场所类型" prop="place_type">
                        <!--                        <el-input v-model="formData.place_type" :disabled="true"/>-->
                        <el-select v-model="formData.place_type" disabled placeholder="">
                            <el-option
                                v-for="item in placeType"
                                :key="item.code"
                                :label="item.name"
                                :value="item.code">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="10">
                    <el-form-item label="单位法人" prop="legal_person">
                        <el-input v-model="formData.legal_person" :disabled="true"/>
                    </el-form-item>
                </el-col>
                <el-col :span="10">
                    <el-form-item label="联系电话" prop="legal_person_phone">
                        <el-input v-model="formData.legal_person_phone" :disabled="true"/>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="20">
                    <el-form-item label="任务名称" prop="job_name">
                        <el-input
                            v-model="formData.job_name"
                            maxlength="50"
                            show-word-limit
                            placeholder="请输入"
                        >
                        </el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="20">
                    <el-form-item label="任务概要" prop="job_desc">
                        <el-input
                            v-model="formData.job_desc"
                            type="textarea"
                            show-word-limit
                            :rows="5"
                            maxlength="300"
                            placeholder="请输入"
                        >
                        </el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-row v-if="editObject&&initShow">
                    <el-col :span="10">
                        <el-form-item label="审批单位" prop="enforce_obj_name">
                            <el-input v-model="formData.enforce_org_name" placeholder="检查单位" @focus="initShow=false"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-else>
                    <el-col :span="10">
                        <el-form-item label="执法机构" prop="enforce_org_id">
                            <el-cascader
                                class="custom-cascader"
                                v-model="enforce_org_id"
                                :props="orgProps"
                                :options="orgOptions"
                                :show-all-levels="false"
                                ref="cascaderAddr"
                                @change="orgChanged">
                            </el-cascader>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-row>
            <el-row>
                <el-col :span="20">
                    <el-form-item label="检查期限" prop="last_enforce_date">
                        <el-date-picker
                            v-model="formData.last_enforce_date"
                            type="date"
                            :picker-options="pickerOptions0"
                            value-format="yyyy-MM-dd"
                            placeholder="选择日期">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="20">
                    <el-form-item label="检查成员" prop="executor_ids">
                        <el-select v-model="formData.executor_ids" multiple clearable placeholder="检查成员"
                                   @change="selectExecutors">
                            <el-option v-for="item in orgUsers" :key="item.id" :value="item.uid"
                                       :label="item.name"/>
                        </el-select>
                    </el-form-item>
                </el-col>
<!--                <el-col :span="10">-->
<!--                    <el-form-item label="审批领导" prop="approve_user_id">-->
<!--                        <el-select v-model="formData.approve_user_id" clearable placeholder="审批人员"-->
<!--                                   @change="selectApprove($event)">-->
<!--                            <el-option v-for="item in orgUsers" :key="item.userId" :value="item.userId"-->
<!--                                       :label="item.userName"/>-->
<!--                        </el-select>-->
<!--                    </el-form-item>-->
<!--                </el-col>-->
            </el-row>
            <el-row>
                <el-col :span="12" :offset="12">
                    <el-form-item>
                        <el-button @click="cancel()">取消</el-button>
                        <el-button type="primary" @click="saveOrEditJob('formData')">确定</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <el-dialog title="选择单位" append-to-body :visible.sync="showChooseResource" class="custom-dialog">
            <choose-resource @changeResource="changeResource"></choose-resource>
        </el-dialog>
        <el-dialog title="单位地址" :visible.sync="showMap" append-to-body>
            <place-map v-if="showMap" ref="map" @changePlace="handlePlace" :address.sync="formData.enforce_obj_address"
                       @hidePlace="showMap=false"></place-map>
        </el-dialog>
    </div>
</template>

<script>
    import PlaceMap from '@/component/PlaceMap.vue'
    import ChooseTemplate from '@/component/ChooseTemplate.vue'
    import ChooseResource from '@/component/ChooseResource.vue'
    import {resourceMixin} from '@/mixin/resource'
    import {updateJobBasic, saveJob} from '@/api/job'
    import {getUserByOrg} from '@/api/base'
    import {getPlaceTypes} from "@/api/resource";
    import { orgMixin } from '@/mixin/org';

    export default {
        components: {
            // eslint-disable-next-line vue/no-unused-components
            PlaceMap,
            // eslint-disable-next-line vue/no-unused-components
            ChooseTemplate,
            ChooseResource
        },
        mixins: [resourceMixin, orgMixin],
        data() {
            let selectUsersValid = (rule, value, callback) => {
                let tmp = this.formData.executors;
                if (!tmp || tmp.length < 1) {
                    callback(new Error('请选择执法人员'))
                } else {
                    callback()
                }
            }
            return {
                pickerOptions0: {
                    disabledDate(time) {
                        return time.getTime() < Date.now() - 8.64e7;
                    }
                },
                params: {
                    page: 1,
                    limit: 5,
                    data: {}
                },
                orgUsers: [],
                selectOrg: [],
                enforce_org_id: '',
                initShow: true,
                selectUsers: [],
                formData: {
                    id: '',
                    enforce_org: {
                        enforce_org_id: '',
                        enforce_org_name: ''
                    },
                    enforce_org_id: '',
                    enforce_org_name: '',
                    enforce_obj_id: '',
                    enforce_obj_name: '',
                    enforce_obj_address: "",
                    job_no: "",
                    approve_user_id: '',//审批人ID
                    approve_user_name: '',//审批人名称
                    job_desc: '',//概要描述
                    job_type: '',
                    job_name: '',
                    last_enforce_date: '',
                    executors: [],
                    executor_ids: '',
                    executor_names: ''
                },
                initUser: false,
                rules: {
                    enforce_obj_name: [
                        {required: true, message: '请选择单位名称', trigger: 'change'},
                    ],
                    enforce_org_id: [
                        {required: true, message: '请选择执法单位', trigger: 'change'},
                    ],
                    job_desc: [
                        {required: true, message: '请输入任务概要', trigger: 'change'}
                    ],
                    job_name: [
                        {required: true, message: '请输入任务名称', trigger: 'change'}
                    ],
                    approve_user_id: [
                        {required: true, message: '请选择审批人', trigger: 'change'},
                    ],
                    executor_ids: [
                        {required: true, validator: selectUsersValid, message: '请选择执法人员', trigger: 'change'}
                    ],
                    last_enforce_date: [
                        {required: true, message: '请选择检查期限', trigger: 'change'},
                    ]
                },
                placeType:[],
                showMap: false,//地图组件
                showChooseResource: false,//选择单位组件
                approveUsers: [] //审核人员列表
            }
        },
        computed: {},
        mounted: function () {
            this.getPlaceTypesAll();
            this.setDefaultValue();
            this.loadOrgTree();
        },

        props: {
            jobType: {
                type: String
            },
            editObject: {
                type: Object
            }
        },
        methods: {
            async getPlaceTypesAll() {
                const list = await getPlaceTypes();
                if (list && list.length > 0) {
                    this.placeType = list;
                }
            },
            clearOrg() {
                this.initShow = false;
                this.formData.enforce_org_id = '';
                this.formData.approve_user_name = '';
                this.formData.approve_user_id = '';
            },
            orgChanged(data) {
                let arr = this.$refs['cascaderAddr'].getCheckedNodes()[0].pathLabels;
                let thsAreaCode = arr[arr.length-1];
                this.formData.enforce_org.enforce_org_name = thsAreaCode;
                this.formData.enforce_org_name = thsAreaCode;
                this.formData.enforce_org.enforce_org_id = data.length > 0 ? data[data.length - 1] : null
                this.formData.enforce_org_id = data.length > 0 ? data[data.length - 1] : null
                this.orgUsers = []
                this.selectUsers=[]
                this.formData.approve_user_id='';
                this.formData.executor_ids = '';
                this.formData.executor_names = '';
                this.getOrgUsers();
            },
            getOrgUsers() {
                if (this.formData.enforce_org_id) {

                    getUserByOrg(1, 10000, this.formData.enforce_org_id).then(res => {
                        if (res && res.data) {
                            this.orgUsers = res.data;
                            this.initUser = true;
                        }
                    })
                } else {
                    this.$message.warning('请先选择执法机构')
                }
            },
            cancel() {
                let keys = Object.keys(this.formData);
                keys.forEach(k => {
                    this.formData[k] = '';
                })
                this.$emit("changeDialogFormVisible")
            },
            //设置初始值
            setDefaultValue: function () {
                // console.log(this.unitSize);
                // this.$message.warning('setJobType')
                this.formData['job_type'] = this.jobType
                if (this.editObject) {
                    // console.log(this.editObject)
                    //基本信息
                    let keys = Object.keys(this.editObject);
                    keys.forEach(k => {
                        if (k != 'enforce_org' && Object.prototype.hasOwnProperty.call(this.formData, k)) {
                            this.formData[k] = this.editObject[k];
                        }
                    })
                    //单位信息
                    let enforce_obj = this.editObject.enforce_obj;
                    if (enforce_obj) {
                        this.formData.enforce_obj_type = enforce_obj.enforce_obj_type;
                        this.formData.place_type = enforce_obj.place_type;
                        this.formData.legal_person = enforce_obj.legal_person;
                        this.formData.legal_person_phone = enforce_obj.legal_person_phone;
                        let objKeys = Object.keys(enforce_obj);
                        objKeys.forEach(k => {
                            if (k != 'id' && k != 'enforce_org_id' && k != 'enforce_org_name' &&
                                k != 'enforce_org' && Object.prototype.hasOwnProperty.call(this.formData,
                                k)) {
                                this.formData[k] = enforce_obj[k];
                            }
                        })
                    }
                    //加载审核人
                    this.getOrgUsers();
                }
            },
            changeResource(data) {
                if (data) {
                    this.formData.enforce_obj_name = data.enforce_obj_name
                    this.formData.enforce_obj_id = data.id
                    this.formData.enforce_obj_type = data.enforce_obj_type;
                    this.formData.place_type = data.place_type;
                    this.formData.legal_person = data.legal_person;
                    this.formData.legal_person_phone = data.legal_person_phone;
                    this.formData.enforce_obj_address = data.enforce_obj_address;
                }
                this.showChooseResource = false
            },
            handlePlace(data) {
                if (data) {
                    this.formData.enforce_obj_address = data.address
                    this.formData.longitude = data.lon
                    this.formData.latitude = data.lat
                    this.formData.coor = `${data.lon},${data.lat}`
                }
                this.showMap = false
            },
            //选择了审核人员
            selectApprove(userId) {
                this.formData.approve_user_id = userId;
                this.orgUsers.forEach(item => {
                    if (item.userId == userId) {
                        this.formData.approve_user_name = item.userName;
                        // console.log(this.formData)
                    }
                })
            },
            //选择了检查人员
            selectExecutors() {
                let userList = [], userName = [];
                let res;
                this.formData.executor_ids.map(id => {
                    res = this.orgUsers.filter(item => id == item.uid);
                    if (res.length > 0) {
                        userList.push({
                            user_id: res[0].uid,
                            user_name: res[0].name,
                            phone: res[0].phone_num,
                        });
                        userName.push(res[0].name);
                    }
                });
                this.formData.executor_names = userName.join(",");
                this.formData.executors = userList;
            },

            initSelectUsers(userIdList) {
                let userList = [];
                this.orgUsers.forEach(item => {
                    userIdList.forEach(userId => {
                        if (item['uid'] == userId) {
                            let user = {};
                            user['user_id'] = item.uid;
                            user['user_name'] = item.name;
                            user['phone'] = item.phone_num;
                            userList.push(user);
                        }
                    });
                });
                this.selectUsers = userList;
            },
            //保存
            saveOrEditJob(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.formData.executor_ids = this.formData.executor_ids.join(',');
                        //id不为空更新
                        if (this.formData.id) {
                            //更新
                            updateJobBasic(this.formData.id, this.formData).then(res => {
                                this.$emit("changeDialogFormVisible")
                                this.$emit("resetForm")
                            })
                        } else {
                            //新增
                            this.formData.job_source = "CREATED";
                            saveJob(this.formData).then(res => {
                                let keys = Object.keys(this.formData);
                                keys.forEach(k => {
                                    this.formData[k] = '';
                                })
                                this.$emit("changeDialogFormVisible")
                                this.$emit("resetForm")
                            })
                        }
                    } else {
                        return false;
                    }
                });
            }
        },
        watch: {
            initUser: {
                // immediate: true, //初始化时让handler调用一下
                handler(newValue, oldValue) {
                    if(this.editObject){
                        this.formData.executor_ids = this.editObject.executor_ids.split(",");
                        this.selectExecutors();
                    }
                }
            },
        }
    }
</script>

<style lang="scss" scoped>
.info {
    display: flex;
    flex-direction: column;
    padding: 16px 16px 0;
    background-color: #FFFFFF;
    border-radius: 10px;
}
</style>