<template>
  <div>
    <NavBar/>
    <van-row>
      <van-col span="24">
        <org-tree v-model="cascaderValue" @change="getDataList"></org-tree>
      </van-col>
    </van-row>
    <van-row>
      <van-col span="12"
      >

        <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"
            confirm-button-text="确定"
            @cancel="onCancel"
            @change="onChange"
            :close-on-click-overlay="false"
          />
        </van-popup
        >
      </van-col>
      <van-col span="12">

        <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-button-text="确定"
            @confirm="onDateConfirm"
            type="year-month"
            title="月份"
            ref="pickers"
          />
        </van-popup>
      </van-col>
    </van-row>
    <!-- 调阅列表 -->
    <div class="bigbox">
      <van-list
        v-model="loading"
        :immediate-check="false"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <van-cell-group>
          <van-cell
            @click.stop="linkHandler(item.status, item.id, item)"
            :title="item.taskName"
            v-for="item in taskList"
            :key="item.id"
            size="large"
            :label="item.planStartTime + '~' + item.planEndTime"
            :is-link="item.status != 3"
          >
            <template #title>
              <span class="custom-title">
                {{
                  item.taskName
                }}<van-tag class="resetDy" @click.stop="resetHandler(item.id)" v-if="item.status == 1" type="primary"
              >重新调阅</van-tag
              ></span
              >


              <span :class="monitor[item.status]">{{item.status | statusFilter(this_)}}</span>
            </template>
          </van-cell>
        </van-cell-group>
      </van-list>
    </div>

    <!-- 扫描弹框 -->
    <scandialog ref="scandialog" @input="resultImg" @changeNFC="getNFC"></scandialog>
  </div>
</template>
<script>
import NavBar from '@/components/NavBar'
import {Col, Row, Cascader, Dialog, DatetimePicker, Icon, Picker} from 'vant'
import {deptTreeList, selectListApp, registration, resetTask, getMonitorStart} from '@/api/toConsult.js'
import {Toast} from 'vant'
import OrgTree from '@/components/orgTree'
import {newDateMonth} from '@/utils/date.js'
import scandialog from '@/components/nfcPopup/alone.vue'
import {base64ToBlob} from '@/utils/base64TurnImg.js'
import {upload} from '@/api/public'

