<template>
  <div>
    <div class="topBox">
      <NavBar :go="{ type: 'push', path: '/menu' }" />

      <van-row>
        <van-col span="24">
          <org-tree v-model="cascaderValue" :name="'sss'" @changeItem="getDataList"></org-tree>
        </van-col>
      </van-row>
      <van-row>
        <van-col span="12"
          ><van-field
            v-model="fieldValue"
            label-width="3em"
            :disabled="showStatus"
            label="状态"
            placeholder=""
            @click="showStatus = true"
            ><van-icon name="arrow-down" slot="button"
          /></van-field>
          <van-popup v-model="showStatus" round position="bottom">
            <van-picker
              title="状态"
              show-toolbar
              :columns="columns"
              @confirm="onConfirm"
              confirm-button-text="确定"
              @cancel="onCancel"
              :close-on-click-overlay="false"
            />
          </van-popup>
        </van-col>
        <van-col span="12">
          <van-field
            v-model="currentDate"
            label-width="3em"
            label="年份"
            placeholder=""
            :disabled="showDate"
            @click="showDate = true"
          >
            <van-icon name="arrow-down" slot="button"
          /></van-field>
          <van-popup v-model="showDate" round position="bottom">
            <van-picker
              v-model="presentDate"
              show-toolbar
              @cancel="onCancel"
              :columns="yearColumns"
              confirm-button-text="确定"
              @confirm="onDateConfirm"
              :default-index="yearSelect"
              title="年份"
            />
          </van-popup>
        </van-col>
      </van-row>
      <van-row>
        <van-col span="24">
          <van-tabs v-model="active" @click="tbsHandler">
            <van-tab name="01-01" title="Q1"></van-tab>
            <van-tab name="04-01" title="Q2"></van-tab>
            <van-tab name="07-01" title="Q3"></van-tab>
            <van-tab name="10-01" title="Q4"></van-tab>
          </van-tabs>
        </van-col>
      </van-row>
    </div>

    <!-- //卡片内容区域 -->
    <div class="navBarclas">
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
        <van-panel :title="item.title" v-for="item in taskList" :key="item.id" class="card" status="状态">
          <template #header>
            <div class="titleClass">
              <div class="title">{{ item.title }}</div>
              <div>
                <van-button type="info" v-if="isSign(item)" size="small" @click="trainSign(item.id)"
                  >演练登记</van-button
                >
                <van-button type="info" v-if="isSignature(item)" size="small" @click="signature(item.id)"
                  >签名</van-button
                >
                <van-button type="info" v-if="evaluateTure(item)" size="small" @click="evaluate(item.id)"
                  >评价</van-button
                >
              </div>
            </div>
          </template>
          <div>
            <div class="mainItem" @click="goInfo(item.id)">
              <div>单位名称</div>
              <div>{{ item.orgName }}</div>
            </div>
            <div class="mainItem" @click="goInfo(item.id)">
              <div>演练状态</div>
              <div class="wj-title-blue" v-if="item.status == 0||item.status == 5" >{{ item.statusText }}</div>
              <div class="wj-title-orange" v-else-if="item.status == 1||item.status == 2" >{{ item.statusText }}</div>
              <div class="wj-title-green" v-else-if="item.status == 3" >{{ item.statusText }}</div>
              <div class="wj-title-red" v-else-if="item.status == 4" >{{ item.statusText }}</div>
              
            </div>
            <div class="mainItem" @click="goInfo(item.id)">
              <div>演练项目</div>
              <div>{{ item.typeText }}</div>
            </div>
            <div class="mainItem" @click="goInfo(item.id)">
              <div>演练时间</div>
              <div v-if="item.drillStartTime&&item.drillEndTime">{{ item.drillStartTime }}-{{item.drillEndTime }}</div>
            </div>
            <div class="mainItem">
              <div>签名情况</div>
              <div class="condition" @click="signatureCondition(item.id)">{{ item.signNums }}</div>
            </div>
          </div>
        </van-panel>
      </van-list>
    </div>
    <!-- 卡片弹框 -->
    <van-dialog
      v-model="conditionShow"
      title="签名情况"
      show-confirm-button
      confirm-button-text="关闭"
      @closed="beforeClose"
    >
      <div class="conditionCls">
        <div class="title">已签名人员({{ participationList.num }}人):</div>
        <div class="people">{{ participationList.list }}</div>
        <div class="title">未签名人员({{ absenceList.num }}人):</div>
        <div class="people">{{ absenceList.list }}</div>
      </div>
    </van-dialog>
  </div>
