<template>
  <div v-if="active" class="register-edit">
    <nav-bar :go="go"></nav-bar>
    <div class="page-container">
      <!--   基本信息   -->
      <div class="card" v-if="taskInfo">
        <van-cell-group>
          <van-cell :title="taskInfo.taskName">
            <template #right-icon>
              <span :style="{ color: getState(getDictLabel(taskInfo.status, 'safety_check_status')) }">
                {{ getDictLabel(taskInfo.status, 'safety_check_status') }}
              </span>
            </template>
          </van-cell>
          <van-cell title="日期时间" :value="formatTime(taskInfo.planStartTime,taskInfo.planEndTime)" />
          <van-cell title="受检机构" :value="taskInfo.beCheckedOrgName" />
          <van-cell v-if="!enable" title="检查组成员" :value="taskInfo.checkTeam || '无'" />
          <van-field
            v-else
            v-model="taskInfo.checkTeam"
            label="检查组成员"
            rows="2"
            autosize
            type="textarea"
            placeholder="请输入"
          />
        </van-cell-group>
      </div>
      <!--  检查项目    -->
      <fieldset class="fieldset" :disabled="!enable">
        <div class="card">
          <p class="legend">检查项目 <span v-if="enable" @click="addCheck">添加检查内容</span></p>
          <van-collapse v-model="activeNames" v-for="v in checkList" :key="v.itemId">
            <van-collapse-item :title="v.itemName" :name="v.itemName">
              <div v-for="(item, index) in v.pointList" :key="item.pointId">
                <van-cell>
                  <template #title>
                    <pre>{{ item.pointName }}</pre>
                  </template>
                  <template #right-icon>
                    <img
                      v-if="enable && item.nfcList && item.nfcList.length > 0"
                      :src="require('../../../assets/svg/NFC.svg')"
                      class="nfc-icon"
                      @click="clickNFC(item.nfcList)"
                    />
                    <van-switch
                      v-if="enable"
                      style="margin-left: 10px"
                      v-model="item.status"
                      :active-value="1"
                      :inactive-value="0"
                      inactive-color="#4fc08d"
                      active-color="#ee0a24"
                      @change="switchChange(item)"
                      size="20"
                    />
                    <span v-else>
                      <van-tag v-if="item.status" type="warning">隐患</van-tag>
                      <van-tag v-else type="success">正常</van-tag>
                    </span>
                  </template>
                </van-cell>
                <van-cell-group v-show="item.status" :border="false">
                  <van-cell v-if="item.nfcList && item.nfcList.length > 0" :border="false">
                    <div
                      v-if="img.img"
                      class="nfc-img"
                      v-for="(img, i) in item.nfcList"
                      :key="img.img"
                      @click="preViewNFC(i)"
                    >
                      <img :src="imgUrl(img.img)" alt="" />
                      <span>{{ img.checkName }}</span>
                    </div>
                  </van-cell>
                  <select-cell
                    required
                    :disabled="!enable"
                    title="整改期限"
                    v-model="item.rectificationDeadline"
                    :data-list="getDictItem('rectification_deadline')"
                  />
                  <van-field
                    required
                    v-model="item.remark"
                    rows="1"
                    autosize
                    label="情况描述："
                    type="textarea"
                    placeholder="请输入"
                  />
                  <div class="upload-box">
                    <uploader v-if="enable" :maxCount="5" v-model="item.imgData" />
                    <van-cell v-else-if="item.imgData">
                      <div
                        class="nfc-img van-hairline--surround"
                        v-for="(v, i) in item.imgData"
                        :key="v.imgPath"
                        @click="clickWarnImage(item.imgData, i)"
                      >
                        <img :src="imgUrl(v.imgPath)" alt="" />
                      </div>
                      <!--                      <img class="nfc-img" v-for="v in item.imgData" :src="imgUrl(v.imgPath)" alt="" :key="v.id">-->
                    </van-cell>
                  </div>
                </van-cell-group>
              </div>
            </van-collapse-item>
          </van-collapse>
        </div>
      </fieldset>
    </div>
    <!--  按钮   -->
    <div v-if="enable" class="flex-box">
      <van-button type="default" style="width: 30%" plain @click="accredit">授权</van-button>
      <van-button type="info" style="width: 30%" plain hairline @click="saveData">保存</van-button>
      <van-button type="info" style="width: 30%" @click="submitData">提交</van-button>
    </div>

    <!--    <van-image-preview v-model="showPreView" :images="preViewImages.images" :startPosition="preViewImages.startPosition">-->
    <!--      <template v-slot:index>第{{ index }}页</template>-->
    <!--    </van-image-preview>-->

    <!--  nfc弹窗  -->
    <nfc-popup v-if="enable" ref="NfcPopup" @change="changeNfcImg"></nfc-popup>
  </div>

  <!--  添加检查内容  -->
  <AddCheck v-else @goBack="goBack" @addItem="addItem"></AddCheck>
