window.onload = function () {
  function countSelectedNo(result) {
    // 获取 checkList 中 selected 为 'no' 的对象个数
    return result.reduce((total, category) => {
      return (
        total +
        category.gqCheckItemVoList.filter((item) => item.itemAnswer === 2)
          .length
      )
    }, 0)
  }

  function countSelectedNotNull(result) {
    // 获取 checkList 中 selected 不为 null 的个数
    return result.reduce((total, category) => {
      return (
        total +
        category.gqCheckItemVoList.filter((item) => item.itemAnswer !== 0)
          .length
      )
    }, 0)
  }

  new Vue({
    el: '#app',
    data: {
      id: '', // 记录id || 隐患id
      pageName: '', // 页面名称(用于记录页面来源，用于操作后返回上一页)
      flag: 'ZG_XQ', // 值为ADD新增、JC_XQ检查详情、ZG_XQ整改详情、YH_XQ隐患详情
      flag: 'ADD',
      // flag: 'JC_XQ',
      // flag: 'YH_XQ',
      deadlineOptions: ['1', '3', '5', '7'],
      checkData: [], // 提交给后端，图片使用vant结构，base64，后端处理，不走爱山东中台。（数据量大！）
      originCheckData: [],
      checkPageIndex: 0,
      noCount: 0,
      totalItems: 0,
      notNullCount: 0,
      // 外层表单信息
      checkDate: gemhoUtil.getTargetDateYMD(), // 检查日期
      checkPeopleName: '', // 检查人员
      rectificationDeadline: '', // 整改截止日期
      reviewDate: '', // 隐患审核日期
      reviewRecord: '',
    },
    mounted() {
      /**
       * 调转该页面时需要传递参数
       * type : ADD新增、JC_XQ检查详情、ZG_XQ整改详情、YH_XQ隐患详情
       * id: 记录id || 隐患id
       * pageName: 页面名称(用于记录页面来源，用于操作后返回上一页)
       *
       */
      // this.flag = gemhoUtil.getParameter('type')
      // this.id = gemhoUtil.getParameter('id')
      // this.pageName = gemhoUtil.getParameter('pageName')
      // if (type === 'YH_XQ') { // 隐患详情
      // 	this.getDetail4YH_XQ()
      // } else if (this.flag === 'ZG_XQ') { // 整改详情
      // 	this.getDetail4YH_XQ()
      // } else if (this.flag === 'JC_XQ') { // 检查详情
      // 	this.getDetail4JC_XQ()
      // } else if (this.flag === 'ADD') { // 新增，调用模板详情方法
      // 	this.getDetail4Template()
      // }
    },
    watch: {
      checkData: {
        handler(newVal) {
          const snapshot = JSON.parse(JSON.stringify(newVal))
          console.log('全量变化:', snapshot)
          this.noCount = countSelectedNo(newVal) // selected=no 的个数
          // this.totalItems = getTotalCheckListItems(newVal); // checkList 子元素总数
          this.notNullCount = countSelectedNotNull(newVal) // selected 不为 null 的个数
        },
        deep: true,
      },
    },
    methods: {
      getOriginMatchedItemById(id) {
        const result =
          this.originCheckData[this.checkPageIndex]['gqCheckItemVoList'].find(
            (item) => item.id === id
          ) || []
        return JSON.parse(JSON.stringify(result))
      },
      // 处理单选变化
      handleSelectionChange(val, item, index) {
        console.log(val, item, '数据改变了前')
        const newItem = this.getOriginMatchedItemById(item.id)
        console.log(val, newItem, '数据改变了。。。。newItem')
        newItem.itemAnswer = val
        // console.log(this.checkData[this.checkPageIndex]['gqCheckItemVoList'])
        this.$set(
          this.checkData[this.checkPageIndex]['gqCheckItemVoList'],
          index,
          JSON.parse(JSON.stringify())
        )
        console.log(
          val,
          this.checkData[this.checkPageIndex]['gqCheckItemVoList'][index],
          '数据改变了后',
          index
        )
      },
      // 文件上传处理
      handleFileUpload(file) {
        console.log('上传文件:', file)
        // 此处可添加实际文件上传逻辑
      },
      // 整改天数确认
      handleDeadlineConfirm(event, item) {
        console.log('select选择', event.target.value)
        const value = event.target.value
        if (value) {
          const days = parseInt(value)
          item.deadlineDays = days
          const deadlineDate = new Date()
          deadlineDate.setDate(deadlineDate.getDate() + days)
          item.deadlineDate = this.formatDate(deadlineDate)
        }
        // this.showDeadlinePicker = false;
      },
      // 日期格式化
      formatDate(date) {
        return `${date.getFullYear()}-${(date.getMonth() + 1)
          .toString()
          .padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
      },
      getDetail4Template() {
        // 安全检查模板初始化
        vant.Toast.loading({
          message: '正在加载...',
          forbidClick: true,
          loadingType: 'spinner',
        })
        http2.post(
          {
            serviceId: API_KEY_MAP['no-page']['id'],
            interfacePublicKey: API_KEY_MAP['no-page']['publicKey'],
            interfacePrivateKey: API_KEY_MAP['no-page']['privateKey'],
            reqParams: {},
          },
          (res) => {
            if (!res) {
              // 中台返回为undefined 重新请求
              vant.Toast.clear()
              setTimeout(() => {
                this.getDetail4Template()
              }, 0)
              return
            }
            if (res) {
              console.log('接口回调数据', JSON.parse(res))
              setTimeout(() => {
                this.$nextTick(() => {
                  vant.Toast.clear()
                })
              }, 0)
              var result = JSON.parse(res)
              this.checkDate = result.checkDate // 检查日期
              this.checkPeopleName = result.checkPeopleName // 检查人员
              this.rectificationDeadline = result.rectificationDeadline // 整改截止日期
              this.reviewDate = result.reviewDate // 隐患审核日期
              this.reviewRecord = result.reviewRecord
              ;(this.totalItems = result.itemAllCount),
                // 表单数据
                (this.checkData = JSON.parse(JSON.stringify(result.data)))
              this.originCheckData = JSON.parse(JSON.stringify(result.data))
            }
          }
        )
      },
      getDetail4YH_XQ() {
        // 隐患详情
        vant.Toast.loading({
          message: '正在加载...',
          forbidClick: true,
          loadingType: 'spinner',
        })
        http2.post(
          {
            serviceId: API_KEY_MAP['no-page']['id'],
            interfacePublicKey: API_KEY_MAP['no-page']['publicKey'],
            interfacePrivateKey: API_KEY_MAP['no-page']['privateKey'],
            reqParams: {
              hdId: '1',
            },
          },
          (res) => {
            if (!res) {
              // 中台返回为undefined 重新请求
              vant.Toast.clear()
              setTimeout(() => {
                this.getDetail4YH_XQ()
              }, 0)
              return
            }
            if (res) {
              console.log('接口回调数据', JSON.parse(res))
              setTimeout(() => {
                this.$nextTick(() => {
                  vant.Toast.clear()
                })
              }, 0)
              var result = JSON.parse(res)
              this.checkDate = result.checkDate // 检查日期
              this.checkPeopleName = result.checkPeopleName // 检查人员
              this.rectificationDeadline = result.rectificationDeadline // 整改截止日期
              this.reviewDate = result.reviewDate // 隐患审核日期
              this.reviewRecord = result.reviewRecord

              // 表单数据
              this.checkData = result.data
            }
          }
        )
      },
      getDetail4JC_XQ() {
        // 检查单详情
        vant.Toast.loading({
          message: '正在加载...',
          forbidClick: true,
          loadingType: 'spinner',
        })
        http2.post(
          {
            serviceId: API_KEY_MAP['no-page']['id'],
            interfacePublicKey: API_KEY_MAP['no-page']['publicKey'],
            interfacePrivateKey: API_KEY_MAP['no-page']['privateKey'],
            reqParams: {
              recordId: '1',
            },
          },
          (res) => {
            if (!res) {
              // 中台返回为undefined 重新请求
              vant.Toast.clear()
              setTimeout(() => {
                this.getDetail4YH_XQ()
              }, 0)
              return
            }
            if (res) {
              console.log('接口回调数据', JSON.parse(res))
              setTimeout(() => {
                this.$nextTick(() => {
                  vant.Toast.clear()
                })
              }, 0)
              var result = JSON.parse(res)
              this.checkDate = result.data.checkTime // 检查日期
              this.checkPeopleName = result.data.checkPeopleName // 检查人员
              this.checkData = result.data.gqCheckTypeDtoList
              this.noCount = result.data.hiddenCount
              this.notNullCount = result.data.notRectifiedCount
              this.totalItems = result.itemAllCount
            }
          }
        )
      },
      add4ZG_XQ() {
        if (!this.checkData.photos.length) {
          vant.Dialog.alert({
            message: '请上传整改图片',
          })
          return
        }
        vant.Toast.loading({
          message: '正在处理...',
          forbidClick: true,
          loadingType: 'spinner',
        })
        http2.post(
          {
            serviceId: API_KEY_MAP['no-page']['id'],
            interfacePublicKey: API_KEY_MAP['no-page']['publicKey'],
            interfacePrivateKey: API_KEY_MAP['no-page']['privateKey'],
            reqParams: {
              hdId: this.id,
              photos: this.checkData,
            },
          },
          (res, type) => {
            if (!res && !type) {
              // 如果是中台接口返回为undefined，则重新发起请求
              vant.Toast.clear()
              setTimeout(() => {
                this.add4ZG_XQ()
              }, 0)
              return
            }
            if (res) {
              console.log('添加结果', res)
              vant.Toast({
                message: '操作成功',
              })
              // history.back()
              gemhoUtil.navigatePage(
                this.pageName + '.html',
                '操作完成,跳转中...'
              )
            }
          }
        )
      },
      add4YH_XQ(auditStatus) {
        // 隐患详情 审核通过或拒绝
        vant.Toast.loading({
          message: '正在处理...',
          forbidClick: true,
          loadingType: 'spinner',
        })
        http2.post(
          {
            serviceId: API_KEY_MAP['no-page']['id'],
            interfacePublicKey: API_KEY_MAP['no-page']['publicKey'],
            interfacePrivateKey: API_KEY_MAP['no-page']['privateKey'],
            reqParams: {
              hdId: this.id,
              auditStatus,
            },
          },
          (res, type) => {
            if (!res && !type) {
              // 如果是中台接口返回为undefined，则重新发起请求
              vant.Toast.clear()
              setTimeout(() => {
                this.add4YH_XQ()
              }, 0)
              return
            }
            if (res) {
              console.log('添加结果', res)
              vant.Toast({
                message: '操作成功',
              })
              // history.back()
              gemhoUtil.navigatePage(
                this.pageName + '.html',
                '操作完成,跳转中...'
              )
            }
          }
        )
      },
      add4JC_XQ() {
        var reqParam = {
          merId: '1',
          gqCheckTypeVoList: this.checkData,
        }
        var url = '/gq/checkRecord/safeCheckRecord'

        http.post(url, reqParam).then((res) => {
          console.log('添加结果', res)
          vant.Toast({
            message: '操作成功',
          })
          gemhoUtil.navigatePage(this.pageName + '.html', '操作完成,跳转中...')
        })
      },
    },
  })
}
