<template>
  <div class="dailyMissionList">
    <headNav title="乡镇检查" @rightClick="rightClick" iconName="plus"></headNav>

    <!-- 搜索 -->
    <div class="searchItem">
      <van-search
        v-model="searchValue"
        input-align="center"
        shape="round"
        @search="sureSearch"
        @clear="cancelSearch"
        background="#ffffff"
        placeholder="请输入搜索内容"
      />
    </div>

    <!-- 日期筛选 -->
    <div class="date_totalInfo">
      <div class="df jfsb">
        <div class="flex1 mb10">
          <van-cell>
            <template #title>
              <div class="df">
                <span class="custom-title" @click="show_time = true">{{showDate}}</span>
                <div class="df aic FontColorInfo fz12" @click="show_time = true">
                  <van-icon class="iconArrow" name="play"></van-icon>
                </div>
                <van-button v-if="showBackMonth" type="primary" size="mini" @click="backToCurrentMonth">回到当月</van-button>
              </div>
            </template>
          </van-cell>
        </div>

        <div class="flex1 mb10">
          <van-cell>
            <template #default>
              <div class="df aic missionFlex">
                <span class="fz13" @click="show_mission = true">{{showMission}}</span>
                <van-icon @click="show_mission = true" class="iconArrow" name="play"></van-icon>
              </div>
            </template>
          </van-cell>
        </div>

        <!-- 时间弹窗 -->
        <van-popup v-model="show_time" position="bottom">
          <van-datetime-picker
            v-model="currentDate"
            type="year-month"
            title="选择年月"
            :min-date="minDate"
            :max-date="maxDate"
            @cancel="show_time = false"
            @confirm="chooseDate"
          />
        </van-popup>

        <!-- 任务弹窗 -->
        <van-popup v-model="show_mission" position="bottom">
          <van-picker
            show-toolbar
            title="任务状态"
            :columns="missionSelect"
            @cancel="show_mission = false"
            @confirm="chooseStatus"
          />
        </van-popup>
      </div>
      <div class="totalCar">
        <div class="mr20">
          今日任务：<span>{{ listTable.length }}</span>条
        </div>
        <div>
          任务时长：<span>{{ todayMisTime }}</span>h
        </div>
      </div>
    </div>

    <div class="missionList">
      <van-list
        v-model="loading"
        :finished="finished"
        :immediate-check="false"
        finished-text="没有更多了"
        @load="getMorePagerList"
      >
        <div
          class="missionItem"
          v-for="item in listTable"
          :key="item.id"
          @click="goDetail(item)"
        >
          <div class="headInfo_car">
            <van-cell>
              <template #title>
                <span class="custom-title">{{ item.enforce_obj_name || (item.enforce_obj && item.enforce_obj.enforce_obj_name) }}</span>
                <!-- <span class="carTips OPoint" v-if="item.checkType === '1'">【日常消防监督检查】</span> -->
              </template>
              <template #default>
                <span v-if="item.job_status == 'TODO'" class="fb FontColorWarn">待执行</span>
                <span v-else-if="item.job_status == 'DOING'" class="fb FontColorOther">执行中</span>
                <span v-else class="fb FontColorSuccess">已归档</span>
              </template>
            </van-cell>
          </div>
          <div class="content_in">
            <div class="contentItem">
              <div class="df aic">
                <div class="FontColorNormal">单位地址：</div>
                <div class="FontColorNormal address">
                  {{ item.enforce_obj && item.enforce_obj.enforce_obj_address }}
                </div>
              </div>
              <div>
                <div>
                  <van-icon
                    name="location"
                    color="#00f"
                    @click.stop="setCenter(item.enforce_obj)"
                  />
                </div>
              </div>
            </div>
            <div class="contentItem">
              <div class="df aic flex2">
                <div class="FontColorNormal">单位类型：</div>
                <div class="FontColorNormal" v-if="item.enforce_obj">
                  {{
                    item.enforce_obj.enforce_obj_type == "1"
                      ? "高危火灾单位"
                      : item.enforce_obj.enforce_obj_type == "2"
                      ? "消防安全重点单位"
                      : item.enforce_obj.enforce_obj_type == "3"
                      ? "一般单位"
                      : "其他单位"
                  }}
                </div>
              </div>
              <div class="df aic flex1">
                <div class="FontColorNormal">场所类型：</div>
                <div class="FontColorNormal">
                  {{ item.placeType }}
                  <!-- {{ item.enforce_obj.place_type == "1" ? "宾馆场所" : "餐饮场所"}} -->
                </div>
              </div>
            </div>
            <div class="contentItem">
              <div class="df aic flex1">
                <div class="FontColorNormal">检查时间：</div>
                <div class="FontColorNormal">{{ formatYYYYMMDD(item.start_time, true) || '未开始' }}</div>
              </div>
              <div class="df aic">
                <div v-if="item.job_status == 'ARCHIVED'" class="FontColorNormal">任务时长：</div>
                <div v-else class="FontColorNormal">任务计划时长：</div>
                <div class="FontColorNormal">{{ item.planTime }}</div>
              </div>
            </div>
            <div class="contentItem">
              <div class="df aic flex1">
                <div class="FontColorNormal">执行人员：</div>
                <div class="FontColorNormal">
                  {{ item.executor_names || getPerson(item.executors) }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </van-list>
    </div>

    <!-- 弹出地图展示 -->
    <van-popup
      v-model="showMap"
      position="bottom"
      @click-overlay="closeOverLay"
      :style="{ height: '450px' }"
    >
      <div v-if="showMap">
        <baiduMap :coor="center" :zoom="zoom"></baiduMap>
      </div>
    </van-popup>

    <!-- 遮罩层 -->
    <v-mask :showOverLay="showOverLay"></v-mask>
  </div>
</template>

<script>
import { get, post } from "@/utils/http.js";
import headNav from "@/components/headNav.vue";
import baiduMap from "@/components/baiduMap.vue";
import mask_overLay from "@/components/overLay_xy.vue";
import { formatYYYYMMDD, notEmpty, dateFormat } from '@/utils/tool';
import { getInfo } from '@/utils/auth';
import dayjs from 'dayjs';
import placeType from '@/mixins/placeType';

export default {
  name: "dailyMissionList",
  inject: ["reload"],
  components: {
    headNav,
    baiduMap,
    "v-mask": mask_overLay,
  },
  mixins: [placeType],
  data() {
    return {
      showBack: false,
      searchValue: "",
      show_time: false,
      showMap: false,
      showBackMonth: false,
      show_mission: false,
      showOverLay: true,
      currentDate: new Date(),
      currentMonth: new Date(),
      minDate: new Date(2000, 0, 1),
      maxDate: new Date(2050, 10, 1),
      showDate: "全部时间",
      showMission: "全部任务",
      todayMisNum: 0,
      todayMisTime: 0,
      missionSelect: [
        {
          k: '',
          text: '全部任务'
        },
        {
          k: 'TODO',
          text: '待执行'
        },
        {
          k: 'DOING',
          text: '执行中'
        },
        {
          k: 'ARCHIVED',
          text: '已归档'
        }
      ],
      // missionSelect: ["全部任务", "待执行", "任务完成", "执行中", "待复查"],
      listTable: [],
      center: "重庆市",
      zoom: 15,
      queryData: {
        job_status: "",
        showDate: "",
      },
      requestData: {
        page: 1,
        size: 10,
        sort: 'create_time desc',
        query: ''
      },
      searchInfo: {
        // startTime: '',
        // endTime: ''
      },
      loading: false,
      finished: false
    };
  },
  computed: {
    userId() {
      const info = getInfo();
      return info ? info.uid : null;
    }
  },
  mounted() {
    this.init();
  },
  // destroyed(){
  //   window.removeEventListener('popstate', this.backPage, false);
  // },
  methods: {
    async init() {
      await this.loadPlaceTypes();
      const now = new Date(); //当前日期
      this.getThisMonthStart(now);
      this.getPagerListApi();
      this.getMissionDuring();
    },
    backToCurrentMonth() {
      this.showDate = dateFormat('YYYY年mm月', this.currentMonth);
      this.currentDate = this.currentMonth;
      this.queryData.showDate = dateFormat('YYYY-mm', this.currentMonth);
      this.requestData.page = 1;
      this.showBackMonth = false;
      this.getPagerListApi();
      this.getMissionDuring();
    },
    rightClick() {
      this.$router.push('/townAdd');
    },
    getMissionDuring() {
      let query = ['job_type==TOWNS'];
      query.push('job_status=in=("TODO","DOING","ARCHIVED")');
      if (this.userId) {
        query.push(`executor_ids==*${this.userId}*`);
      }
      if (notEmpty(this.queryData.showDate)) {
        query.push('last_enforce_date>=' + this.queryData.showDate);
        const end = dayjs(this.currentDate).add(1, 'month').format('YYYY-MM');
        query.push('last_enforce_date<' + end);
      }
      const search = this.searchValue && this.searchValue.trim() || '';
      if (notEmpty(search)) {
        query.push(`enforce_obj_name=='*${search}*'`);
      }
      get('/v2/api/enforce-job/cost', {
        query: query.join(';')
      }).then(res => {
        this.todayMisTime = (res/60).toFixed(1);
      });
    },
    getMorePagerList() {
      this.requestData.page++
      this.getPagerListApi()
    },
    // 获取日常检查列表Api
    getPagerListApi() {
      this.showOverLay = true;
      let query = ['job_type==TOWNS'];
      if (this.userId) {
        query.push(`executor_ids==*${this.userId}*`);
      }
      if (notEmpty(this.queryData.job_status)) {
        query.push('job_status==' + this.queryData.job_status);
      }
      else {
        query.push('job_status=in=("TODO","DOING","ARCHIVED")');
      }
      if (notEmpty(this.queryData.showDate)) {
        query.push('last_enforce_date>=' + this.queryData.showDate);
        const end = dayjs(this.currentDate).add(1, 'month').format('YYYY-MM');
        query.push('last_enforce_date<' + end);
      }
      const search = this.searchValue && this.searchValue.trim() || '';
      if (notEmpty(search)) {
        query.push(`enforce_obj_name==*${search}*`);
      }
      this.requestData.query = query.join(';');
      get("/v2/api/enforce-job", this.requestData).then((res) => {
        const data = res.data || [];
        data.map(item => {
          this.parsePlaceType(item);
          item.planTime = this.getItemTime(item);
        });
        if (this.requestData.page < 2) {
          this.listTable = data;
        }
        else {
          this.listTable = this.listTable.concat(data);
        }
        this.loading = false;
        this.finished = res.page * res.size >= res.total;
        this.showOverLay = false;
      });
    },

    // 获取本月开始 结束
    getThisMonthStart(date, isString) {
      if (!date) {
        return
      }
      let now = date
      if (isString) {
        now = new Date(date)
      }
      var nowMonth = now.getMonth(); //当前月
      var nowYear = now.getYear(); //当前年
      nowYear += nowYear < 2000 ? 1900 : 0;
      var monthStartDate = new Date(nowYear, nowMonth, 1);
      var monthEndDate = new Date(
        nowYear,
        nowMonth,
        this.getMonthDays(nowMonth, nowYear)
      );
      nowMonth += 1;
      if (nowMonth < 10) {
        nowMonth = '0' + nowMonth;
      }
      this.showDate = nowYear + "年" + nowMonth + "月";
      this.queryData.showDate = nowYear + '-' + nowMonth;
    },
    closeOverLay() {
      this.showMap = false;
    },
    getMonthDays(myMonth, nowYear) {
      //获得某月的天数
      var monthStartDate = new Date(nowYear, myMonth, 1);
      var monthEndDate = new Date(nowYear, myMonth + 1, 1);
      var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
      return days;
    },
    formatYYYYMMDD,
    getItemTime(item) {
      let count = 0;
      if (item.start_time && item.finish_time) {
        const num = new Date(item.finish_time) - new Date(item.start_time);
        count = num / (1000 * 60);
      }
      else if (item.item_sum > 0) {
        count = 3 * item.item_sum;
      }
      return (count/60).toFixed(2) + 'h';
    },

    // 设置地图中心
    setCenter(location) {
      this.showMap = true;
      var lo = {
        lng: location.longitude,
        lat: location.latitude,
      };
      this.center = lo;
    },

    // 选择了一个时间
    chooseDate() {
      this.getThisMonthStart(this.currentDate);
      this.requestData.page = 1;
      this.getPagerListApi();
      this.show_time = false;
      const date = dateFormat('YYYYmm', this.currentDate);
      const now = dateFormat('YYYYmm', this.currentMonth);
      this.showBackMonth = date != now;
      this.getMissionDuring();
    },

    // 选择了一个状态
    chooseStatus(obj, index) {
      const e = document.getElementsByClassName('missionList')[0];
      if (e) {
        e.scrollTo(0, 0);
      }
      this.requestData.page = 1;
      this.queryData.job_status = obj.k;
      this.showMission = obj.text;
      this.show_mission = false;
      this.getPagerListApi();
      this.getMissionDuring();
    },
    // 确定搜索
    sureSearch(val) {
      const str = this.searchValue || '';
      this.searchInfo.byCheckUnit = str.trim();
      this.requestData.page = 1;
      this.getPagerListApi();
      this.getMissionDuring();
    },
    // 设置主协标识
    getPerson(per) {
      let str = "";
      if (per) {
        for (let i in per) {
          if (i == 0) {
            str = str + per[i].user_name + "(主)，";
          } else {
            str = str + per[i].user_name + "(协)";
          }
        }
      } else {
        str = "无";
      }
      return str;
    },
    // 取消搜索
    cancelSearch() {
      this.searchInfo.byCheckUnit = "";
      this.getPagerListApi();
      this.getMissionDuring();
    },

    goDetail(data) {
      this.$router.push(`/town/detail/${data.id}`);
    },
  },
};
</script>

<style scoped lang="scss">
.dailyMissionList {
  .searchItem {
    margin-top: 45px;
    border-bottom: 1px solid #d5d5d5;
  }

  .date_totalInfo {
    background-color: #fff;
    padding-bottom: 10px;
    border-bottom: 1px solid #d5d5d5;
  }

  .missionList {
    margin-top: 10px;
    height: calc(100vh - 215px);
    padding: 10px 15px;
    overflow-y: auto;
    font-size: 13px;

    .missionItem {
      margin-bottom: 20px;
      background-color: #fff;
      padding: 5px 12px;
      // border-radius: 5px;
      border-bottom: 1px solid #d5d5d5;

      .carTips {
        color: #999999;
        font-size: 12px;
      }

      .contentItem {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding-top: 10px;

        &:last-child {
          padding-bottom: 10px;
        }
      }
    }
  }

  .missionFlex {
    justify-content: flex-end;
  }

  .totalCar {
    font-size: 12px;
    color: rgb(153, 153, 153);
    padding-left: 15px;
    display: flex;
  }

  .iconArrow {
    margin-top: -3px;
    transform: rotate(90deg);
    margin-left: 5px;
    color: #999999;
    font-size: 12px;
  }
}
.address {
  display: inline-block;
  max-width: 220px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>

<style lang="scss">
.dailyMissionList {
  .van-search {
    padding: 10px 25px;

    .van-search__content.van-search__content--round {
      border: 1px solid #e1e1e1;
    }
  }

  .van-cell {
    &::after {
      border-bottom: none;
    }
  }

  .van-cell.van-cell--clickable {
    display: flex;
    align-items: center;
    color: #969696;

    .van-icon.van-icon-bars {
      margin-left: 5px;
    }
  }

  .headInfo_car {
    border-bottom: 1px solid #fcfcfc;

    .van-cell__title {
      font-weight: bold;
      flex: 2;
      display: flex;
      align-items: center;
    }

    .van-cell {
      padding: 4px 0px;
    }

    .custom-title {
      color: #323232;
      display: inline-block;
      max-width: 240px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }

    .van-cell.van-cell--clickable {
      padding: 0;
    }
  }

  .custom-title {
    color: #323233;
    font-size: 13px;
  }

  .date_totalInfo {
    .van-cell {
      background-color: #f5f5f5;
    }
  }
}
</style>