<template>
  <div class="container">
    <Header title="隐患详情" />
    <van-tabs
      v-model="activeName"
      color="white"
      background="#1c4990"
      title-active-color="white"
      title-inactive-color="#ccc"
      swipeable
      animated
    >
      <van-tab title="隐患信息" name="a">
        <div class="tabMain">
          <div class="textMain">
            <div class="left">
              <span>隐患图片</span>
              <p style="color:#1c4990;" @click="imageShow = true">
                <van-icon name="photo" color="#1c4990" />共
                {{ imageList.length }} 张
              </p>
            </div>
            <div class="right">
              <span>隐患编号</span>
              <p>{{ itemForm.dangerNo }}</p>
            </div>
          </div>
          <div class="textMain">
            <div class="left">
              <span>发起人</span>
              <p>{{ itemForm.createUserName }}</p>
            </div>
            <div class="right">
              <span>发现时间</span>
              <p>{{ itemForm.registTime }}</p>
            </div>
          </div>
          <div class="textMain">
            <div class="left">
              <span>隐患名称</span>
              <p>{{ itemForm.dangerName }}</p>
            </div>
          </div>
          <div class="textMain">
            <div class="left">
              <span>所在区域</span>
              <p>{{ itemForm.areaName }}</p>
            </div>
            <div class="right">
              <span>分析对象名称</span>
              <p>
                {{ itemForm.hazardName }}
              </p>
            </div>
          </div>
          <div class="textMain">
            <div class="left">
              <span>隐患类型</span>
              <p>
                {{ $findItemById(dangerTypeList, itemForm.hazardDangerType) }}
              </p>
            </div>
            <div class="right">
              <span>隐患来源</span>
              <p>{{ $findItemById(dangerSrcList, itemForm.dangerSrc) }}</p>
            </div>
          </div>
          <div class="textMain">
            <div class="left">
              <span>隐患等级</span>
              <p>{{ itemForm.dangerLevel ? "重大隐患" : "一般隐患" }}</p>
            </div>
            <div class="right">
              <span>隐患描述</span>
              <p>{{ itemForm.dangerDesc || "无" }}</p>
            </div>
          </div>
          <div class="textMain">
            <div class="left">
              <span>治理类型</span>
              <p>{{ itemForm.dangerManageType ? "限期整改" : "即查即改" }}</p>
            </div>
            <div class="right">
              <span>任务名称</span>
              <p>{{ itemForm.controlMeasures || "无" }}</p>
            </div>
          </div>
          <div
            class="btns"
            v-if="
              itemForm.dangerStatus === 10 &&
                itemForm.areaManageUserList.some(
                  item => item.userId === user.userId
                )
            "
          >
            <van-button type="warning" @click="turnDown">驳回</van-button>
            <van-button type="primary" @click="pass">通过</van-button>
          </div>

          <div
            class="btns"
            v-if="
              itemForm.dangerStatus === 20 &&
                itemForm.manageUserId === user.userId
            "
          >
            <van-button type="primary" @click="claim">领取</van-button>
          </div>
          <div class="remark" v-if="itemForm.dangerStatus === 60">
            <p>状态：已驳回</p>
            <p>驳回人：{{ itemForm.rejectUserName }}</p>
            <p>驳回原因：{{ itemForm.remarkInfo || "无" }}</p>
          </div>
        </div>
      </van-tab>
      <van-tab title="整改信息" name="b">
        <div class="tabMain">
          <div class="textBox">
            <p class="tabTitle">整改基本信息</p>
            <div class="textMain">
              <div class="left">
                <span>整改部门</span>
                <p>{{ $findItemById(getDeptTree, itemForm.deptId) }}</p>
              </div>
              <div class="right">
                <span>整改负责人</span>
                <p>
                  {{ itemForm.manageUserName }}
                </p>
              </div>
            </div>
            <div class="textMain">
              <div class="center">
                <span>整改期限</span>
                <p>{{ itemForm.dangerManageDeaddline }}</p>
              </div>
            </div>
            <div class="textMain">
              <div class="center">
                <span>整改建议</span>
                <p>{{ itemForm.suggest || "无" }}</p>
              </div>
            </div>
          </div>
          <div
            class="textBox"
            v-if="itemForm.dangerStatus === 40 || itemForm.dangerStatus === 50"
          >
            <p class="tabTitle">整改措施</p>
            <div class="textMain">
              <div class="left">
                <span>添加时间</span>
                <p>{{ itemForm.dangerManageDeaddline }}</p>
              </div>
              <div class="right">
                <span>整改人</span>
                <p>{{ itemForm.manageUserName }}</p>
              </div>
            </div>
            <div class="textMain">
              <div class="left">
                <span>整改措施</span>
                <p>{{ itemForm.controlMeasures }}</p>
              </div>
              <div class="right">
                <span>整改资金</span>
                <p>{{ itemForm.cost }}</p>
              </div>
            </div>
            <div class="textMain">
              <div class="left">
                <span>整改图片</span>
                <p style="color:#1c4990;" @click="rectifyShow = true">
                  <van-icon name="photo" color="#1c4990" /> 共{{
                    rectifyImage.length
                  }}张
                </p>
              </div>
            </div>
          </div>
          <div
            class="textBox"
            v-if="
              itemForm.dangerStatus === 30 &&
                itemForm.manageUserId === user.userId
            "
          >
          <div v-if="itemForm.checkSignature" class="check">
          <p style="font-size: 18px;margin-bottom: 30px;">验收已被驳回，请重新提交整改措施！</p>
          <div>
            <p>验收人签字：</p>
            <img v-show="itemForm.checkSignature" :src="itemForm.checkSignature" alt="" />
          </div>

              <p>验收时间：{{ itemForm.checkAcceptTime }}</p>
              <p>驳回原因：{{ itemForm.checkAcceptComment }}</p>
          </div>
            <p class="tabTitle">整改措施</p>
            <div class="module">
              <div :class="className">
                <span class="spanTitle1">添加整改时间</span>
                <van-cell :value="internalValue" @click="focus" />
                <b v-if="verify" class="verify">*</b>
              </div>
              <p class="reminder" v-if="reminder">当前项为必填项</p>
            </div>
            <!-- <div class="module">
              <div :class="className1">
                <span class="spanTitle1">审核人</span>
                <van-field
                  v-model="internalValue1"
                  is-link
                  readonly
                  @click="focus1"
                />

                <span class="whiteBack"></span>
                <b v-if="verify1" class="verify">*</b>
              </div>
              <p class="reminder" v-if="reminder1">当前项为必填项</p>
            </div> -->
            <Input title="整改措施" :verify="true" v-model="rectify.measures" />
            <Input title="整改资金" :verify="false" v-model="cost" />
            <Uploader
              title="整改照片"
              :verify="true"
              v-model="rectify.fileList"
            />
            <div style="text-align: center;margin-top: 25px;">
              <van-button type="primary" @click="add">提交</van-button>
            </div>
          </div>
          <div class="textBox" v-if="itemForm.dangerStatus === 50">
            <p class="tabTitle">验收信息</p>
            <div class="textMain">
              <div class="left">
                <span>验收人签字</span>
                <img
                  :src="itemForm.checkSignature"
                  alt=""
                />
              </div>
            </div>
            <div class="textMain">
              <div class="left">
                <span>验收时间</span>
                <p>{{ itemForm.checkAcceptTime }}</p>
              </div>
              <div class="right">
                <span>验收情况描述</span>
                <p>{{ itemForm.checkAcceptComment }}</p>
              </div>
            </div>
          </div>
          <div
            class="textBox"
            v-if="
              itemForm.dangerStatus === 40 &&
                itemForm.areaManageUserList.some(
                  item => item.userId === user.userId
                )
            "
          >
            <p class="tabTitle">验收信息</p>

            <p class="textSign">验收人签字</p>
            <div class="sign">
              <div class="signImg">
                <img v-show="signImg" :src="signImg" alt="" />
              </div>
              <div class="signBtn">
                <p @click="delImg">
                  <van-icon name="delete-o" />
                  <span class="empty">清除</span>
                </p>
                <p @click="toSign">
                  <van-icon name="edit" />
                  <span class="empty">去签字</span>
                </p>
              </div>
            </div>
            <div class="module">
              <div :class="className">
                <span class="spanTitle1">添加验收时间</span>
                <van-cell :value="internalValue" @click="focus" />
                <b v-if="verify" class="verify">*</b>
              </div>
              <p class="reminder" v-if="reminder">当前项为必填项</p>
            </div>
            <Input title="验收情况描述" :verify="false" v-model="remark" />
            <div class="btns">
              <van-button type="warning" @click="checkDown">驳回</van-button>
              <van-button type="primary" @click="checkAdd">通过</van-button>
            </div>
          </div>
        </div>
      </van-tab>
      <van-tab title="流程信息" name="c">
        <div class="tabMain">
          <div
            class="flowText"
            v-for="(item, index) in dangerOperateRecordList"
            :key="index"
          >
            <div :class="[item.operateNickName ? 'borderText' : 'borderText1']">
              <p>{{ item.operateNickName + item.statusDesc }}</p>
              <p>完成时间：{{ item.operateTime }}</p>
            </div>
            <p
              class="flowText"
              v-show="index !== dangerOperateRecordList.length - 1"
            >
              <b>↑</b>
            </p>
          </div>
        </div>
      </van-tab>
    </van-tabs>
    <van-image-preview
      v-model="imageShow"
      :images="imageList"
      :closeable="true"
      :loop="false"
      :closeOnPopstate="true"
    />
    <van-image-preview
      v-model="rectifyShow"
      :images="rectifyImage"
      :closeable="true"
      :loop="false"
      :closeOnPopstate="true"
    />
    <van-calendar
      color="#1c4990"
      :default-date="new Date()"
      :min-date="new Date(2010, 0, 1)"
      :max-date="new Date(2050, 0, 1)"
      v-model="show"
      @confirm="onConfirm"
      @close="blur"
    >
      <template slot="title">
        <div class="calendar-title" @click="timerPicker = true">
          {{ selectTimeToSeconds }}
        </div>
      </template>
    </van-calendar>
    <van-overlay
      class="time-picker"
      :show="timerPicker"
      :close-on-click-overlay="false"
    >
      <van-picker
        show-toolbar
        title="选择时间"
        :columns="timeColumns"
        @cancel="timerPicker = false"
        @confirm="confirmTime"
      />
    </van-overlay>
    <van-popup v-model="show1" round position="bottom">
      <van-cascader
        v-model="cascaderValue"
        title="审核人"
        :options="getDeptUserTree"
        @close="blur1"
        @finish="onFinish1"
        active-color="#1c4990"
      />
    </van-popup>
    <van-dialog
      v-model="showDia"
      title="驳回原因"
      show-cancel-button
      confirmButtonColor="#1c4990"
      @cancel="turnValue = ''"
      @confirm="review"
    >
      <van-field
        placeholder="请输入驳回原因"
        rows="1"
        autosize
        v-model="turnValue"
        v-bind="$attrs"
        type="textarea"
      />
    </van-dialog>
    <Signature v-if="isSign" @getSign="getSign" />
  </div>
