1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
package cn.flightfeather.thirdappmodule.activity;
 
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;
 
import com.ping.greendao.gen.DaoSession;
import com.ping.greendao.gen.UserinfoDao;
 
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
 
import cn.carbswang.android.numberpickerview.library.NumberPickerView;
import cn.flightfeather.thirdappmodule.CommonApplication;
import cn.flightfeather.thirdappmodule.R;
import cn.flightfeather.thirdappmodule.bean.entity.City;
import cn.flightfeather.thirdappmodule.bean.entity.District;
import cn.flightfeather.thirdappmodule.bean.entity.Domaincatalog;
import cn.flightfeather.thirdappmodule.bean.entity.Domainitem;
import cn.flightfeather.thirdappmodule.bean.entity.Province;
import cn.flightfeather.thirdappmodule.bean.entity.Task;
import cn.flightfeather.thirdappmodule.bean.entity.Town;
import cn.flightfeather.thirdappmodule.bean.entity.Userinfo;
import cn.flightfeather.thirdappmodule.httpservice.TaskService;
import cn.flightfeather.thirdappmodule.httpservice.UserInfoService;
import cn.flightfeather.thirdappmodule.module.task.NewMonthTaskMapActivity;
import cn.flightfeather.thirdappmodule.util.CommonUtils;
import cn.flightfeather.thirdappmodule.util.Constant;
import cn.flightfeather.thirdappmodule.util.DateFormatter;
import cn.flightfeather.thirdappmodule.util.Domain;
import cn.flightfeather.thirdappmodule.util.UUIDGenerator;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
 
import static cn.flightfeather.thirdappmodule.util.CommonUtils.getDomainItemByCalalogGuid;
import static cn.flightfeather.thirdappmodule.util.DateFormatter.dateFormat;
 