export default {
  data() {
    return {
      pageNum: 1,
      loading: false, //加载状态
      finished: false, //是否全部加载完成
      str: '',
      fieldValue: '全部',
      monitor: ['monitor', 'monitored', 'monitoring', 'waringtoring'], //状态样式
      value1: JSON.parse(sessionStorage.getItem('SET_USER_ORGNAME')) || '', //输入框model
      currentDate: newDateMonth(),
      presentDate: '', //当前时间
      cascaderValue: '',
      columns: ['全部'],
      statusList: [], //调阅状态字典数组
      show: false,
      this_: this,
      showStatus: false,
      showDate: false,
      showDialog: false,
      fieldNames: {
        text: 'name',
        value: 'id',
        children: 'children'
      },
      taskId: '', //当前点击所属任务ID
      taskStatus: null, //当前点击所属任务状态
      taskList: [], //任务数组集合
      options: [] //机构数组
    }
  },
  components: {
    NavBar,
    OrgTree,
    scandialog,
    Dialog,
    Icon,
    DatetimePicker,
    Picker,
    Col,
    Row,
    Cascader
  },

  filters: {
    statusFilter(value, this_) {
      let str = ''
      if (this_.statusList.length > 0) {
        this_.statusList.forEach(item => {
          if (value == item.dictValue) {
            str = item.dictLabel
          }
        })
      }

      return str
    }
  },

  computed: {
    presentDateCpd() {
      return new Date(+newDateMonth().split('-')[0], +newDateMonth().split('-')[1] - 1)
    }
  },
  created() {
    this.presentDate = this.presentDateCpd
    this.init()
  },
  mounted() {
    this.cascaderValue = JSON.parse(window.sessionStorage.getItem('SET_USER_ORGID')) + ''
  },
  methods: {
    //单元格点击事件
    linkHandler(status, id, item) {
      if (!this.checkIsCurrentOrgTask()){
        return ;
      }
      if (status == 0) {
        //判断当前时间是否小于开始时间 小于则不能进行操作
        let date = new Date().getTime()
        let startDate = Date.parse(new Date(item.planStartTime))

        if (date <= startDate) {
          Toast.success('当前调阅任务还未开始,不能进行调阅')
        } else {
          this.startMonitorHandler(id, status)
        }
      }

      if (status == 1) {
        this.startMonitorHandler(id, status);
        return;
      }

      if (status == 3) {
        return Toast('当前监控调阅任务已逾期,无法操作!')
      }
      if (status != 0 && status != 3) {
        this.lookInfoHandler(id, status)
      }
    },
    //重新调阅
    resetHandler(id) {
      if (!this.checkIsCurrentOrgTask()){
        return ;
      }
      Dialog.confirm({
        title: '提示',
        message: '确认要对该任务进行重新调阅吗?'
      }).then(() => {
        resetTask(id).then(res => {
          if (res.code == 200) {
            Toast.success('初始化任务成功')
            this.selectListAppHandler()
          }
        })
      })
    },
    //机构变化
    getDataList(v) {
      this.cascaderValue = v
      this.selectListAppHandler()
    },
    //onLoad下拉刷新
    onLoad() {
      if (this.pageNum == 1) {
        this.pageNum = 2
      }
      this.loading = true
      this.selectListAppHandler(1, () => {
        this.pageNum++
        this.loading = false
      })
    },
    //清空查询条件
    clearSearch() {
      this.str = ''
      this.cascaderValue = ''
      this.value1 = ''
      this.currentDate = ''
      this.fieldValue = ''
      this.selectListAppHandler()
    },
    //nfc拍照功能完成
    change(img) {
      console.log(img)
    },
    //初始化
    init() {
      //获取调阅状态字典
      this.getDictHandler('retrieval_task_status', res => {
        this.statusList = res
        res.forEach(item => {
          this.columns.push(item.dictLabel)
        })
      })
      // this.selectListAppHandler()
    },
    selectListAppHandler(type = 0, callBack = () => {
    }) {
      if (!type) {
        this.pageNum = 1
        this.taskList = []
      }

      //获取任务列表
      selectListApp({
        pageNum: this.pageNum,
        pageSize: 10,
        status: this.str || '',
        orgId: this.cascaderValue || JSON.parse(window.sessionStorage.getItem('SET_USER_ORGID')) + '' || '',
        moth: this.currentDate || ''
      }).then(res => {
        let {code, rows, 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 = []
        }
      })
    },

    //扫描NFC
    nfcHandler() {
      //NFC和图片对应字段先写死后期接入app之后再做更改
      let obj = {
        nfc: 'nfc',
        taskId: this.taskId
      }
      registration(obj).then(res => {

        let {code, data, msg} = res
        if (code == 200) {
          Toast.success('扫描成功')
          this.$router.push('/consultInfo/' + this.taskId + '_' + this.taskStatus)
        } else {
          Toast.error({message: msg, position: 'top'})

        }
      })
    },
    //扫描图片并上传到服务器和后端
    photoHandler(img = '', nfc = '') {
      //上传到服务器
      //开始调阅上传
      let obj = {
        startPicture: img,
        startNfc: nfc,
        taskId: this.taskId,
        monitorFlag: 0
      }
      registration(obj).then(res => {
        let {code, data, msg} = res
        if (code == 200) {
          Toast.success('扫描成功')
          this.$router.push('/consultInfo/' + this.taskId + '_' + this.taskStatus)
        }
      })
    },
    //文件上传
    resultImg(img) {
      this.photoHandler(img[0].url)
    },
    //上传NFC
    getNFC(nfc) {
      this.photoHandler('', nfc)
    },
    //关闭弹框事件
    closeDialog() {
      this.show = false
      this.selectListAppHandler()
    },
    checkIsCurrentOrgTask() {
      //判断是否当前用户所属机构的任务, 用户仅允许执行自己机构的任务
      let orgId = JSON.parse(window.sessionStorage.getItem('SET_USER_ORGID'));
      if (orgId == this.cascaderValue) {
        return true;
      }
      console.log('非当前用户所属机构任务,无法执行;')
      return false;
    },
    // 开始调阅事件
    startMonitorHandler(taskId, status) {
      this.taskId = taskId;
      this.taskStatus = status;
      let obj = {taskId: taskId}
      getMonitorStart(obj).then(res => {
        let {code, data, msg} = res
        let dayNums = data.dayNums;
        let noComplete = data.noComplete;
        if (noComplete > 0) {
          this.$router.push('/consultInfo/' + taskId + '_' + status)
        } else {

          if (dayNums >= 5) {
            //提醒确认
            Dialog.confirm({
              title: '提示',
              message: `当前调阅任务今日调阅已达到${dayNums}次,是否继续调阅？`,
            }).then(() => {
              this.$refs.scandialog.visible = true;
              this.globalLoading = true;
            })
          } else {
            this.$refs.scandialog.visible = true;
            this.globalLoading = true;
          }
        }
      })

    },

    //查看调阅详情
    lookInfoHandler(taskId, status) {
      this.taskId = taskId
      this.$router.push('/consultInfo/' + taskId + '_' + status)
    },
    //级联选择当前任意层级触发
    changeCascader(val) {
      console.log(val)
      let {selectedOptions} = val
      //级联值
      this.cascaderValue = selectedOptions[selectedOptions.length - 1].id
      //输入框值
      this.value1 = selectedOptions[selectedOptions.length - 1].name
    },
    onFinish() {
    },
    //搜索选择状态时触发
    onConfirm(value, index) {
      this.fieldValue = value
      this.statusList.forEach(item => {
        if (value == item.dictLabel) {
          this.str = item.dictValue
        }
      })
      if (value == '全部') {
        this.str = ''
      }
      this.showStatus = 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
    },
    onChange(picker, value, index) {
    },
    onCancel() {
      this.show = false
      this.showStatus = false
      this.showDate = false
    }
  }
}
</script>
<style lang="scss" scoped>
.topBox {
  border: 1px solid #ccc;
  margin: 20px;

  display: flex;

  .sonLeftBox {
    padding: 10px;
    flex: 1;
    background-color: #fff;
  }
}

