import {Component} from '@angular/core';
import {IonicPage, NavController, NavParams} from 'ionic-angular';
import {Response} from '@angular/http';
import {Storage} from '@ionic/storage';
import {OutGoingReportDetailPage} from '../outGoingReportDetail/outGoingReportDetail';
import {AppService,AppGlobal} from "../../../../service/http.service";
import {MyReportPage} from "../../../mine/myReport/myReport";
import {MinePage} from "../../../tabs/mine/mine";

@IonicPage()
@Component({
    selector: 'page-outGoingReportEdit',
    templateUrl: 'outGoingReportEdit.html'
})

export class OutGoingReportEditPage {

    isLeave = false;

    //picture: string = "./assets/imgs/logo.png";
    picture: string;
    //报备详情显示处理
    introduce: string;

    edit_CityList;
    addressid: string = '';

    syn_addressid: string = '';
    //报备
    premanager = {};

    //个人报备
    userpre = {
        id: "",
        managerId: "",  //报备id
        isorFromsh: 0,   //默认不离沪
        leaveTime: "",   //离沪时间
        backTime: "",    //回沪时间
        userpreDesc: "",   //离沪说明
        outaddressids: "",  //个人报备选择的地点地址：保存id值
        userId:'',   //协助报备
        userName:''
    };
    //报备截至日期
    temp_endTime;
    //临时离沪信息
    temp_userpre = {};

    person;   //协助报备人
    //离沪时间差
    dategap: any;
    //离沪地点显示
    locations: any;
    //详细说明展示
    isCover: boolean = false;

    constructor(public navCtrl: NavController,
                public navParams: NavParams,
                public appService: AppService,
                public storage: Storage) {
        //当前页面----个人报备1页面

        this.gettemp_userprePre();
    }

    ngOnInit(): void {
        //报备列表页面  到  个人报备1页面
        this.storage.get("premanager").then((value) => {
            if (value != null && value != '') {
                this.premanager = value;
                //加载报备的图片
                this.picture = AppGlobal.picture + this.premanager["uploadPic"];
                //加载报备详细说明
                this.subIntroduce(this.premanager["managerDesc"]);
                this.userpre.managerId = this.premanager["id"]; //1.保存-报备id
                this.temp_endTime = this.premanager["endTime"];  //报备截止时间

                let data = {
                    premanagerId: value.id,
                    userId:''
                };
                if(this.navParams.get('userid')){
                    data.userId = this.navParams.get('userid');
                }else if(this.navParams.get('premanager')){
                    data.userId = null;
                }
                    //编辑初始化：查询
                    this.appService.ObserverHttpPost("/wisdomgroup/modules/userpre/getUserpre", data)
                        .subscribe((res: Response) => {
                            if(res){
                                let result = res.json();
                                this.userpre.id = result["id"];  //保存-id
                                //离沪勾选
                                if (result.isorFromsh == 1) { //离沪
                                    this.userpre.isorFromsh = 1;
                                    this.isLeave = true;

                                    this.edit_CityList = result.areaList;
                                    if (this.edit_CityList != null && this.edit_CityList.length > 0) {
                                        this.addressid = '';
                                        this.locations = '';
                                        for (let index = 0; index < this.edit_CityList.length; index++) {
                                            const element = this.edit_CityList[index];
                                            this.addressid += element["id"] + ",";
                                            this.locations += element["areaName"] + ",";
                                        }
                                        this.addressid = this.addressid.substring(0, this.addressid.lastIndexOf(","));
                                        this.locations = this.locations.substring(0, this.locations.lastIndexOf(","));  //回显地点
                                        this.userpre.outaddressids = this.addressid;  //保存-离沪地点
                                    }
                                    this.userpre.leaveTime = result["formshTime"]; //保存-离沪时间
                                    this.userpre.backTime = result["comeshTime"];  //保存-回沪时间
                                    if (result.userpreDesc != '' || typeof(result.userpreDesc) != 'undefined') {
                                        this.userpre.userpreDesc = result["userpreDesc"];  //保存-离沪说明
                                    }
                                    //页面显示 时间差
                                    this.dategap = this.userpre.leaveTime + "~" + this.userpre.backTime;  //回显时间差
                                }
                            }
                            }, error => {
                            }
                        );
                // }
            }
        });
        this.storage.get("person").then((value)=>{
            if (value != null && value != ''){
                this.person = value;
            }
        });
        //此操作只从报备列表页面到此页面，仅执行一次（不然每次都初始化了）
        this.storage.remove("premanager");
        this.gettemp_userprePre();
        this.addRecodings();
    }

