<template>
  <div class="container">
    <Header title="添加隐患" />
    <div class="main">
      <Uploader title="隐患照片" :verify="true" v-model="addForm.fileList" />
      <Time title="发现时间" :minDate="new Date(2000, 0, 1)" :verify="true" v-model="addForm.registTime" />
      <Input title="隐患名称" :verify="true" v-model="addForm.dangerName" />
      <Input title="隐患描述" :verify="false" v-model="dangerDesc" />
      <Select
      :disable="dangerType"
        :verify="true"
        title="所在区域"
        :options="getAreaTree"
        v-model="addForm.areaId"
      />
      <Select
      :disable="dangerType"
        :verify="true"
        title="分析对象名称"
        :options="getAreaTree1"
        v-model="addForm.hazardId"
      />
      <Select
        :verify="true"
        title="隐患来源"
        :options="dangerSrcList"
        v-model="addForm.dangerSrc"
      />
      <Select
        :verify="true"
        title="隐患类型"
        :options="dangerTypeList"
        v-model="addForm.hazardDangerType"
      />
      <Radio
        :verify="true"
        title="隐患等级"
        :option="dangerLevelOptions"
        v-model="addForm.dangerLevel"
      />
      <Radio
        :verify="true"
        title="治理类型"
        :option="dangerManageTypeOptions"
        v-model="addForm.dangerManageType"
      />
      <Input title="任务名称" :verify="false" v-model="controlMeasures" />
      <p class="textTitle">整改信息</p>
      <Select
        :verify="true"
        title="整改部门"
        :options="getDeptTree"
        v-model="addForm.deptId"
      />
      <Select
        :verify="true"
        title="整改负责人"
        :options="getDeptUserTree"
        v-model="addForm.manageUserId"
      />
      <Time
        title="整改期限"
        :verify="true"
        :minDate="new Date(
          new Date(addForm.registTime).getFullYear() || 2000,
          new Date(addForm.registTime).getMonth() || 0,
          new Date(addForm.registTime).getDate() || 1
        )"
        v-model="addForm.dangerManageDeaddline"
      />
      <Input title="整改建议" :verify="false" v-model="suggest" />
      <van-button style="margin-top: 15px;" type="primary" @click="add"
        >提交</van-button
      >
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import {
  addDanger,
  upload,
  getDangerItem,
  editDanger,
  convertImageToBase64Str,
  getHazardList
} from '@/api/danger'
export default {
  name: 'Vueh5CbsAddDanger',
  computed: {
    ...mapState('baseUrl', ['baseUrl']),
    ...mapState('dangerList', [
      'dangerSrcList',
      'dangerTypeList',
      'getAreaTree',
      'getDeptTree',
      'getDeptUserTree'
    ]),
    minDate () {
      if (this.addForm.registTime) {
        return new Date(
          new Date(this.addForm.registTime).getFullYear(),
          new Date(this.addForm.registTime).getMonth(),
          new Date(this.addForm.registTime).getDate()
        )
      }

      return new Date(2010, 0, 1)
    }
  },
  watch: {
    addForm: {
      handler (val) {
        if (val.areaId && (val.areaId !== this.areaIdOld)) {
          console.log('进来了', val.areaId, this.areaIdOld)
          this.getHazardList(val.areaId)
          this.areaIdOld = val.areaId
        }
      },
      deep: true,
      immediate: true
    }
  },
  data () {
    return {
      areaIdOld: '.',
      dangerType: false,
      getAreaTree1: [], // 分析对象名称列表
      dangerImage: '',
      dangerDesc: '', // 隐患描述
      controlMeasures: '', // 任务名称
      suggest: '', // 整改建议
      addForm: {
        fileList: [], // 隐患照片
        registTime: '', // 发现时间
        dangerName: '', // 隐患名称
        areaId: '', // 所属区域
        hazardId: '', // 分析对象名称
        dangerLevel: 0, // 隐患等级
        dangerSrc: '', // 隐患来源
        hazardDangerType: '', // 隐患类型
        dangerManageType: 0, // 治理类型
        deptId: '', // 整改部门
        manageUserId: '', // 整改负责人
        dangerManageDeaddline: '' // 整改期限
      },
      itemForm: {},
      dangerManageTypeOptions: [
        {
          name: '即查即改',
          id: 0
        },
        {
          name: '限期整改',
          id: 1
        }
      ],
      dangerLevelOptions: [
        {
          name: '一般隐患',
          id: 0
        },
        {
          name: '重大隐患',
          id: 1
        }
      ]
    }
  },

  async created () {
    console.log(new Date('2023-09-25 15:55:12').getDate())
    if (this.$route.params.id) {
      this.dangerType = true
      this.getAreaTree1 = this.$route.params.list
      this.addForm.areaId = this.$route.params.areaId
      this.areaIdOld = this.$route.params.areaId
      this.addForm.hazardId = this.$route.params.hazardId
      // await this.getHazardList(this.$route.params.areaId)
      console.log(this.addForm.hazardId, '第一个')
      console.log(this.addForm.areaId, '第二个')
    }
    if (this.$route.query.id) {
      getDangerItem(this.$route.query.id).then(({ data }) => {
        if (data.code === 200) {
          this.itemForm = data.data
          this.dangerDesc = data.data.dangerDesc
          this.controlMeasures = data.data.controlMeasures
          this.suggest = data.data.suggest
          this.addForm.registTime = data.data.registTime
          this.addForm.dangerName = data.data.dangerName
          this.addForm.areaId = data.data.areaId
          this.addForm.hazardId = data.data.hazardId
          this.addForm.dangerLevel = data.data.dangerLevel
          this.addForm.dangerSrc = data.data.dangerSrc
          this.addForm.hazardDangerType = data.data.hazardDangerType
          this.addForm.deptId = data.data.deptId
          this.addForm.dangerManageType = data.data.dangerManageType
          this.addForm.manageUserId = data.data.manageUserId
          this.addForm.dangerManageDeaddline = data.data.dangerManageDeaddline
          console.log(data.data.dangerImage.split(','))
          // this.addForm.fileList = data.data.dangerImage.split('').map(item => {
          //   convertImageToBase64Str({ url: item }).then(({ data }) => {
          //     return { content: data.msg, file: '' }
          //   })
          // })
          const list = data.data.dangerImage.split(',')
          this.toBase(list)
          console.log(this.addForm)
        }
      })
    }
  },

  methods: {
    getHazardList (id) {
      getHazardList({ areaId: id }).then(({ data }) => {
        if (data.code === 200) {
          this.getAreaTree1 = this.getUsers(data.data)
          this.addForm.hazardId = ''
        }
      })
    },
    getUsers (data) {
      return data.map(item => {
        return { text: item.hazardName, value: item.id }
      })
    },
    async toBase (list) {
      for await (const item of list) {
        const { data } = await convertImageToBase64Str({ url: item })
        console.log(data)
        if (data.code === 200) {
          this.addForm.fileList.push({ content: data.msg, file: '' })
        } else {
          this.$notify({
            type: 'danger',
            message: data.msg,
            duration: 1000
          })
          return
        }
      }
    },
    // Base64 转 Blob
    dataURLtoBlob (dataurl) {
      var arr = dataurl.split(',') // 分割为数组，分割到第一个逗号
      const mime = arr[0].match(/:(.*?);/)[1] // 获取分割后的base64前缀中的类型
      const bstr = window.atob(arr[1])
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: mime })
    },
    async add () {
      console.log(this.addForm)
      if (this.$examine(this.addForm) === true) {
        this.dangerImage = ''
        console.log('可以提交', this.addForm)
        for await (const item of this.addForm.fileList) {
          const file = new window.File(
            [this.dataURLtoBlob(item.content)],
            '图片.jpg',
            { type: 'jpg' }
          ) // 转成file类型
          console.log(item.file)
          const formData = new FormData()
          formData.append('file', file)
          const { data } = await upload(formData)
          console.log(data)
          if (data.code === 200) {
            if (!this.dangerImage) {
              this.dangerImage += data.fileName
            } else {
              this.dangerImage += ',' + data.fileName
            }
          } else {
            this.$notify({
              type: 'danger',
              message: data.msg,
              duration: 1000
            })
            return
          }
        }
        if (this.$route.query.id) {
          this.itemForm.dangerDesc = this.dangerDesc
          this.itemForm.controlMeasures = this.controlMeasures
          this.itemForm.suggest = this.suggest
          this.itemForm.registTime = this.addForm.registTime
          this.itemForm.dangerName = this.addForm.dangerName
          this.itemForm.areaId = this.addForm.areaId
          this.itemForm.hazardId = this.addForm.hazardId
          this.itemForm.dangerLevel = this.addForm.dangerLevel
          this.itemForm.dangerSrc = this.addForm.dangerSrc
          this.itemForm.hazardDangerType = this.addForm.hazardDangerType
          this.itemForm.deptId = this.addForm.deptId
          this.itemForm.dangerManageType = this.addForm.dangerManageType
          this.itemForm.manageUserId = this.addForm.manageUserId
          this.itemForm.dangerManageDeaddline = this.addForm.dangerManageDeaddline
          this.itemForm.dangerImage = this.dangerImage
          editDanger(this.itemForm).then(({ data }) => {
            if (data.code === 200) {
              this.$notify({
                type: 'success',
                message: data.msg,
                duration: 1000
              })
              this.$router.go(-1)
            }
          })
        } else {
          addDanger({
            riskMeasureId: this.$route.params.riskMeasureId || '',
            checkTaskInventoryRecordId: this.$route.params.id || '',
            areaId: this.addForm.areaId,
            hazardId: this.addForm.hazardId,
            controlMeasures: this.controlMeasures,
            dangerDesc: this.dangerDesc,
            dangerImage: this.dangerImage,
            dangerLevel: this.addForm.dangerLevel,
            dangerManageDeaddline: this.addForm.dangerManageDeaddline,
            dangerManageType: this.addForm.dangerManageType,
            dangerName: this.addForm.dangerName,
            dangerSrc: this.addForm.dangerSrc,
            deptId: this.addForm.deptId,
            hazardDangerType: this.addForm.hazardDangerType,
            manageUserId: this.addForm.manageUserId,
            registTime: this.addForm.registTime,
            suggest: this.suggest
          }).then(({ data }) => {
            if (data.code === 200) {
              this.$notify({
                type: 'success',
                message: data.msg,
                duration: 1000
              })
              this.$router.go(-1)
            }
          })
        }
      } else {
        const list = this.$examine(this.addForm)
        this.addForm = { ...list[0] }
        setTimeout(() => {
          this.addForm = { ...list[1] }
          console.log(this.addForm.manageUserId)
        }, 0)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.textTitle {
  text-align: left;
  font-family: PingFangSC-Semibold;
  font-size: 16px;
  letter-spacing: 0.19px;
  border-bottom: 1px solid #eee;
  margin: 20px 5px;
  padding-bottom: 5px;
  font-weight: 700;
  color: grey;
}
</style>