.custom-title {
  font-weight: bold;
}

.van-cell__label {
  font-size: 25px;
}

.monitor {
  color: #008cd6;
  padding-left: 10px;
  padding-right: 10px;

  float: right;
  // font-size: 20px;
  // border-radius: 10px;
  // background-color: #8cb585;
}

.monitored {
  color: #bc9f71;

  padding-left: 10px;
  padding-right: 10px;
  float: right;
  // font-size: 20px;

  // border-radius: 10px;
  // background-color: #1989fa;
}

.monitoring {
  color: #009240;
  padding-left: 10px;
  padding-right: 10px;
  float: right;
  // font-size: 20px;
  // border-radius: 10px;
  // background-color: #25da0b;
}

.waringtoring {
  color: #d7000f;

  padding-left: 10px;
  padding-right: 10px;
  float: right;

  // font-size: 20px;
  // border-radius: 10px;
  // background-color: #e46962;
}

.title {
  margin: 10px;
  margin-left: 0px;
  font-size: 40px;
}

.time {
  font-size: 32px;
}

.startMonitor {
  background-color: #f5f5f9;
  color: #1989fa;
  width: 160px;
  line-height: 200px;
  font-size: 36px;
  text-align: center;
}

.endMonitor {
  background-color: #f5f5f9;
  color: #1989fa;
  width: 160px;
  line-height: 200px;
  font-size: 36px;
  text-align: center;
}

.img_box {
  text-align: center;

  .img {
    width: 200px;
    height: 200px;
  }
}

.text {
  text-align: center;
  font-size: 30px;
  margin-top: 30px;
  margin-bottom: 100px;
}

.btns {
  margin-top: 40px;
  margin-bottom: 40px;
  display: flex;
  justify-content: space-around;

  .nfcPhoto {
    color: #409bf2;

    div {
      width: 100%;
      text-align: center;
    }
  }
}

.btnf_box {
  background-color: #fff;
}

.van-dialog {
  padding: 30px;
}

.spanimg {
  display: flex;
  justify-content: flex-end;

  .close {
    width: 50px;
    height: 50px;
  }
}

.btn {
  float: right;
  margin-top: 24px;
  margin-right: 20px;
  box-sizing: border-box;
}

.bigbox {
  height: calc(100vh - 400px);
  overflow: scroll;
  margin-top: 20px;
  margin-left: 20px;
  margin-right: 20px;
  background-color: #fff;
}

.card {
  margin: 20px;
  margin-bottom: 0px;
  box-shadow: 0 8px 12px #ebedf0;
}

.titleClass {
  display: flex;
  align-items: center;
  height: 100%;
  padding: 20px;
  border-bottom: 1px solid #ccc;

  .title {
    font-size: 30px;
    font-weight: bold;
    flex: 1;
    line-height: 50px;
  }
}

.mainItem {
  display: flex;
  font-size: 28px;
  padding: 20px;
  justify-content: revert;

  .date {
    margin-left: 30px;
  }

  .condition {
    color: #1989fa;
    text-decoration: underline;
  }
}

.bttons {
  color: #1989fa;
  border: none;
}

: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;
}

.resetDy {
  margin-left: 20px;
}

.van-cell__value {
  color: black;
  text-align: left;
}
</style>
