<template>
  <div>
    <div class="topBox">
      <NavBar  />

      <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"
            clearable
            :disabled="showStatus"
            label="状态"
            placeholder=""
            @click="showStatus = true"
            ><van-icon name="arrow-down" slot="button"
          /></van-field> -->
          <van-cell title="状态" @click="showStatus = true" is-link arrow-direction="down" :value="fieldValue" />

          <van-popup v-model="showStatus" round position="bottom">
            <van-picker
              title="状态"
              show-toolbar
              :columns="columns"
              @confirm="onConfirm"
              @cancel="onCancel"
              confirm-button-text="确定"
              @change="onChange"
              :close-on-click-overlay="false"
            />
          </van-popup>
        </van-col>
        <van-col span="12">
          <!-- <van-field
            v-model="currentDate"
            clearable
            label-width="3em"
            label="月份"
            placeholder=""
            :disabled="showDate"
            @click="showDate = true"
          >
            <van-icon name="arrow-down" slot="button"
          /></van-field> -->
          <van-cell title="月份" @click="showDate = true" is-link arrow-direction="down" :value="currentDate" />

          <van-popup v-model="showDate" round position="bottom">
            <van-datetime-picker
              v-model="presentDate"
              @cancel="onCancel"
              @confirm="onDateConfirm"
              confirm-button-text="确定"
              type="year-month"
              :formatter="formatter"
              title="月份"
            />
          </van-popup>
        </van-col>
      </van-row>
      <!-- <van-row>
        <van-col span="24"
          ><van-field
            v-model="typeName"
            label-width="3em"
            clearable
            label="类型"
            :disabled="typeStatus"
            placeholder=""
            @click="typeStatus = true"
          >
            <van-icon name="arrow-down" slot="button" />
          </van-field>
          <van-popup v-model="typeStatus" round position="bottom">
            <van-picker
              title="类型"
              show-toolbar
              :columns="typeColumns"
              @confirm="onConfirmHandler"
              @cancel="onCancel"
              @change="onChange"
              confirm-button-text="确定"
              :close-on-click-overlay="false"
            />
          </van-popup>
        </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
                >
              </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 v-if="item.status == 0" class="wj-title-blue">{{ item.statusText }}</div>
              <div v-else-if="item.status == 1" class="wj-title-orange">{{ item.statusText }}</div>
              <div v-else-if="item.status == 2" class="wj-title-green">{{ item.statusText }}</div>
              <div v-else-if="item.status == 3" class="wj-title-red">{{ item.statusText }}</div>
              <div v-else class="wj-title-blue">{{ item.statusText }}</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 { gettrainingList, getsignUserList } from '@/api/training.js'
import { deptTreeList } from '@/api/toConsult.js'