</template>

<script>
import {
  getDangerItem,
  upload,
  dangerReview,
  receiveDanger,
  checkDangerManage,
  submitDangerManage
} from '@/api/danger'
import { mapState } from 'vuex'
import Signature from '@/components/signature'
import moment from 'moment'
export default {
  name: 'VueSkDangerDetails',
  computed: {
    ...mapState('baseUrl', ['baseUrl']),
    ...mapState('login', ['user']),
    ...mapState('dangerList', [
      'dangerSrcList',
      'dangerTypeList',
      'getAreaTree',
      'getDeptTree',
      'getDeptUserTree'
    ])
  },
  components: {
    Signature
  },
  data () {
    return {
      typeNum: 1,
      isSign: false,
      showDia: false,
      turnValue: '', // 驳回原因
      // 整改数据
      rectify: {
        measures: '', // 整改措施
        fileList: [] // 隐患图片
      },
      remark: '',
      // 验收数据
      cascaderValue: '',
      internalValue: '',
      cost: '', // 整改资金
      signImg: '', // 签字
      timeColumns: [
        {
          values: this.createTimeList(23),
          defaultIndex: Number(moment().format('HH'))
        },
        {
          values: this.createTimeList(59),
          defaultIndex: Number(moment().format('mm'))
        },
        {
          values: this.createTimeList(59),
          defaultIndex: Number(moment().format('ss'))
        }
      ],
      timerPicker: false,
      selectTimeToSeconds: moment().format('HH:mm:ss'),
      verify: true,
      verify1: true,
      className: 'el_input_focus',
      className1: 'el_input_focus',
      internalValue1: '',
      show: false,
      show1: false,
      reminder: false,
      reminder1: false,
      addTime: '',
      activeName: 'a',
      imageList: [],
      rectifyImage: [],
      rectifyShow: false,
      imageShow: false,
      itemForm: {},
      dangerOperateRecordList: [],
      dangerImage: ''
    }
  },

  mounted () {
    console.log(this.$route.query.id, '这是id')
    this.getDangerItem()
  },

  methods: {
    getDangerItem () {
      getDangerItem(this.$route.query.id).then(({ data }) => {
        if (data.code === 200) {
          this.dangerOperateRecordList = []
          console.log(data.data)
          this.itemForm = data.data
          if (data.data.dangerImage) {
            this.imageList = data.data.dangerImage
              .split(',')
              .map(item => this.baseUrl + item)
          }
          if (data.data.rectifyImage) {
            this.rectifyImage = data.data.rectifyImage
              .split(',')
              .map(item => this.baseUrl + item)
          }

          if (this.itemForm.checkSignature) {
            this.itemForm.checkSignature = this.baseUrl + this.itemForm.checkSignature
          }
          data.data.dangerOperateRecordList.forEach((item, index) => {
            this.dangerOperateRecordList.push({
              operateUserName: item.operateUserName || '',
              operateNickName: item.operateNickName || '',
              statusDesc: item.statusDesc,
              operateTime: item.operateTime
                ? new Date(item.operateTime).toLocaleString()
                : '待完成'
            })
          })
        }
      })
    },
    // 删除签字
    delImg () {
      this.signImg = ''
    },
    // 签字
    toSign () {
      this.isSign = true
    },
    getSign (val) {
      this.signImg = val
      this.isSign = false
    },
    // 领取隐患
    claim () {
      receiveDanger(this.itemForm.id).then(({ data }) => {
        if (data.code === 200) {
          this.$notify({
            type: 'success',
            message: data.msg,
            duration: 1000
          })
          this.$router.go(-1)
        }
      })
    },
    // 审核驳回确认
    review () {
      dangerReview({
        dangerId: this.itemForm.id,
        remark: this.turnValue,
        type: 1
      }).then(({ data }) => {
        if (data.code === 200) {
          this.$notify({
            type: 'success',
            message: data.msg,
            duration: 1000
          })
          this.$router.go(-1)
        }
      })
    },
    // 审核通过
    pass () {
      dangerReview({ dangerId: this.itemForm.id, remark: '', type: 2 }).then(
        ({ data }) => {
          if (data.code === 200) {
            this.$notify({
              type: 'success',
              message: data.msg,
              duration: 1000
            })
            this.$router.go(-1)
          }
        }
      )
    },
    // 驳回弹框
    turnDown () {
      this.showDia = true
    },
    // 整改提交
    async add () {
      console.log('jinlaile', this.reminder)
      this.blur()
      this.blur1()
      if (this.$examine(this.rectify) === true) {
        if (this.reminder) return
        this.dangerImage = ''
        console.log('可以提交', this.rectify)
        for await (const item of this.rectify.fileList) {
          console.log(item.file)
          const formData = new FormData()
          formData.append('file', item.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
          }
        }
        console.log('走到这里了')
        submitDangerManage({
          rectificationTime: this.internalValue,
          controlMeasures: this.rectify.measures,
          cost: this.cost,
          dangerId: this.itemForm.id,
          rectifyImage: this.dangerImage
        }).then(({ data }) => {
          if (data.code === 200) {
            this.$notify({
              type: 'success',
              message: data.msg,
              duration: 1000
            })
            this.getDangerItem()
            this.activeName = 'b'
          }
        })
      } else {
        const list = this.$examine(this.rectify)
        console.log(list[1], '数据111111')
        this.rectify = { ...list[0] }
        setTimeout(() => {
          this.rectify = { ...list[1] }
        }, 0)
      }
    },
    // base64转file
    base64ToFile (base64) {
      const arr = base64.split(',')
      console.log(arr)
      console.log(arr[0].match(/:(.*?);/))
      const mime = arr[0].match(/:(.*?);/)[1]
      const suffix = mime.split('/')[1]
      const bstr = atob(arr[1])
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], `签字.${suffix}`, { type: suffix })
    },
    // 验收提交
    checkAdd () {
      this.typeNum = 2
      this.checks()
    },
    async checks () {
      this.blur()
      if (!this.signImg) {
        this.$notify({
          type: 'danger',
          message: '请先签字！',
          duration: 1000
        })
        return
      }
      if (this.reminder) return
      const formData = new FormData()
      console.log(this.base64ToFile(this.signImg))
      formData.append('file', this.base64ToFile(this.signImg))
      const { data } = await upload(formData)
      console.log(data)
      if (data.code === 200) {
        // if (!this.dangerImage) {
        //   this.dangerImage += data.fileName
        // } else {
        //   this.dangerImage += ',,' + data.fileName
        // }
        checkDangerManage({
          dangerId: this.itemForm.id,
          remark: this.remark,
          checkAcceptTime: this.internalValue,
          type: this.typeNum,
          sign: data.fileName
        }).then(({ data }) => {
          if (data.code === 200) {
            this.$notify({
              type: 'success',
              message: data.msg,
              duration: 1000
            })
            this.$router.go(-1)
          }
        })
      }
    },
    // 验收驳回
    checkDown () {
      this.typeNum = 1
      this.checks()
    },
    createTimeList (N) {
      const foo = []
      for (let i = 0; i <= N; i += 1) {
        if (i < 10) {
          foo.push(`0${i}`)
        } else {
          foo.push(i)
        }
      }
      return foo
    },
    confirmTime (value) {
      this.selectTimeToSeconds = `${value[0]}:${value[1]}:${value[2]}`
      this.timerPicker = false
    },
    onConfirm (date) {
      this.show = false
      this.internalValue = `${moment(date).format('YYYY-MM-DD')} ${
        this.selectTimeToSeconds
      }`
      if (this.verify) {
        if (this.internalValue) {
          this.className = 'el_input_focus1'
          this.reminder = false
        } else {
          this.reminder = true
          this.className = 'el_input_focusTrue'
        }
      } else {
        if (this.internalValue) {
          this.className = 'el_input_focus1'
        } else {
          this.className = 'el_input_focus'
        }
      }
    },
    focus () {
      this.show = true
      if (this.internalValue) {
        this.className = 'el_input_focus1'
      } else {
        this.className = 'el_input_blur'
      }
    },
    blur () {
      this.show = false
      if (this.verify) {
        if (this.internalValue) {
          this.className = 'el_input_focus1'
          this.reminder = false
        } else {
          this.reminder = true
          this.className = 'el_input_focusTrue'
        }
      } else {
        if (this.internalValue) {
          this.className = 'el_input_focus1'
        } else {
          this.className = 'el_input_focus'
        }
      }
    },

    onFinish1 ({ selectedOptions }) {
      this.show1 = false
      this.internalValue1 = selectedOptions[selectedOptions.length - 1].text
      console.log(this.cascaderValue)
      if (this.verify1) {
        if (this.internalValue1) {
          this.className1 = 'el_input_focus1'
          this.reminder1 = false
        } else {
          this.reminder1 = true
          this.className1 = 'el_input_focusTrue'
        }
      } else {
        if (this.internalValue1) {
          this.className1 = 'el_input_focus1'
        } else {
          console.log('走着了')
          this.className1 = 'el_input_focus'
        }
      }
    },
    focus1 () {
      this.show1 = true
      if (!this.internalValue1) {
        this.className1 = 'el_input_blur'
      }
    },
    blur1 () {
      this.show1 = false
      if (this.verify1) {
        if (this.internalValue1) {
          this.className1 = 'el_input_focus1'
          this.reminder1 = false
        } else {
          this.reminder1 = true
          this.className1 = 'el_input_focusTrue'
        }
      } else {
        if (this.internalValue1) {
          this.className1 = 'el_input_focus1'
        } else {
          this.className1 = 'el_input_focus'
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
.topText {
  margin-top: 20px !important;
}
.flowText {
  text-align: center;
  margin-top: 10px;
  span {
    border: 2px solid #1c4990;
    // background: #1c4990;
    color: #1c4990;
    border-radius: 3px;
    padding: 10px 20px;
    // font-weight: 600;
    font-size: 16px;
  }
  b {
    font-size: 20px;
    font-weight: 900;
    color: #1c4990;
  }
}
.tabTitle {
  color: #1c4990;
  padding: 10px 15px;
  font-weight: 600;
  margin-top: 10px;
  border-bottom: 1px solid #eee;
}
.textSign {
  padding: 15px 0 0 15px;
  color: #969799;
}
.textMain {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
  .center {
    padding: 0 15px;
    width: 100%;
    text-align: left;
    span {
      font-size: 12px;
      color: #969799;
    }
    p {
      margin-top: 5px;
      word-wrap: break-word;
    }
  }
  .left,
  .right {
    img {
      width: 100%;
      height: auto;
      margin-top: 5px;
    }
    padding: 0 15px;
    width: 50%;
    text-align: left;
    span {
      font-size: 12px;
      color: #969799;
    }
    p {
      margin-top: 5px;
      word-wrap: break-word;
    }
  }
  .right {
    border-left: 2px solid #eee;
  }
}
.textBox {
  margin-bottom: 20px;
}
.borderText {
  display: inline-block;
  border: 2px solid #1c4990;
  color: #1c4990;
  border-radius: 3px;
  padding: 5px 40px;
  // font-weight: 600;
  font-size: 16px;
  p {
    &:last-child {
      color: #969799;
      font-size: 13px;
      margin-top: 10px;
    }
  }
}
.borderText1 {
  display: inline-block;
  border: 2px solid red;
  color: red;
  border-radius: 3px;
  padding: 5px 40px;
  // font-weight: 600;
  font-size: 16px;
  p {
    &:last-child {
      color: red;
      font-size: 13px;
      margin-top: 10px;
    }
  }
}
.btns {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  button {
    margin: 20px;
  }
}
.sign {
  width: 100%;
  min-height: 200px;
  margin-top: 10px;
  .signImg {
    width: 100%;
    height: 150px;
    border: 1px solid #ccc;
    border-radius: 10px;
    opacity: 0.5;
    background: rgba(0, 0, 0, 0.2);
    img {
      width: 100%;
      height: 148px;
      border-radius: 10px;
      // transform: translate(0, -0.75rem) rotate(-90deg);
    }
  }
  .signBtn {
    margin-top: 5px;
    display: flex;
    justify-content: space-between;
    font-family: PingFangSC-Medium;
    color: #797979;
    letter-spacing: 0.17px;
    font-weight: 500;
  }
}
.check{
  color: red;
  padding: 10px;
  p{
    margin: 10px 0;
  }
  div{
    display: flex;
     img{
    width: 60%;
    border: 1px solid #ccc;
    border-radius: 4px;
  }
  }

}
.remark {
  width: 100%;
  padding: 20px 15px;
  color: red;
  p {
    margin-top: 10px;
  }
}
.time-picker {
  z-index: 2100 !important;
  display: flex;
  align-items: center;
  /deep/ .van-picker {
    width: 100%;
  }
}
</style>