    //增加阅读记录
    addRecodings(){
        this.appService.ObserverHttpGet("/wisdomgroup/modules/activity/addRecodings", null)
            .subscribe((res: Response) => {

                }, error => {
                }
            );
    }

    gettemp_userprePre() {

        //从个人报备2页面  到 个人报备1页面
        this.storage.get("temp_userpre").then((value) => {
            if (value != null && value != '') {
                this.isLeave = true;
                this.userpre.isorFromsh = 1;
                //temp_userpre 保存的是个人报备2 页面中选择的值
                this.temp_userpre = value;
                this.userpre.leaveTime = this.temp_userpre["leaveDate"];
                this.userpre.backTime = this.temp_userpre["backDate"];
                if (value.managerDesc != '' || typeof(value.managerDesc) != 'undefined') {
                    this.userpre.userpreDesc = this.temp_userpre["managerDesc"];
                }
                this.userpre.outaddressids = this.temp_userpre["outaddressids"];
                this.userpre.managerId = this.temp_userpre["managerId"];

                //编辑  （存在个人报备id）
                if (this.temp_userpre["id"] != null && this.temp_userpre["id"] != '') {
                    this.userpre.id = this.temp_userpre["id"];
                }
                //页面显示 时间差
                this.dategap = this.temp_userpre["leaveDate"].substring(0, 10) + "~" + this.temp_userpre["backDate"].substring(0, 10);

                this.locations = this.temp_userpre["areaName"];
                this.temp_endTime = this.temp_userpre["entTime"];

                this.picture = AppGlobal.picture + this.temp_userpre["premanagerImg"];
                this.premanager["managerDesc"] = this.temp_userpre["premanagerIntroduce"];
                this.subIntroduce(this.temp_userpre["premanagerIntroduce"]);

            }
        });

    }

    //具体介绍
    hidden() {
        this.isCover = false;
    }

    show() {
        this.isCover = true;
    }

    //报备详情限定一行17个字符串，两行57个字符串，多余以省略号代替
    subIntroduce(str: string) {
        if (!str) this.introduce = '';
        if (str.length <= 17) this.introduce = str;
        if (str.length > 17 && str.length <= 25) this.introduce = str.substr(0, 17) + "...";
        if (str.length > 25 && str.length <= 42) this.introduce = str.substr(0, 25) + "...";
        if (str.length > 42) this.introduce = str.substr(0, 42) + "...";
    }

    //选择是否离沪
    chooseLeave(status) {
        if (status == 1) {  //不离沪
            this.isLeave = false;
            this.userpre.isorFromsh = 0;

            this.userpre.leaveTime = "";
            this.userpre.backTime = "";
            this.userpre.userpreDesc = "";
            this.userpre.outaddressids = "";

        } else if (status == 0) {
            this.isLeave = true;
            this.userpre.isorFromsh = 1;
        }
    }

    // 跳转到报备详情页面页面
    editReport() {
        this.storage.remove("city");
        this.navCtrl.push("OutGoingReportDetailPage", {
            premanager: this.premanager,
            doPremanager:this.navParams.get('premanager'),
            userId:this.navParams.get('userid')
        });
    }