</template>

<script>
import NavBar from '@/components/NavBar'
import SelectCell from '@/components/selectCell'
import DateCell from '@/components/dateCell'
import Uploader from '@/components/upload/uploader'
import NfcPopup from '@/components/nfcPopup/more'
import AddCheck from './addCheck'
import { registerDetail, registerSubmit } from './api'
import { imgUrl } from '@/utils'
import { ImagePreview } from 'vant'
import { mapGetters } from 'vuex'

export default {
  name: 'securityDetail',
  components: { NavBar, SelectCell, DateCell, Uploader, NfcPopup, AddCheck },
  data() {
    return {
      id: null,
      activeNames: ['1'],
      //基本信息
      taskInfo: [],
      NFCList: [],
      //区域下检查内容列表
      checkList: [],
      //检查内容具体项列表
      checkItemList: [],
      //nfc扫描数量
      NFCNum: 0,
      //所有检查项数量
      allCheckNum: 0,
      //区域下检查项数量
      checkNum: 0,
      //nfc图片
      nfcImage: [],
      enable: false,
      stateList: [],
      dayList: [],
      preViewImages: {
        images: [],
        startPosition: 0
      },
      dicts: ['safety_check_status', 'rectification_deadline'],
      showPreView: false,
      selected: null,
      active: true,
      go: {
        type: 'replace',
        path: '/securityCheckRegister'
      }
    }
  },
  computed: {
    ...mapGetters(['dictionary'])
  },
  mounted() {
    this.id = this.$route.query.id
    this.getData()
  },
  methods: {
    //格式化时间范围
    formatTime(start,end,format){
      format = format || 'YYYY-MM-DD'
      return `${this.dayjs(start).format(format)} ~ ${this.dayjs(end).format(format)}`;
    },
    addItem(val) {
      console.log(val, 'list')
      if (!val) return
      let str = JSON.parse(JSON.stringify(val))
      str.forEach(valItem => {
        console.log(this.checkList, 'checkList')
        // 查找是否有与 valItem.itemId 相同的项
        const existingItem = this.checkList.find(checkItem => checkItem.itemId === valItem.itemId)
        if (existingItem) {
          // // 如果存在相同 itemId 的项，查找 pointList 是否有与 valItem.pointId 相同的项
          const existingPoint = existingItem.pointList.find(pointItem => pointItem.pointId === valItem.id)
          if (!existingPoint) {
            console.log(existingItem, 'point添加成功')
            this.$nextTick(() => {
              existingItem.pointList.push(valItem)
              this.active = true
            })
          } else {
            this.$toast(existingPoint.pointName + '已添加')
          }
        } else {
          console.log(valItem, 'item添加成功')
          this.checkList.push({
            itemId: valItem.itemId,
            itemName: valItem.itemName,
            pointList: [valItem]
          })
          this.active = true
        }
      })
    },
    goBack() {
      this.active = true
    },
    getState(state) {
      switch (state) {
        case '待检查':
          return '#bbbbbb'
        case '进行中':
          return '#008cd6'
        case '完成':
          return '#009240'
        case '已过期':
          return '#D7000F'
      }
    },
    addCheck() {
      this.active = false
    },
    clickWarnImage(arr, i) {
      this.preViewImages.images = arr.map(v => imgUrl(v.imgPath))
      this.preViewImages.startPosition = i
      ImagePreview(this.preViewImages)
    },
    preViewNFC(i) {
      this.preViewImages.images = this.nfcImage.map(v => imgUrl(v.img))
      this.preViewImages.startPosition = i
      ImagePreview(this.preViewImages)
    },
    getDicts(s) {
      return this.stateList.find(v => s == v.dictValue).dictLabel
    },
    //初始化数据
    getData() {
      let taskId = this.$route.query.id
      registerDetail(taskId).then(res => {
        console.log(res, 'res')
        this.taskInfo = res.data
        this.enable = this.taskInfo.status === 1 || this.taskInfo.status === 2 //是否可编辑
        this.checkList = res.data.checkList
        //设置默认展开项
        this.activeNames = this.checkList.map(v => v.itemName)
      })
    },
    //保存数据
    saveData() {
      //验证必填项
      let pointData = []
      this.checkList.forEach(v => {
        v.pointList.forEach(item => {
          pointData.push(item)
        })
      })
      let arr = pointData.filter(v => {
        if (v.status === 1) {
          return !v.remark || !v.rectificationDeadline
        }
      })
      if (arr.length) return this.$toast(`${arr[0].itemName}:该信息不完整请填写`)
      this.taskInfo.isSubmit = 0
      registerSubmit(this.taskInfo).then(res => {
        this.$toast('保存成功')
        this.$router.replace({
          path: '/securityCheckRegister'
        })
      })
    },

    //提交数据
    submitData() {
      //验证必填项
      let pointData = []
      this.checkList.forEach(v => {
        v.pointList.forEach(item => {
          pointData.push(item)
        })
      })
      let arr = pointData.filter(v => {
        if (v.status === 1) {
          return !v.remark || !v.rectificationDeadline
        }
      })
      if (arr.length) return this.$toast(`${arr[0].itemName}:该信息不完整请填写`)
      //console.log( this.taskInfo,' this.taskInfo')
      this.taskInfo.isSubmit = 1
      registerSubmit(this.taskInfo).then(res => {
        this.$toast('提交成功')
        this.$router.replace({
          path: '/securityCheckRegister'
        })
      })
    },

    //授权
    accredit() {
      let { checkOrgId, ymdDate, planId, beCheckedOrgId, id } = this.taskInfo
      console.log(checkOrgId, 'checkOrgId')
      this.$router.push({
        path: '/addWorker',
        query: {
          orgId: checkOrgId,
          ymdDate,
          planId,
          beCheckedOrgId,
          taskId: id
        }
      })
    },
    //点击NFC图标
    clickNFC(arr) {
      //if(arr.length === 0) return;
      // let arr = this.selectArea.nfclist.filter(item=>{
      //   return item.status == 0;
      // })
      this.$refs.NfcPopup.show(arr)
    },
    //清空数据
    clearData() {
      this.areaList = []
      this.taskInfo = []
      this.selectArea = []
      this.NFCList = []
      this.checkList = []
      this.checkItemList = []
      this.NFCNum = 0
      this.enable = false
    },
    //切换开关时添加操作时间
    switchChange(item) {
      console.log(item, '666')
      //item.resTime = formatDate(new Date());
    },
    //添加图片时的回调
    changeNfcImg(imgItem) {
      console.log(imgItem, this.selectArea.nfclist, 'imgItem')
      this.selectArea.nfclist.forEach(v => {
        if (v.nfccdoe === imgItem.nfcCode) {
          v.img = imgItem.url
          v.status = 1
          v.scanMethod = 1
          this.nfcImage.push(v)
        }
      })
      console.log(this.selectArea.nfclist, this.nfcImage, 'nfcObj')
    }
  }
}
</script>
<style lang="scss" scoped>
.register-edit {
  height: 100%;
  overflow: hidden;
  .page-container {
    height: calc(100vh - 220px);
    overflow: auto;
    padding: 20px;
  }
  .flex-box {
    padding: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    > span {
      margin: 0 20px;
    }
  }
  .legend {
    background-color: #fff;
    padding: 0 20px;
    height: 80px;
    line-height: 80px;
    font-size: 30px;
    display: flex;
    justify-content: space-between;
    > span {
      color: orange;
    }
  }
  .card {
    margin-bottom: 20px;
    box-shadow: 0 10px 10px #eaeaea;
    &:last-child {
      margin-bottom: 0;
    }
  }
  .check-area {
    background-color: #f1f1f1;
    margin: 10px;
    padding: 20px;
    color: #aaa;
    border-radius: 6px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 2px 6px #ddd;
  }
  .nfc-icon {
    width: 50px;
    height: 50px;
    margin-left: 20px;
  }
  .custom-title {
    align-self: center;
    vertical-align: middle;
  }
  .upload-box {
    margin: 30px;
  }
  .warning-msg {
    color: orange;
    text-align: center;
    height: 80px;
    line-height: 80px;
  }
  .active {
    color: #fff;
    background-color: #1989fa;
  }
  .nfc-img {
    display: inline-block;
    width: 140px;
    height: 140px;
    margin: 0 10px;
    position: relative;
    > img {
      width: 100%;
      height: 100%;
      border: none;
    }
    > span {
      position: absolute;
      padding: 0 10px;
      bottom: 0;
      left: 0;
      display: block;
      width: 100%;
      background-color: rgba(0, 0, 0, 0.2);
      color: #eaeaea;
      font-size: 20px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      line-height: 30px;
      height: 30px;
    }
  }
}
</style>