</template>
<script>
import NavBar from '@/components/NavBar'
import { Col, Row, Cascader, Dialog, DatetimePicker, Icon, Picker } from 'vant'
import { getdrillTask, getsignUserList } from '@/api/drillTask.js'
import { deptTreeList } from '@/api/toConsult.js'
import { Toast } from 'vant'
import OrgTree from '@/components/orgTree'
import { newDateMonth, newDateYear } from '@/utils/date.js'
export default {
  data() {
    return {
      orgName: '',
      orgShow: false,
      presentDate: '', //默认时间
      pageNum: 1,
      loading: false, //加载状态
      finished: false, //是否全部加载完毕
      participationList: {
        list: [], // 参与人员
        num: 0 //人数
      },
      yearColumns: [],
      absenceList: {
        list: [],
        num: 0
      }, // 缺席人员
      orgName: JSON.parse(sessionStorage.getItem('SET_USER_ORGNAME')) || '', //机构名称
      cascaderValue: '', //机构ID
      show: false, //机构弹框显示隐藏
      active: '01-01',
      fieldNames: {
        text: 'name',
        value: 'id',
        children: 'children'
      },
      taskList: [], //列表数据
      typeValue: ' ', //类型值
      yearSelect: null,
      value1: JSON.parse(sessionStorage.getItem('SET_USER_ID')) || '', //输入框model

      showStatus: false, //状态显示隐藏
      showDate: false, //月份显示隐藏
      fieldValue: '全部', //状态名称
      statusValue: ' ', //状态值
      columns: ['全部'], //状态数组
      columnsList: [], //状态数组
      currentDate: newDateYear(), //年份
      conditionShow: false //机构弹框显示隐藏
    }
  },
  components: {
    NavBar,
    OrgTree,
    Dialog,
    Icon,
    DatetimePicker,
    Picker,
    Col,
    Row,
    Cascader
  },

  created() {
    this.presentDate = new Date(newDateYear())
    this.getNewMonth()
    this.yearData()
  },
  mounted() {
    this.init()
    this.cascaderValue = JSON.parse(window.sessionStorage.getItem('SET_USER_ORGID')) + ''
  },
  methods: {
    //getNewDate
    getNewMonth() {
      //获取当前月份
      let date = new Date().getMonth() + 1

      //默认填充当前季度
      if (date > 7 && date < 10) {
        this.active = '07-01'
        //三季度
      } else if (date > 4 && date < 7) {
        //二季度
        this.active = '04-01'
      } else if (date > 1 && date < 4) {
        //一季度
        this.active = '01-01'
      } else {
        this.active = '10-01'
        // 四季度
      }
    },
    //机构搜索
    getDataList(val) {
      this.cascaderValue = val.id
      this.orgName = val.name
      this.selectListAppHandler()
    },
    //判断是否展示签名按钮
    isSignature(list) {
      let falg = false
      let timefalg = false
      //value1 当前登陆用户ID
      //当前时间再时间范围内且签名是待签名状态且签名列表存在当前登录人未签名的情况才可以进行签名
      if (list.startDate && list.endDate && list.status == 1) {
        let date = new Date().getTime()
        let startDate = Date.parse(new Date(list.startDate))
        let endDate = Date.parse(new Date(list.endDate))

        if (date >= startDate && date <= endDate) {
          console.log(list.id, 'ssss')
          timefalg = true
        }
        if(!list.planId){
          timefalg = true
        }
      }
      if (list.userList && list.userList.length > 0) {
        list.userList.forEach(item => {
          console.log(this.value1, 'sss')
          if (this.value1 == item.userId && item.sign == 0 && item.type == 1) {
            falg = true
          }
        })
      }

      if (falg && timefalg) {
        return true
      }
    },
    //判断评价按钮是否展示
    evaluateTure(item) {
      if (item.status == 2 && window.sessionStorage.getItem('SET_USER_ORGTYPE') != 4) {
        return true
      }
    },
    //判断是否展示登记按钮
    isSign(list) {
      let falg = false
      let timefalg = false
      //value1 当前登陆用户ID
      let date = new Date().getTime()
      let startDate = Date.parse(new Date(list.startDate))
      let endDate = Date.parse(new Date(list.endDate))
      //任务处于待记录状态，且任务在规定完成时间范围内，登录人所在机构和角色与任务培训角色、培训机构一致才显示

      if (
        (list.startDate && list.endDate && list.status == 0) ||
        (list.startDate && list.endDate && list.status == 5)
      ) {
        if (date >= startDate && date <= endDate) {
          timefalg = true
        }
      }
      //cascaderValue  当前机构ID
      //当前用户角色ID
      let orgId = JSON.parse(window.sessionStorage.getItem('SET_USER_ORGID')) + ''
      if (orgId == list.orgId) {
        falg = true
      }
      if (date > endDate) {
        //当前时间大于结束时间表示已超期

        timefalg = false
        falg = false
      }
      if (falg && timefalg) {
        return true
      }
    },

    //初始化
    init() {
      //获取数据字典
      this.getDictHandler('drill_task_status', res => {
        this.columnsList = res
        this.columns = res.map(item => item.dictLabel)
        this.columns.unshift('全部')
      })
      //获取分页列表
      this.selectListAppHandler()
    },
    selectListAppHandler(type = 0, callback = () => {}) {
      let obj = {
        isAppSelect: 1,
        pageNum: this.pageNum,
        pageSize: 10
      }
      if (!type) {
        obj.pageNum = 1
        this.pageNum = 1
      }
      if (this.statusValue) {
        obj.status = this.statusValue
      }

      obj.orgId = this.cascaderValue || JSON.parse(window.sessionStorage.getItem('SET_USER_ORGID')) + '' || ''

      if (this.currentDate) {
        obj.date = this.currentDate + '-' + this.active
      }
      if (this.typeValue) {
        obj.type = this.typeValue
      }

      //获取任务列表
      getdrillTask(obj).then(res => {
        let { code, rows, msg } = res
        if (code == 200) {
          if (type) {
            this.taskList.push(...rows)
            if (rows.length == 0 || rows.length < 10) {
              //已加载完全部数据
              this.finished = true
            }
            callback()
          } else {
            this.finished = false
            this.taskList=rows||[]
            if(rows.length == 0){
              this.taskList=[]
            }
          }
        } else {
          this.finished = true
          this.taskList = []
        }
      })
    },

    //搜索选择状态时触发
    onConfirm(value, index) {
      this.fieldValue = value
      this.columnsList.forEach(item => {
        if (value == item.dictLabel) {
          this.statusValue = item.dictValue
        }
      })
      if (value == '全部') {
        this.statusValue = ' '
      }

      this.selectListAppHandler()
      this.showStatus = false
    },
    tbsHandler() {
      this.selectListAppHandler()
    },
    //月份选中触发
    onDateConfirm(val) {
      this.currentDate = this.newDate(val + '')

      this.showDate = false
      this.selectListAppHandler()
    },
    yearData() {
      // 获取默认显示的时间
      var nowTime = new Date()
      let year = nowTime.getFullYear()
      let month = nowTime.getMonth()
      let day = nowTime.getDate()
      // 循环数组 填写最小时间和最大时间范围
      for (let i = 1980; i < 2099; i++) {
        this.yearColumns.push(i)
      }
      // 格式化时间并截取
      var years = this.formatDate(new Date(year, month, day))
      var Year = years.slice(0, 4)
      // 将截取的年份赋值给绑定值 用于点击弹出日期窗口后显示当前的时间
      this.yearSelect = this.yearColumns.indexOf(Number(Year))
    }, //日期转换
    newDate(time) {
      var date = new Date(time)
      var y = date.getFullYear()
      var m = date.getMonth() + 1
      m = m < 10 ? '0' + m : m
      var d = date.getDate()
      d = d < 10 ? '0' + d : d
      return y
    },
    //日期格式
    formatDate(date) {
      return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
    },

    //onLoad下拉刷新
    onLoad() {
      if (this.pageNum == 1) {
        this.pageNum = 2
      }
      this.loading = true
      this.selectListAppHandler(1, () => {
        this.pageNum++
        this.loading = false
        console.log(1)
      })
    },
    //查看签名情况
    signatureCondition(id) {
      this.conditionShow = true
      getsignUserList(id).then(res => {
        console.log(res, 'ssss')
        let { meg, code, data } = res
        data.map(item => {
          if (item.sign != 1) {
            this.absenceList.list.push(item.userName)
            this.absenceList.num++
          } else {
            this.participationList.list.push(item.userName)
            this.participationList.num++
          }
        })
        this.absenceList.list = this.absenceList.list.join(',')
        this.participationList.list = this.participationList.list.join(',')
      })
    },
    //培训登记跳转
    trainSign(id) {
      this.$router.push('/addRehearsalTask/' + id)
    },
    //签名
    signature(id) {
      this.$router.push('/rehearsalTaskSign/' + id + '_edit')
    },
    //评价
    evaluate(id) {
      this.$router.push('/rehearsalTaskSign/' + id + '_evaluate')
    },
    //关闭弹框
    beforeClose() {
      ;(this.participationList = {
        list: [], // 参与人员
        num: 0 //人数
      }),
        (this.absenceList = {
          list: [],
          num: 0
        })
    },
    //跳转详情
    goInfo(id) {
      this.$router.push('/rehearsalTasinfo/' + id + '_info')
    },

    onCancel() {
      this.show = false
      this.typeStatus = false
      this.showDate = false
      this.showStatus = false
    }
  }
}
</script>
<style lang="scss" scoped>
.popup {
  height: 40vh;
}
.navBarclas {
  height: calc(100vh - 380px);
  overflow: scroll;
}
.btnf_box {
  background-color: #fff;
}
.card {
  margin: 20px;
  margin-bottom: 0px;
  box-shadow: 0 8px 12px #ebedf0;
}
.btn {
  float: right;
  margin-top: 24px;
  margin-right: 20px;
  box-sizing: border-box;
}
.titleClass {
  display: flex;
  align-items: center;
  height: 100%;
  padding: 20px;
  border-bottom: 1px solid #ccc;

  .title {
    font-size: 30px;
    flex: 1;
    line-height: 50px;
  }
}
.mainItem {
  display: flex;
  font-size: 28px;
  padding: 20px;
  justify-content: space-between;
  .condition {
    color: #1989fa;
    text-decoration: underline;
  }
}
.conditionCls {
  .title {
    color: #1989fa;
    margin-left: 30px;
    // margin-top: 30px;
  }
  .people {
    margin-left: 80px;
    margin-bottom: 30px;
    margin-top: 30px;
  }
}
.topBox {
  // overflow: hidden;
}
:deep.van-field--disabled {
  color: #323233;
}
:deep.van-field--disabled .van-field__label {
  color: #323233;
}
:deep .van-field__control[disabled] {
  color: #323233;
  -webkit-text-fill-color: #323233;
}
</style>