import OrgTree from '@/components/orgTree'
import { newDateMonth } from '@/utils/date.js'
export default {
  data() {
    return {
      orgName: '',
      orgShow: false,
      presentDate: '', //默认时间
      pageNum: 1,
      loading: false, //加载状态
      finished: false, //是否全部加载完毕
      participationList: {
        list: [], // 参与人员
        num: 0 //人数
      },
      absenceList: {
        list: [],
        num: 0
      }, // 缺席人员
      orgName: JSON.parse(sessionStorage.getItem('SET_USER_ORGNAME')) || '', //机构名称
      cascaderValue: '', //机构ID
    
      show: false, //机构弹框显示隐藏

      fieldNames: {
        text: 'name',
        value: 'id',
        children: 'children'
      },
      taskList: [], //列表数据
      typeValue: ' ', //类型值
      typeName: '全部', //类型名称
      value1: JSON.parse(sessionStorage.getItem('SET_USER_ID')) || '', //输入框model

      typeStatus: false, //类型显示隐藏
      showStatus: false, //状态显示隐藏
      showDate: false, //月份显示隐藏
      fieldValue: '全部', //状态名称
      statusValue: ' ', //状态值
      columns: ['全部', '待登记', '待提交', '待签名', '已逾期', '已完成'], //状态数组
      typeColumns: ['全部', '每月安全培训教育', '专项安全培训教育'], //类型数组
      currentDate: newDateMonth(), //月份值
      conditionShow: false //机构弹框显示隐藏
    }
  },
  components: {
    NavBar,
    OrgTree,
    Dialog,
    Icon,
    DatetimePicker,
    Picker,
    Col,
    Row,
    Cascader
  },

  created() {
    this.presentDate = new Date(+newDateMonth().split('-')[0], +newDateMonth().split('-')[1] - 1)
  },
  mounted() {
    this.init()
  
    this.cascaderValue = JSON.parse(window.sessionStorage.getItem('SET_USER_ORGID')) + ''
    
  },
 
  
  methods: {
    //日期选择组件formatter
    formatter(type, val) {
      if (type === 'month') {
        return `${val}月`;
      } else if (type === 'year') {
        return `${val}年`;
      }
      return val;
    },
    //机构搜索
    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 => {
          if (this.value1 == item.userId && item.sign === 0 && item.type == 1) {
            falg = true
          }
        })
      }

      if (falg && timefalg) {
        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.status == 4)) {
        
        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.selectListAppHandler()
    },
    selectListAppHandler(type = 0, callback = () => {}) {
      let obj = {
        isAppSelect: 1,
        pageNum: this.pageNum,
        pageSize: 10
      }
      if (!type) {
        obj.pageNum = 1
        this.pageNum = 1
        this.taskList = []
      }
      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 + '-01'
      }
      if (this.typeValue) {
        obj.type = this.typeValue
      }

      //获取任务列表
      gettrainingList(obj).then(res => {
        let { code, rows, msg,total } = res
        if (code == 200) {
          if (type) {
            this.taskList.push(...rows)

            if (this.taskList.length >= total) {
              //已加载完全部数据
              this.finished = true
            } else {
              callback()
            }
          } else {
            this.taskList.push(...rows)
            this.finished = false
            this.loading = false
            if (this.taskList.length >= total) {
              //已加载完全部数据
              this.finished = true
            }

            // this.taskList = rows || []
          }
        } else {
          this.finished = true
          this.taskList = []
        }
      })
    },

    // 开始调阅事件
    startMonitorHandler(taskId) {
      this.taskId = taskId
      this.showDialog = true
    },
    //已调阅事件
    endMonitorHandler(status, taskId) {
      // 0待调阅，1调阅中，2已调阅，3已超期
      //跳转详情
      if (status <= 1) return
      this.$router.push('/consultInfo/' + taskId)
    },

    //搜索选择状态时触发
    onConfirm(value, index) {
      this.fieldValue = value

      switch (value) {
        case '待登记':
          this.statusValue = '0'

          break
        case '待签名':
          this.statusValue = '1'
          break

        case '已完成':
          this.statusValue = '2'
          break

        case '已逾期':
          this.statusValue = '3'
          break

        case '待提交':
          this.statusValue = '4'
          break
        case '全部':
          this.statusValue = ' '
          break
      }
      this.selectListAppHandler()
      this.showStatus = false
    },
    //类型确认框
    onConfirmHandler(value, index) {
      this.typeName = value

      switch (value) {
        case '每月安全培训教育':
          this.typeValue = '0'

          break
        case '专项安全培训教育':
          this.typeValue = '1'
          break
        case '全部':
          this.typeValue = ' '
          break
      }

      this.typeStatus = false
      this.selectListAppHandler()
    },
    //月份选中触发
    onDateConfirm() {
      this.currentDate = this.newDate(this.presentDate)

      this.showDate = false
      this.selectListAppHandler()
    },
    //日期转换
    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 + '-' + m
    },
    //onLoad下拉刷新
    onLoad() {
     
      this.loading = true
      this.selectListAppHandler(1, () => {
        this.pageNum++
        this.loading = false
        
      })
    },
    //查看签名情况
    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('/Addtraining/' + id)
    },
    //签名
    signature(id) {
      this.$router.push('/personnelSignature/' + id + '_edit')
    },
    //关闭弹框
    beforeClose() {
      console.log('sssssssss')
      ;(this.participationList = {
        list: [], // 参与人员
        num: 0 //人数
      }),
        (this.absenceList = {
          list: [],
          num: 0
        })
    },
    //跳转详情
    goInfo(id) {
      this.$router.push('/personnelSigninfo/' + id + '_info')
    },
    onChange(picker, value, index) {},
    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 - 330px);
  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;
}
.van-cell__value{
  color: black;
  text-align: left;
}
</style>