    //提交报备
    savePremanager() {
        if (this.userpre.isorFromsh == 1) {
            //判断离沪地点是否选择
            if (this.userpre.outaddressids == null || this.userpre.outaddressids == '') {
                this.appService.alert("请填写离沪详情信息！");
                return false;
            }

            if (this.userpre.userpreDesc != null && this.userpre.userpreDesc != '') {
                //离沪乱码处理
                let temp_userpreDesc = encodeURIComponent(this.userpre["userpreDesc"]);
                this.userpre.userpreDesc = temp_userpreDesc;
            }
        }

        if(this.person){
            this.userpre.userId = this.person.id;
            this.userpre.userName = this.person.name;
        }

        //判断报备截止日期
        let signflag = Date.parse(this.temp_endTime.toString()) > Date.parse(new Date().toString());

        if (!signflag) {
            this.appService.alert('超过报备截至时间！');
            return false;
        }

            this.appService.ObserverHttpPost("/wisdomgroup/modules/userpre/create", this.userpre)
                .subscribe((res: Response) => {
                        let resultback = res.json();
                        if (resultback.code == '200') {

                            if( this.person ){
                                const index = this.navCtrl.getActive().index;
                                this.navCtrl.remove(3, index);
                                this.navCtrl.pop();
                            }else{
                                const index = this.navCtrl.getActive().index;
                                this.navCtrl.remove(0, index);
                                this.navCtrl.setRoot(MinePage);
                                this.navCtrl.parent.select(3);
                                this.navCtrl.push("MyReportPage");
                            }
                            this.storage.remove("premanager");
                            this.storage.remove("person");
                            this.storage.remove("temp_userpre");
                            this.storage.remove("managerId");
                            this.storage.remove("city");
                            this.storage.remove("cityList");
                        } else {
                            //失败
                            this.appService.popToastView(resultback.msg, 'middle', 1000);
                        }
                    }, error => {
                    }
                );
    }

    //修改报备
    editPremanager() {
        if (this.userpre.isorFromsh == 1) {
            //判断离沪地点是否选择
            if (this.userpre.outaddressids == null || this.userpre.outaddressids == '') {
                this.appService.alert("请填写离沪详情信息！");
                return false;
            }

            if (this.userpre.userpreDesc != null && this.userpre.userpreDesc != '') {
                //离沪乱码处理
                let temp_userpreDesc = encodeURIComponent(this.userpre["userpreDesc"]);
                this.userpre.userpreDesc = temp_userpreDesc;
            }
        }
        if(this.person){
            this.userpre.userId = this.person.id;
            this.userpre.userName = this.person.name;
        }

        this.storage.get("cityList").then((value) => {
            if (value != null && value != '') { //离沪
                this.addressid = '';
                for (let index = 0; index < value.length; index++) {
                    const element = value[index];
                    this.addressid += element["id"] + ",";
                }
                this.addressid = this.addressid.substring(0, this.addressid.lastIndexOf(","));
                this.userpre.outaddressids = this.addressid;
            }  //编辑或者是选择不离沪
            this.savePremanager_sysn(this.userpre, result => {
                let resultback = result;
                if (resultback.code == '200') {
                    //this.appService.popToastView(resultback.msg,'middle',1000);
                    if( this.person ){
                        const index = this.navCtrl.getActive().index;
                        this.navCtrl.remove(3, index);
                        this.navCtrl.pop();
                    }else{
                        // //清空 插入
                        const index = this.navCtrl.getActive().index;
                        this.navCtrl.remove(0, index);
                        this.navCtrl.setRoot(MinePage);
                        this.navCtrl.parent.select(3);
                        this.navCtrl.push("MyReportPage");
                    }
                } else {
                    //失败
                    this.appService.popToastView(resultback.msg, 'middle', 1000);
                }
            });

        });
    }

    //防止异步
    savePremanager_sysn(userprev, callback?): any {
        this.appService.ObserverHttpPost("/wisdomgroup/modules/userpre/create", userprev)
            .toPromise()
            .then(res => {

                this.storage.remove("premanager");
                this.storage.remove("temp_userpre");
                this.storage.remove("managerId");
                this.storage.remove("city");
                this.storage.remove("cityList");
                let data = res.json();
                callback(data == null ? "[]" : data);
            })
            .catch(error => {
            });
    }
}