public class NewMonthTaskActivity extends AppCompatActivity implements View.OnClickListener,
        NumberPickerView.OnScrollListener, NumberPickerView.OnValueChangeListener,
        NumberPickerView.OnValueChangeListenerInScrolling {
 
    private static final String TAG = "NewMonthTaskActivity";
    private static final int MODE_ADD = 1;
    private static final int MODE_UPDATE = 2;
 
    private TextView tv_task_name;
    private TextView tv_task_start_time;
    private TextView tv_task_end_time;
    private TextView tv_task_type;
    private TextView tv_task_area;
    private TextView tv_level;
    private TextView tv_task_executors;
    private TextView tv_task_deadline_type;
    private TextView tv_task_level;
 
    private CommonApplication application;
    private Task mCurrentTask = new Task();
    private List<Userinfo> userList = new ArrayList<>();
    private String[] pattens = new String[4];
    private String template = "%s%s%s%s"; //1时间段;2区域;3任务类型;4(固定)任务
    private DaoSession daoSession;
    private int taskTypeChoice = -1;
    private int taskLevelChoice = -1;
    private int taskDeadLineChoice = -1;
    private boolean isLoadedUsers = false;
    private boolean[] mCheckedArray;
    private NumberPickerView provincePicker;
    private NumberPickerView cityPicker;
    private NumberPickerView districtPicker;
    private NumberPickerView townPicker;
    private List<Province> list_province;
    private List<City> list_city;
    private List<District> list_district;
    private List<Town> list_town;
    private String[] provinces;
    private View areaPickerLayout;
    private boolean isShowingTownPicker;
    private List<Domainitem> taskTypeDomainItemList;
    private HashMap<Integer, Domainitem> deadlineTypeDomainItemMap = new HashMap<>();
    private HashMap<Integer, Domainitem> taskLevelDomainItemMap = new HashMap<>();
    private View view_waiting;
    private boolean isFirstShowAreaPicker = true;
    private int mCurrentMode;
    private Calendar cal_s = Calendar.getInstance(), cal_e = Calendar.getInstance();
    private String mOriginalExecutors;
    private CheckBox cb_unfixed_scense;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_month_task);
        initData();
        initUI();
    }
 
    /**
     * 获取若干值域数据,如任务类型,省市区等信息
     */
    private void initData() {
        application = (CommonApplication) getApplication();
        daoSession = application.getDaoSession();
        loadUser(false);
        loadArea();
        initDomainItem();
        Intent intent = getIntent();
        Serializable task = intent.getSerializableExtra(Constant.KEY_INTENT_TOPCLASS_TASK);
        initCurrentTask(task);
    }
 
    /**
     * 初始化值域信息
     */
    private void initDomainItem() {
        taskTypeDomainItemList = getDomainItemByCalalogGuid(daoSession, Domain.DOMAINGUID_TASKTYPE);
        List<Domainitem> list = getDomainItemByCalalogGuid(daoSession, Domain.DOMAINGUID_TASKDEADLINETYPE);
        for (Domainitem item : list) {
            deadlineTypeDomainItemMap.put(Integer.parseInt(item.getValue()), item);
        }
        list = getDomainItemByCalalogGuid(daoSession, Domain.DOMAINGUID_TASKLEVEL);
        for (Domainitem item : list) {
            taskLevelDomainItemMap.put(Integer.parseInt(item.getValue()), item);
        }
    }
 
    /**
     * 初始化月任务信息
     */
    private void initCurrentTask(Serializable task) {
        if (task != null) {
            mCurrentMode = MODE_UPDATE;
            mCurrentTask = (Task) task;
            cal_s.setTime(mCurrentTask.getStarttime());
            cal_e.setTime(mCurrentTask.getEndtime());
            updateMonthDiff(cal_s.get(Calendar.YEAR), cal_s.get(Calendar.MONTH));
            if (mCurrentTask.getExtension1().equals(Domain.DOMAIN_SUITABLE_TOWN)) {
                pattens[1] = mCurrentTask.getCityname()+mCurrentTask.getDistrictname()+mCurrentTask.getTownname();
            } else {
                pattens[1] = mCurrentTask.getCityname()+mCurrentTask.getDistrictname();
            }
            pattens[2] = mCurrentTask.getTypename();
            pattens[3] = "任务";
            mOriginalExecutors = mCurrentTask.getExecutorguids();
        } else {
            mCurrentMode = MODE_ADD;
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.MONTH, 1);
            cal.set(Calendar.DAY_OF_MONTH, 1);
            cal = CommonUtils.findFirstWorkingDay(cal, true);
            cal.set(Calendar.HOUR_OF_DAY, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);
            mCurrentTask.setStarttime(cal.getTime());
            cal.add(Calendar.MONTH, 1);
            cal.add(Calendar.DAY_OF_MONTH, -1);
            cal = CommonUtils.findFirstWorkingDay(cal, false);
            cal.set(Calendar.HOUR_OF_DAY, 23);
            cal.set(Calendar.MINUTE, 59);
            cal.set(Calendar.SECOND, 59);
            mCurrentTask.setEndtime(cal.getTime());
            String name = "%d年%d月";
            pattens[0] = String.format(Locale.CHINA, name, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1);
            pattens[1] = "上海市静安区";
            pattens[2] = "巡查";
            pattens[3] = "任务";
            mCurrentTask.setTguid(UUIDGenerator.generate16ShortUUID());
            mCurrentTask.setName(String.format(template, pattens[0], pattens[1], pattens[2], pattens[3]));
            //不理想
            mCurrentTask.setProvincecode("31");
            mCurrentTask.setProvincename("上海市");
            mCurrentTask.setCitycode("3100");
            mCurrentTask.setCityname("上海市");
            mCurrentTask.setDistrictcode("310106");
            mCurrentTask.setDistrictname("静安区");
            mCurrentTask.setRuningstatus(Domain.TASK_STATUS_WAITING);
            mCurrentTask.setDeadlinetype("定期计划");
            mCurrentTask.setLevelnum(2);
            Domainitem item = taskTypeDomainItemList.get(0);
            mCurrentTask.setTypeno(Byte.valueOf(item.getValue()));
            mCurrentTask.setTypename(item.getText());
        }
    }
 
    private void initUI() {
        findViewById(R.id.ll_task_start_time).setOnClickListener(this);
        findViewById(R.id.ll_task_end_time).setOnClickListener(this);
        findViewById(R.id.ll_task_type).setOnClickListener(this);
        findViewById(R.id.ll_task_area).setOnClickListener(this);
        findViewById(R.id.ll_task_executors).setOnClickListener(this);
        findViewById(R.id.ll_task_deadline_type).setOnClickListener(this);
        findViewById(R.id.ll_task_level).setOnClickListener(this);
        findViewById(R.id.view_empty).setOnClickListener(this);
        findViewById(R.id.tv_submit).setOnClickListener(this);
        findViewById(R.id.tv_save).setOnClickListener(this);
        findViewById(R.id.img_left).setOnClickListener(this);
        findViewById(R.id.img_right).setVisibility(View.GONE);
        findViewById(R.id.spinner_topclass_task).setVisibility(View.GONE);
        cb_unfixed_scense = (CheckBox)findViewById(R.id.cb_unfixed_scense);
        ((TextView) findViewById(R.id.actionbar_title)).setText("新增顶层任务");
        view_waiting = findViewById(R.id.view_waiting);
        tv_level = (TextView) findViewById(R.id.tv_level);
        tv_level.setOnClickListener(this);
        areaPickerLayout = findViewById(R.id.area_picker);
        provincePicker = (NumberPickerView) findViewById(R.id.picker_province);
        cityPicker = (NumberPickerView) findViewById(R.id.picker_city);
        districtPicker = (NumberPickerView) findViewById(R.id.picker_district);
        townPicker = (NumberPickerView) findViewById(R.id.picker_town);
        townPicker.setVisibility(View.GONE);
        provincePicker.setOnScrollListener(this);
        provincePicker.setOnValueChangedListener(this);
        provincePicker.setOnValueChangeListenerInScrolling(this);
        cityPicker.setOnScrollListener(this);
        cityPicker.setOnValueChangedListener(this);
        cityPicker.setOnValueChangeListenerInScrolling(this);
        districtPicker.setOnScrollListener(this);
        districtPicker.setOnValueChangedListener(this);
        districtPicker.setOnValueChangeListenerInScrolling(this);
        townPicker.setOnScrollListener(this);
        townPicker.setOnValueChangedListener(this);
        townPicker.setOnValueChangeListenerInScrolling(this);
        tv_task_name = (TextView) findViewById(R.id.tv_task_name);
        tv_task_start_time = (TextView) findViewById(R.id.tv_task_start_time);
        tv_task_end_time = (TextView) findViewById(R.id.tv_task_end_time);
        tv_task_type = (TextView) findViewById(R.id.tv_task_type);
        tv_task_area = (TextView) findViewById(R.id.tv_task_area);
        tv_task_executors = (TextView) findViewById(R.id.tv_task_executors);
        tv_task_deadline_type = (TextView) findViewById(R.id.tv_task_deadline_type);
        tv_task_level = (TextView) findViewById(R.id.tv_task_level);
        tv_task_start_time.setText(dateFormat.format(mCurrentTask.getStarttime()));
        tv_task_end_time.setText(dateFormat.format(mCurrentTask.getEndtime()));
        tv_task_name.setText(mCurrentTask.getName());
        tv_task_type.setText(mCurrentTask.getTypename());
        tv_task_deadline_type.setText(mCurrentTask.getDeadlinetype());
        tv_task_level.setText(taskLevelDomainItemMap.get(mCurrentTask.getLevelnum()).getText());
        String area = mCurrentTask.getCityname() + mCurrentTask.getDistrictname();
        tv_task_area.setText(area);
        if (mCurrentMode == MODE_UPDATE) {
            String executors = mCurrentTask.getExecutorrealnames().replaceAll(Constant.CONNECTOR, Constant.CONNECTOR_FOR_VIEW);
            tv_task_executors.setText(executors);
        }
    }
 
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }
 
    private void showDatePickerDialog(Calendar cal, final boolean isStartTime) {
        final int year, month, day;
        year = cal.get(java.util.Calendar.YEAR);
        month = cal.get(java.util.Calendar.MONTH);
        day = cal.get(java.util.Calendar.DAY_OF_MONTH);
        //日历控件
        DatePickerDialog dp = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int iyear, int monthOfYear, int dayOfMonth) {
                String name;
                if (isStartTime) {
                    cal_s.set(Calendar.YEAR, iyear);
                    cal_s.set(Calendar.MONTH, monthOfYear);
                    cal_s.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                    cal_s.set(Calendar.HOUR_OF_DAY, 0);
                    cal_s.set(Calendar.MINUTE, 0);
                    cal_s.set(Calendar.SECOND, 0);
                    String dateString = dateFormat.format(cal_s.getTime());
                    mCurrentTask.setStarttime(cal_s.getTime());
                    tv_task_start_time.setText(dateString);
                    cal_e.set(Calendar.YEAR, iyear);
                    cal_e.set(Calendar.MONTH, monthOfYear);
                    cal_e.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                    cal_e.add(Calendar.MONTH, 1);
                    cal_e.add(Calendar.DAY_OF_YEAR, -1);
                    cal_e.set(Calendar.HOUR_OF_DAY, 23);
                    cal_e.set(Calendar.MINUTE, 59);
                    cal_e.set(Calendar.SECOND, 59);
                    String dateString2 = dateFormat.format(cal_e.getTime());
                    mCurrentTask.setEndtime(cal_e.getTime());
                    tv_task_end_time.setText(dateString2);
                } else {
                    cal_e.set(Calendar.YEAR, iyear);
                    cal_e.set(Calendar.MONTH, monthOfYear);
                    cal_e.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                    cal_e.set(Calendar.HOUR_OF_DAY, 23);
                    cal_e.set(Calendar.MINUTE, 59);
                    cal_e.set(Calendar.SECOND, 59);
                    String dateString = dateFormat.format(cal_e.getTime());
                    mCurrentTask.setEndtime(cal_e.getTime());
                    tv_task_end_time.setText(dateString);
                }
                updateMonthDiff(iyear, monthOfYear);
                mCurrentTask.setName(String.format(template, pattens[0], pattens[1], pattens[2], pattens[3]));
                tv_task_name.setText(mCurrentTask.getName());
            }
        }, year, month, day);
        DatePicker datePicker = dp.getDatePicker();
        if (isStartTime) {
//            datePicker.setMinDate(Calendar.getInstance().getTimeInMillis());
        } else {
            datePicker.setMinDate(mCurrentTask.getStarttime().getTime());
        }
        dp.show();
    }
 
    private void updateMonthDiff(int iyear, int monthOfYear) {
        String name;
        int yearDiff = cal_e.get(Calendar.YEAR) - cal_s.get(Calendar.YEAR);
        int monthDiff = yearDiff * 12 + cal_e.get(Calendar.MONTH) - cal_s.get(Calendar.MONTH);
        if (yearDiff == 0) {
            if (monthDiff == 0) {
                name = "%d年%d月";
                pattens[0] = String.format(Locale.CHINA, name, iyear, monthOfYear + 1);
 
            } else {
                name = "%d年%d月-%d月";
                pattens[0] = String.format(Locale.CHINA, name, iyear, cal_s.get(Calendar.MONTH) + 1, monthOfYear + 1);
            }
        } else {
            name = "%d年%d月-%d年%d月";
            pattens[0] = String.format(Locale.CHINA, name, cal_s.get(Calendar.YEAR), cal_s.get(Calendar.MONTH) + 1, cal_e.get(Calendar.YEAR), monthOfYear + 1);
        }
    }
 
    /**
     * 显示任务类型对话框
     */
    private void showTaskTypeDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        Domaincatalog domaincatalog = daoSession.getDomaincatalogDao().load(Domain.DOMAINGUID_TASKTYPE);
        builder.setTitle(domaincatalog.getName());
        final String[] items = new String[taskTypeDomainItemList.size()];
        for (int i = 0; i < items.length; i++) {
            Domainitem item = taskTypeDomainItemList.get(i);
            items[i] = item.getText();
        }
        builder.setSingleChoiceItems(items, mCurrentTask.getTypeno() - 1,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        taskTypeChoice = which;
                        Toast.makeText(NewMonthTaskActivity.this, items[which],
                                Toast.LENGTH_SHORT).show();
                    }
                });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                if (taskTypeChoice != -1) {
                    Domainitem item = taskTypeDomainItemList.get(taskTypeChoice);
                    mCurrentTask.setTypeno(Byte.parseByte(item.getValue()));
                    mCurrentTask.setTypename(item.getText());
                    tv_task_type.setText(mCurrentTask.getTypename());
                }
            }
        });
        builder.show();
    }
 
    /**
     * 显示任务期限类型对话框
     */
    private void showTaskDeadlineTypeDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        Domaincatalog domaincatalog = daoSession.getDomaincatalogDao().load(Domain.DOMAINGUID_TASKDEADLINETYPE);
        builder.setTitle(domaincatalog.getName());
        final String[] items = new String[deadlineTypeDomainItemMap.size()];
        for (Map.Entry<Integer, Domainitem> entry : deadlineTypeDomainItemMap.entrySet()) {
            Domainitem item = entry.getValue();
            items[item.getIndex()] = item.getText();
        }
        int choice;
        if (taskDeadLineChoice == -1) {
            choice = 0;
        } else {
            choice = taskDeadLineChoice;
        }
        builder.setSingleChoiceItems(items, choice,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        taskDeadLineChoice = which;
                        Toast.makeText(NewMonthTaskActivity.this, items[which],
                                Toast.LENGTH_SHORT).show();
                    }
                });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                if (taskDeadLineChoice != -1) {
                    Domainitem item = deadlineTypeDomainItemMap.get(taskDeadLineChoice + 1);
                    mCurrentTask.setDeadlinetype(item.getText());
                    tv_task_deadline_type.setText(mCurrentTask.getDeadlinetype());
                    if (item.getText().equals(Domain.TASK_DEADLINE_TYPE_TEMPORARY)) {
                        mCurrentTask.setLevelnum(Domain.TASK_LEVEL_1);
                        tv_task_level.setText(taskLevelDomainItemMap.get(mCurrentTask.getLevelnum()).getText());
                    }
                }
            }
        });
        builder.show();
    }
 
    /**
     * 显示任务层次对话框
     */
    private void showTaskLevelDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        Domaincatalog domaincatalog = daoSession.getDomaincatalogDao().load(Domain.DOMAINGUID_TASKLEVEL);
        builder.setTitle(domaincatalog.getName());
        final String[] items = new String[taskLevelDomainItemMap.size()];
        for (Map.Entry<Integer, Domainitem> entry : taskLevelDomainItemMap.entrySet()) {
            Domainitem item = entry.getValue();
            items[item.getIndex()] = item.getText();
        }
        builder.setSingleChoiceItems(items, mCurrentTask.getLevelnum() - 1,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        taskLevelChoice = which;
                        Toast.makeText(NewMonthTaskActivity.this, items[which],
                                Toast.LENGTH_SHORT).show();
                    }
                });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                if (taskLevelChoice != -1) {
                    mCurrentTask.setLevelnum(taskLevelChoice + 1);
                    tv_task_level.setText(taskLevelDomainItemMap.get(mCurrentTask.getLevelnum()).getText());
                }
            }
        });
        builder.show();
    }
 
    /**
     * 显示省市区街镇选取对话框
     */
    private void showAreaPickerView() {
        if (!isFirstShowAreaPicker) {
            return;
        }
        isFirstShowAreaPicker = false;
        if (provinces == null) {
            provinces = new String[list_province.size()];
        }
        for (int i = 0; i < list_province.size(); i++) {
            provinces[i] = list_province.get(i).getProvincename();
        }
        String[] citys = updateShowText(list_city, Domain.LEVEL_CITY, 0);
        String[] districts = updateShowText(list_district, Domain.LEVEL_DISTRICT, 0);
        String[] towns = updateShowText(list_town, Domain.LEVEL_TOWN, 0);
        provincePicker.refreshByNewDisplayedValues(provinces);
        cityPicker.refreshByNewDisplayedValues(citys);
        districtPicker.refreshByNewDisplayedValues(districts);
        townPicker.refreshByNewDisplayedValues(towns);
        provincePicker.setWrapSelectorWheel(false);
        cityPicker.setWrapSelectorWheel(false);
        districtPicker.setWrapSelectorWheel(false);
        townPicker.setWrapSelectorWheel(false);
    }
 
    private String[] updateShowText(List list, int level, int valueIndex) {
        long areaId = 0;
        ArrayList<Object> areaList = new ArrayList<>();
        switch (level) {
            case Domain.LEVEL_PROVINCE:
                break;
            case Domain.LEVEL_CITY:
                areaId = list_province.get(valueIndex).getProvinceid();
                break;
            case Domain.LEVEL_DISTRICT:
                areaId = list_city.get(valueIndex).getCityId();
                break;
            case Domain.LEVEL_TOWN:
                areaId = list_district.get(valueIndex).getDistrictid();
                break;
        }
        for (Object object : list) {
            if (object instanceof City) {
                if (((City) object).getPronvinceid() == areaId) {
                    areaList.add(object);
                }
            } else if (object instanceof District) {
                if (((District) object).getCityid() == areaId) {
                    areaList.add(object);
                }
            } else if (object instanceof Town) {
                if (((Town) object).getDistrictid() == areaId) {
                    areaList.add(object);
                }
            }
        }
        int areaLen = areaList.size();
        String[] areaArr = new String[areaLen];
        for (int i = 0; i < areaArr.length; i++) {
            Object area = areaList.get(i);
            switch (level) {
                case Domain.LEVEL_CITY:
                    areaArr[i] = ((City) area).getCityname();
                    break;
                case Domain.LEVEL_DISTRICT:
                    areaArr[i] = ((District) area).getDistrictname();
                    break;
                case Domain.LEVEL_TOWN:
                    areaArr[i] = ((Town) area).getTownname();
                    break;
            }
        }
        return areaArr;
    }
 
    /**
     * 显示任务执行者多选对话框
     */
    private void showExecutorsDialog() {
        // 设置默认选中的选项,全为false默认均未选中
        if (mCheckedArray == null) {
            mCheckedArray = new boolean[userList.size()];
            for (int i = 0; i < mCheckedArray.length; i++) {
                mCheckedArray[i] = false;
            }
        }
        if (mCurrentMode == MODE_UPDATE) {
            ArrayList<Userinfo> list = new ArrayList<>();
            list.addAll(userList);
            userList.clear();
            int index = 0;
            for (Userinfo userinfo : list) {
                if (mCurrentTask.getExecutorguids().contains(userinfo.getGuid())) {
                    userList.add(index, userinfo);
                    mCheckedArray[index] = true;
                    index++;
                } else {
                    userList.add(userinfo);
                }
            }
        }
        AlertDialog.Builder multiChoiceDialog = new AlertDialog.Builder(NewMonthTaskActivity.this);
        multiChoiceDialog.setTitle("选择任务执行者");
        final String[] items = new String[userList.size()];
        for (int i = 0; i < items.length; i++) {
            items[i] = userList.get(i).getRealname();
        }
        multiChoiceDialog.setMultiChoiceItems(items, mCheckedArray,
                new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which,
                                        boolean isChecked) {
                        if (mOriginalExecutors != null && mOriginalExecutors.contains(userList.get(which).getGuid())) {
                            Toast.makeText(NewMonthTaskActivity.this, "此用户不可取消。", Toast.LENGTH_SHORT).show();
                        } else {
                            mCheckedArray[which] = isChecked;
                        }
                    }
                });
        multiChoiceDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        int i = 0;
                        StringBuilder sb = new StringBuilder();
                        StringBuilder sb_un = new StringBuilder(); //用户名字符串
                        StringBuilder sb_rn = new StringBuilder(); //真实姓名字符串,用于界面显示
                        for (boolean isChecked : mCheckedArray) {
                            if (isChecked) {
                                Userinfo user = userList.get(i);
                                sb.append(user.getGuid()).append(Constant.CONNECTOR);
                                sb_un.append(user.getAcountname()).append(Constant.CONNECTOR);
                                sb_rn.append(user.getRealname()).append(Constant.CONNECTOR);
                            }
                            i++;
                        }
                        if (sb.length() > 0) {
                            String executors = sb.deleteCharAt(sb.length() - 1).toString();
                            String executors_un = sb_un.deleteCharAt(sb_un.length() - 1).toString();
                            String executors_rn = sb_rn.deleteCharAt(sb_rn.length() - 1).toString();
                            mCurrentTask.setExecutorguids(executors);
                            mCurrentTask.setExecutorusernames(executors_un);
                            mCurrentTask.setExecutorrealnames(executors_rn);
                            tv_task_executors.setText(executors_rn.replaceAll(Constant.CONNECTOR, Constant.CONNECTOR_FOR_VIEW));
                        }
                    }
                });
        multiChoiceDialog.show();
    }
 
    /**
     * 获取用户信息,首先获取本地数据库的用户列表,同步向服务器发送请求
     */
    private void loadUser(boolean isShowExecutorsDialog) {
        //获取本地数据
        userList.clear();
        userList = daoSession.getUserinfoDao().queryBuilder()
                .where(UserinfoDao.Properties.Usertypeid.eq(1)).list();
        //异步任务加载
        new LoadUserInfoAsynctask(isShowExecutorsDialog).execute();
    }
 
    /**
     * 获取数据库中省市区街镇的信息
     */
    private void loadArea() {
        list_province = daoSession.getProvinceDao().loadAll();
        list_city = daoSession.getCityDao().loadAll();
        list_district = daoSession.getDistrictDao().loadAll();
        list_town = daoSession.getTownDao().loadAll();
    }
 
    @Override
    protected void onPause() {
        super.onPause();
        //保存当前数据至本地
 
    }
 
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.ll_task_start_time) {
            if (mCurrentMode == MODE_ADD) {
                showDatePickerDialog(cal_s, true);
            } else {
                Toast.makeText(this, "任务开始时间不能修改。", Toast.LENGTH_SHORT).show();
            }
        } else if (id == R.id.ll_task_end_time) {
            showDatePickerDialog(cal_e, false);
        } else if (id == R.id.ll_task_type) {
            if (mCurrentMode == MODE_ADD) {
                showTaskTypeDialog();
            } else {
                Toast.makeText(this, "任务类型不能修改。", Toast.LENGTH_SHORT).show();
            }
        } else if (id == R.id.ll_task_deadline_type) {
            if (mCurrentMode == MODE_ADD) {
                showTaskDeadlineTypeDialog();
            } else {
                Toast.makeText(this, "任务期限类型不能修改。", Toast.LENGTH_SHORT).show();
            }
        } else if (id == R.id.ll_task_level) {
            if (mCurrentMode == MODE_ADD) {
                if (!mCurrentTask.getDeadlinetype().equals(Domain.TASK_DEADLINE_TYPE_TEMPORARY)) {
                    showTaskLevelDialog();
                } else {
                    Toast.makeText(this, "当前任务期限为临时任务。", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(this, "任务层次不能修改。", Toast.LENGTH_SHORT).show();
            }
        } else if (id == R.id.ll_task_area) {
            if (mCurrentMode == MODE_ADD) {
                toggleView(areaPickerLayout);
                showAreaPickerView();
            } else {
                Toast.makeText(this, "任务区域不能修改。", Toast.LENGTH_SHORT).show();
            }
        } else if (id == R.id.ll_task_executors) {
            if (isLoadedUsers) {
                showExecutorsDialog();
            } else {
                loadUser(true);
            }
        } else if (id == R.id.view_empty) {
            toggleView(areaPickerLayout);
        } else if (id == R.id.tv_level) {
            isShowingTownPicker = !isShowingTownPicker;
            if (isShowingTownPicker) {
                townPicker.setVisibility(View.VISIBLE);
                tv_level.setText(R.string.hideTown);
            } else {
                townPicker.setVisibility(View.GONE);
                tv_level.setText(R.string.showTown);
            }
        } else if (id == R.id.tv_submit) {
            getAreaInfo();
            areaPickerLayout.setVisibility(View.GONE);
        } else if (id == R.id.tv_save) {//保存本地且提交服务器,生成顶层任务GUID,同时跳转至监管对象版本的制定
            checkingTaskInfo();
        } else if (id == R.id.img_left) {
            this.finish();
        }
    }
 
    /**
     * 验证任务信息是否有遗漏
     */
    private void checkingTaskInfo() {
        if (mCurrentTask.getExecutorguids() == null || mCurrentTask.getStarttime() == null
                || mCurrentTask.getEndtime() == null || mCurrentTask.getDistrictname() == null) {
            Toast.makeText(this, "任务信息不完整,请重新确认信息。", Toast.LENGTH_SHORT).show();
            return;
        }
        View dialog = LayoutInflater.from(this).inflate(R.layout.activity_new_month_task, null);
        final TextView tv_task_name = (TextView) dialog.findViewById(R.id.tv_task_name);
        dialog.findViewById(R.id.actionbar).setVisibility(View.GONE);
        TextView tv_task_start_time = (TextView) dialog.findViewById(R.id.tv_task_start_time);
        TextView tv_task_end_time = (TextView) dialog.findViewById(R.id.tv_task_end_time);
        TextView tv_task_type = (TextView) dialog.findViewById(R.id.tv_task_type);
        TextView tv_task_deadline_type = (TextView) dialog.findViewById(R.id.tv_task_deadline_type);
        TextView tv_task_level = (TextView) dialog.findViewById(R.id.tv_task_level);
        TextView tv_task_area = (TextView) dialog.findViewById(R.id.tv_task_area);
        TextView tv_task_executors = (TextView) dialog.findViewById(R.id.tv_task_executors);
        final CheckBox cb_unfixed_scense = (CheckBox) dialog.findViewById(R.id.cb_unfixed_scense);
        cb_unfixed_scense.setEnabled(false);
        dialog.findViewById(R.id.tv_save).setVisibility(View.GONE);
        tv_task_name.setText(mCurrentTask.getName());
        tv_task_start_time.setText(DateFormatter.dateFormat.format(mCurrentTask.getStarttime()));
        tv_task_end_time.setText(DateFormatter.dateFormat.format(mCurrentTask.getEndtime()));
        tv_task_type.setText(mCurrentTask.getTypename());
        tv_task_deadline_type.setText(this.tv_task_deadline_type.getText());
        tv_task_level.setText(this.tv_task_level.getText());
        cb_unfixed_scense.setChecked(this.cb_unfixed_scense.isChecked());
        String area;
        String areaLevel;
        if (mCurrentTask.getTownname() == null) {
            area = mCurrentTask.getCityname() + mCurrentTask.getDistrictname();
            areaLevel = "3";
        } else {
            area = mCurrentTask.getCityname() + mCurrentTask.getDistrictname() + mCurrentTask.getTownname();
            areaLevel = "4";
        }
        mCurrentTask.setExtension1(areaLevel);
        tv_task_area.setText(area);
        tv_task_executors.setText(this.tv_task_executors.getText());
        new AlertDialog.Builder(this).setTitle("任务信息确认")
                .setView(dialog)
                .setNegativeButton(R.string.cancel, null)
                .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Userinfo user = application.getCurrentUser();
                        Date now = Calendar.getInstance().getTime();
                        mCurrentTask.setSettime(now);
                        mCurrentTask.setPlannerguid(user.getGuid());
                        mCurrentTask.setPlannerusername(user.getAcountname());
                        mCurrentTask.setPlannerrealname(user.getRealname());
                        mCurrentTask.setT1stverifierguid(user.getGuid());
                        mCurrentTask.setT1stverifierusername(user.getAcountname());
                        mCurrentTask.setT1stverifierrealname(user.getRealname());
                        mCurrentTask.setT1stisverify(true);
                        mCurrentTask.setT1stverifytime(now);
                        if (cb_unfixed_scense.isChecked()) {
                            mCurrentTask.setExtension2(Domain.UNFIXED_SCNESE_ALLOWED);
                        } else {
                            mCurrentTask.setExtension2(Domain.UNFIXED_SCNESE_FORBIDDEN);
                        }
                        if (mCurrentMode == MODE_ADD) {
                            Intent intent = new Intent(NewMonthTaskActivity.this, NewMonthTaskMapActivity.class);
                            intent.putExtra(Constant.KEY_INTENT_TOPCLASS_TASK, mCurrentTask);
                            startActivity(intent);
                            NewMonthTaskActivity.this.finish();
                        } else {
                            callPostTopClassTask();
                        }
                    }
                }).show();
    }
 
    private void callPostTopClassTask() {
        view_waiting.setVisibility(View.VISIBLE);
        Call<ResponseBody> call = application.getRetrofit().create(TaskService.class).postTask(mCurrentTask);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
                view_waiting.setVisibility(View.GONE);
                if (response.body() != null) {
                    Toast.makeText(NewMonthTaskActivity.this, "修改任务信息大成功。", Toast.LENGTH_SHORT).show();
                    Intent data = new Intent();
                    data.putExtra(Constant.KEY_INTENT_TOPCLASS_TASK, mCurrentTask);
                    setResult(RESULT_OK, data);
                    NewMonthTaskActivity.this.finish();
                } else if (response.errorBody() != null) {
                    Toast.makeText(NewMonthTaskActivity.this, "修改任务信息失败,请重试。", Toast.LENGTH_SHORT).show();
                }
            }
 
            @Override
            public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
                view_waiting.setVisibility(View.GONE);
            }
        });
    }
 
    /**
     * 获取省市区的信息
     */
    private void getAreaInfo() {
        String provinceName = provincePicker.getContentByCurrValue();
        String cityName = cityPicker.getContentByCurrValue();
        String districtName = districtPicker.getContentByCurrValue();
        String townName = townPicker.getContentByCurrValue();
        Province province = null;
        City city = null;
        District district = null;
        mCurrentTask.setProvincename(provinceName);
        for (Province p : list_province) {
            if (p.getProvincename().equals(provinceName)) {
                province = p;
                mCurrentTask.setProvincecode(p.getProvincecode());
            }
        }
        mCurrentTask.setCityname(cityName);
        for (City c : list_city) {
            if (c.getCityname().equals(cityName) && province != null
                    && c.getPronvinceid().equals(province.getProvinceid())) {
                city = c;
                mCurrentTask.setCitycode(c.getCitycode());
            }
        }
        mCurrentTask.setDistrictname(districtName);
        for (District d : list_district) {
            if (d.getDistrictname().equals(districtName) && city != null
                    && d.getCityid().equals(city.getCityId())) {
                district = d;
                mCurrentTask.setDistrictcode(d.getDistrictcode());
            }
        }
        if (isShowingTownPicker) {
            mCurrentTask.setTownname(townName);
            for (Town t : list_town) {
                if (t.getTownname().equals(townName) && district != null
                        && t.getDistrictid().equals(district.getDistrictid())) {
                    mCurrentTask.setTowncode(t.getTowncode());
                }
            }
            pattens[1] = mCurrentTask.getCityname() + mCurrentTask.getDistrictname() + mCurrentTask.getTownname();
        } else {
            pattens[1] = mCurrentTask.getCityname() + mCurrentTask.getDistrictname();
        }
        mCurrentTask.setName(String.format(template, pattens[0], pattens[1], pattens[2], pattens[3]));
        tv_task_name.setText(mCurrentTask.getName());
        tv_task_area.setText(pattens[1]);
    }
 
    private void toggleView(View view) {
        if (view.isShown()) {
            view.setVisibility(View.GONE);
        } else {
            view.setVisibility(View.VISIBLE);
        }
    }
 
    @Override
    public void onScrollStateChange(NumberPickerView view, int scrollState) {
        int id = view.getId();
        if (id == R.id.picker_province) {
        } else if (id == R.id.picker_city) {
        } else if (id == R.id.picker_district) {
        } else if (id == R.id.picker_town) {
        }
    }
 
    @Override
    public void onValueChange(NumberPickerView picker, int oldVal, int newVal) {
        Log.e(TAG, "onValueChange()" + picker.getValue() + ";" + picker.getContentByCurrValue());
        int id = picker.getId();
        if (id == R.id.picker_province) {
            String[] citys = updateShowText(list_city, Domain.LEVEL_CITY, newVal);
            cityPicker.refreshByNewDisplayedValues(citys);
        } else if (id == R.id.picker_city) {
            String[] districts = updateShowText(list_district, Domain.LEVEL_DISTRICT, newVal);
            districtPicker.refreshByNewDisplayedValues(districts);
        } else if (id == R.id.picker_district) {
            String[] towns = updateShowText(list_town, Domain.LEVEL_TOWN, newVal);
            if (towns != null && towns.length > 0) {
                townPicker.refreshByNewDisplayedValues(towns);
            }
        } else if (id == R.id.picker_town) {
        }
    }
 
    @Override
    public void onValueChangeInScrolling(NumberPickerView picker, int oldVal, int newVal) {
        int id = picker.getId();
        if (id == R.id.picker_province) {
        } else if (id == R.id.picker_city) {
        } else if (id == R.id.picker_district) {
        } else if (id == R.id.picker_town) {
        }
    }
 
    /**
     * 获取用户信息的异步任务
     * <p>
     * 注:目前没有接口,通过获取全部数据来过滤我要的数据.不合理
     */
    private class LoadUserInfoAsynctask extends AsyncTask<Void, Void, Void> {
 
        private final boolean isShowExecutorsDialog;
 
        LoadUserInfoAsynctask(boolean isShowExecutorsDialog) {
            this.isShowExecutorsDialog = isShowExecutorsDialog;
        }
 
        @Override
        protected Void doInBackground(Void... params) {
            UserInfoService userInfoService = application.getRetrofit().create(UserInfoService.class);
            Call<List<Userinfo>> userinfoCall = userInfoService.getAllUser();
            userinfoCall.enqueue(new Callback<List<Userinfo>>() {
                @Override
                public void onResponse(@NonNull Call<List<Userinfo>> call, @NonNull Response<List<Userinfo>> response) {
                    if (response != null && response.body() != null) {
                        List<Userinfo> list = response.body();
//                        daoSession.getUserinfoDao().deleteAll();
//                        daoSession.getUserinfoDao().insertOrReplaceInTx(list);
                        userList.clear();
                        for (Userinfo userinfo : list) {
                            if (userinfo.getUsertypeid() == 1) {
                                userList.add(userinfo);
                            }
                        }
                        isLoadedUsers = true;
                        if (isShowExecutorsDialog) {
                            tv_task_executors.post(new Runnable() {
                                @Override
                                public void run() {
                                    showExecutorsDialog();
                                }
                            });
                        }
                    }
                }
 
                @Override
                public void onFailure(@NonNull Call<List<Userinfo>> call, @NonNull Throwable t) {
                    Log.e(TAG, "onFailure()" + t.getMessage());
                }
            });
            return null;
        }
    }
}