<template>
  <div class="container">
    <Header title="作业详情" />
    <van-tabs
      background="#1c4990"
      color="#fff"
      title-inactive-color="#dcdee0"
      title-active-color="#fff"
      line-width="80px"
      style="height: calc(100% - 50px); overflow: hidden;"
      swipeable
      animated
      :ellipsis="false"
      @click="onClick"
    >
      <van-tab
        v-for="(item, index) in tabList"
        :title="item.title"
        :disabled="
          item.show && !item.arr.includes(workticketData.workTicketStatus)
        "
        :key="index"
      >
        <job-information
          v-show="index === 0"
          @previewPicture="previewPicture"
        ></job-information>
        <!-- <operating-personnel v-show="index === 1"></operating-personnel> -->
        <!-- <gas-analysis v-show="index === 1"></gas-analysis> -->
        <div class="job-infrom" v-show="index === 1">
          <div
            style="margin-left: 16px;"
            class="item-button"
            v-if="workticketData.workTicketStatus === '40'"
          >
            <van-button type="info" @click="isShow = true">气体录入</van-button>
          </div>
          <div
            v-for="(item, index) in workTicketGasAnalysisDTOList"
            :key="index"
          >
            <div class="item-text">
              <div class="text">
                <span>检测时间</span>
                <span>{{ item.sampleTime }}</span>
              </div>
            </div>
            <div class="item-text">
              <div class="text">
                <span>检测人</span>
                <span>{{ item.inspectorate }}</span>
              </div>
              <div class="line"></div>
              <div class="text">
                <span>分析位置/部位</span>
                <span>{{ item.analysisLocation }}</span>
              </div>
            </div>
            <div class="item-text">
              <div class="text">
                <span>氧气(%)</span>
                <span>{{ item.o2 }}</span>
              </div>
              <div class="line"></div>
              <div class="text">
                <span>可燃气(%)</span>
                <span>{{ item.ca }}</span>
              </div>
            </div>
            <div class="item-text">
              <div class="text">
                <span>硫化氢(%)</span>
                <span>{{ item.h2s }}</span>
              </div>
              <div class="line"></div>
              <div class="text">
                <span>一氧化碳(%)</span>
                <span>{{ item.co }}</span>
              </div>
            </div>
          </div>
        </div>
        <div v-show="index === 2" class="action-confirm">
          <div class="table_content">
            <table border="1" rules="all">
              <thead>
                <tr>
                  <th>序号</th>
                  <th>安全措施</th>
                  <th>是否涉及</th>
                  <th v-if="isGuardian">操作</th>
                </tr>
              </thead>
              <tbody id="tbody">
                <tr
                  v-for="(item, index) in workTicketSmOptionRunDTOList"
                  :key="index"
                >
                  <td>{{ index + 1 }}</td>
                  <td>{{ item.smOptionName }}</td>
                  <td>
                    <van-radio-group
                      v-model="item.smOptionState"
                      direction="horizontal"
                      :disabled="!!workTicketDiscloseUserSignImg && !!workTicketAcceptUserSignImg"
                    >
                      <van-radio checked-color="#1c4990" name="1">是</van-radio>
                      <van-radio checked-color="#1c4990" name="0">否</van-radio>
                    </van-radio-group>
                  </td>
                  <td v-if="isGuardian"></td>
                </tr>
                <tr
                  v-for="(item, index) in addSafetyList"
                  :key="workTicketSmOptionRunDTOList.length + 1 + index"
                >
                  <td>{{ workTicketSmOptionRunDTOList.length + 1 + index }}</td>
                  <td>
                    <van-field
                      rows="1"
                      autosize
                      v-model="item.smOptionName"
                      type="textarea"
                      placeholder="请输入"
                    />
                  </td>
                  <td>
                    <van-radio-group
                      v-model="item.smOptionState"
                      direction="horizontal"
                      :disabled="!!workTicketDiscloseUserSignImg && !!workTicketAcceptUserSignImg"
                    >
                      <van-radio checked-color="#1c4990" name="1">是</van-radio>
                      <van-radio checked-color="#1c4990" name="0">否</van-radio>
                    </van-radio-group>
                  </td>
                  <td v-if="isGuardian" @click="delSafety(index)">删除</td>
                </tr>
              </tbody>
            </table>
            <div v-if="isGuardian" class="item-button">
              <van-button type="info" @click="addSafety">添加</van-button>
            </div>
            <div class="sign">
              <div class="sign-title">安全交底人：</div>
              <div class="sign_img">
                <van-image
                  v-if="workTicketDiscloseUserSignImg"
                  :src="baseUrl + workTicketDiscloseUserSignImg"
                  width="100%"
                  height="100%"
                />
              </div>
              <div class="sign_facility" v-if="isGuardian && !workTicketDiscloseUserSignImg">
                <div @click="handleIsgn('workTicketDiscloseUserSignImg')">
                  <van-icon name="edit" size="18" style="margin-right:.03rem" />
                  <span>去签字 </span>
                </div>
              </div>
            </div>
            <div class="sign">
              <div class="sign-title">接受交底人：</div>
              <div class="sign_img">
                <van-image
                  v-if="workTicketAcceptUserSignImg"
                  :src="baseUrl + workTicketAcceptUserSignImg"
                  width="100%"
                  height="100%"
                />
              </div>
              <div class="sign_facility" v-if="isOperator && !workTicketAcceptUserSignImg">
                <div @click="handleIsgn('workTicketAcceptUserSignImg')">
                  <van-icon name="edit" size="18" style="margin-right:.03rem" />
                  <span>去签字 </span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="start" v-show="index === 3">
          <div class="start-title">
            启动签字流程
          </div>
          <div
            class="sign"
            v-for="(item, index) in workTicketSignOptionRunDTOList"
            :key="index"
          >
            <div class="sign-title">{{ item.workTicketSignOption }}：</div>
            <div class="sign_img">
              <van-image
                v-if="item.workSignOptionUserImg"
                :src="baseUrl + item.workSignOptionUserImg"
                width="100%"
                height="100%"
              />
            </div>
            <div
              class="sign_facility"
              v-if="
                isCountersign(item.userSignList) && !item.workSignOptionUserImg
              "
            >
              <div @click="handleCountersign(index, item.id)">
                <van-icon name="edit" size="18" style="margin-right:.03rem" />
                <span>去签字 </span>
              </div>
            </div>
          </div>
          <div class="start-title">
            完工验收
          </div>
          <div class="sign">
            <div class="sign-title">验收人：</div>
            <div class="sign_img">
              <van-image
                v-if="workTicketCheckUserSignImg"
                :src="baseUrl + workTicketCheckUserSignImg"
                width="100%"
                height="100%"
              />
            </div>
            <div class="sign_facility" v-if="isCompletionTest">
              <div @click="handleOperator('workTicketCheckUserSignImg')">
                <van-icon name="edit" size="18" style="margin-right:.03rem" />
                <span>去签字 </span>
              </div>
            </div>
          </div>
        </div>
        <process-information
          v-show="index === 4"
          :workFlowList="workFlowList"
        ></process-information>
      </van-tab>
    </van-tabs>
    <Signature v-if="isSign" @getSign="getSign" />
    <van-image-preview
      v-model="imageShow"
      :images="imageList"
      :closeable="true"
      :loop="false"
      :closeOnPopstate="true"
    />
    <van-popup
      v-model="isShow"
      position="bottom"
      round
      :style="{ height: '80%' }"
      closeable
    >
      <div style="height: 40px;"></div>
      <van-form validate-first @submit="onSubmit" label-width="120">
        <!-- 通过 pattern 进行正则校验 -->
        <van-field
          v-model="gasAnalysisData.inspectorate"
          label="检测人"
          name="检测人"
          placeholder="检测人"
          :rules="[{ required: true, message: '请填写' }]"
        />
        <van-field
          readonly
          clickable
          name="检测时间"
          :value="gasAnalysisData.sampleTime"
          label="检测时间"
          placeholder="点击选择日期"
          @click="showCalendar = true"
          :rules="[{ required: true, message: '请填写' }]"
        />
        <van-field
          v-model="gasAnalysisData.analysisLocation"
          label="分析位置/部位"
          name="分析位置/部位"
          placeholder="分析位置/部位"
          :rules="[{ required: true, message: '请填写' }]"
        />
        <van-field
          v-model="gasAnalysisData.o2"
          label="氧气(%)"
          name="pattern"
          placeholder="氧气(%)"
          :rules="[{ pattern, message: '输入只包含数字和小数点' }]"
        />
        <van-field
          v-model="gasAnalysisData.ca"
          label="可燃气(%)"
          name="pattern"
          placeholder="可燃气(%)"
          :rules="[{ pattern, message: '输入只包含数字和小数点' }]"
        />
        <van-field
          v-model="gasAnalysisData.h2s"
          label="硫化氢(%)"
          name="pattern"
          placeholder="硫化氢(%)"
          :rules="[{ pattern, message: '输入只包含数字和小数点' }]"
        />
        <van-field
          v-model="gasAnalysisData.co"
          label="一氧化碳(%)"
          name="pattern"
          placeholder="一氧化碳(%)"
          :rules="[{ pattern, message: '输入只包含数字和小数点' }]"
        />
        <div style="margin: 16px;">
          <van-button
            :disabled="isDisabled"
            style="background-color: #1c4990;border-color: #1c4990;"
            round
            block
            type="info"
            native-type="submit"
            >提交</van-button
          >
        </div>
      </van-form>
    </van-popup>
    <div class="container1">
      <van-calendar
        v-model="showCalendar"
        :show-confirm="true"
        @confirm="onConfirm"
        color="#1c4990"
        class="calendar"
        :default-date="defaultDate"
        :close-on-click-overlay="false"
      >
        <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="选择时间"
          @cancel="timerPicker = false"
          :columns="timeColumns"
          @confirm="confirmTime"
        />
      </van-overlay>
    </div>
  </div>
</template>

<script>
import jobInformation from './jobInformation.vue'
import processInformation from './processInformation.vue'
import Signature from '@/components/signature'
import { mapState } from 'vuex'
import {
  addWorkTicketGasAnalysis,
  workSignOptionRun,
  checkWorkTicketMeasureV2,
  acceptance,
  getOperateRecord
} from '@/api/jobReservation.js'
import { upload } from '@/api/danger.js'
import moment from 'moment'
export default {
  name: 'LicenseDetails',
  components: {
    jobInformation,
    processInformation,
    Signature
  },
  data () {
    return {
      workFlowList: [],
      workSignOptionRunId: '',
      countersignIndex: '',
      isDisabled: false,
      defaultDate: new Date(),
      selectTimeToSeconds: moment().format('HH:mm:ss'),
      pattern: /^[0-9]*\.?[0-9]+$/,
      showCalendar: false,
      timerPicker: false,
      isShow: false,
      workTicketSmOptionRunDTOList: [],
      workTicketSignOptionRunDTOList: [],
      workTicketGasAnalysisDTOList: [],
      isSign: false,
      imageShow: false,
      workTicketDiscloseUserSignImg: '',
      workTicketAcceptUserSignImg: '',
      workTicketCheckUserSignImg: '',
      addSafetyList: [],
      isMeasuresUserShow: true,
      isUserSignImgShow: true,
      type: '',
      imageList: [],
      tabList: [
        { title: '作业信息', show: false, arr: [] },
        { title: '气体分析', show: true, arr: ['40', '50'] },
        { title: '措施确认', show: false, arr: [] },
        { title: '启动与验收', show: true, arr: ['30', '40', '50'] },
        { title: '流程信息', show: false, arr: [] }
      ],
      gasAnalysisData: {
        analysisLocation: '',
        ca: 0,
        co: 0,
        h2s: 0,
        id: '',
        o2: 0,
        sampleTime: '',
        inspectorate: ''
      },
      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'))
        }
      ]
    }
  },
  watch: {
    '$store.state.dangerList.workticketData': {
      deep: true,
      handler: function () {
        this.getDetails()
      }
    }
  },
  computed: {
    ...mapState('baseUrl', ['baseUrl']),
    ...mapState('login', ['user']),
    ...mapState('dangerList', ['workticketData']),
    // 安全交底人
    isGuardian () {
      return (
        this.user.userId === this.workticketData.workTicketDirectorId &&
        this.workticketData.workTicketStatus === '10'
      )
    },
    // 接受交底人
    isOperator () {
      return (
        this.user.userId === this.workticketData.workTicketDirectorId &&
        this.workticketData.workTicketStatus === '10'
      )
    },
    // 会签
    isCountersign () {
      return arr => {
        const list = Array.isArray(arr) ? arr.map(item => item.userId) : []
        return (
          list.includes(this.user.userId) &&
          this.workticketData.workTicketStatus === '30'
        )
      }
    },
    // 完工
    isCompletionTest () {
      return (
        this.user.userId === this.workticketData.workTicketDirectorId &&
        this.workticketData.workTicketStatus === '40'
      )
    }
  },
  created () {
    this.getDetails()
  },
  methods: {
    onClick (type) {
      if (type === 4) {
        getOperateRecord(this.workticketData.id).then(({ data }) => {
          if (data.code === 200) {
            this.workFlowList = data.data
          }
        })
      }
    },
    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.gasAnalysisData.sampleTime = `${moment(date).format('YYYY-MM-DD')} ${
        this.selectTimeToSeconds
      }`
      this.showCalendar = false
    },
    onSubmit () {
      this.isDisabled = true
      const params = {
        ...this.gasAnalysisData,
        workTicketId: this.workticketData.id,
        ca: parseFloat(this.gasAnalysisData.ca),
        co: parseFloat(this.gasAnalysisData.co),
        h2s: parseFloat(this.gasAnalysisData.h2s),
        o2: parseFloat(this.gasAnalysisData.o2)
      }
      addWorkTicketGasAnalysis(params)
        .then(({ data }) => {
          if (data.code === 200) {
            this.$notify({
              type: 'success',
              message: '已提交',
              duration: 1000
            })
            this.isDisabled = false
            this.isShow = false
            this.$store.dispatch(
              'dangerList/getWorkticketData',
              this.workticketData.id
            )
            setTimeout(() => {
              this.getDetails()
            }, 100)
          } else {
            this.isDisabled = false
          }
        })
        .finally(() => {
          this.isDisabled = false
        })
    },
    addSafety () {
      this.addSafetyList.push({
        smOptionName: '',
        smOptionState: '',
        workTicketId: this.workticketData.id,
        workTicketType: this.workticketData.workTicketType
      })
    },
    delSafety (index) {
      this.$dialog({
        message: '是否删除？',
        showCancelButton: true
      })
        .then(() => {
          this.addSafetyList.splice(index, 1)
        })
        .catch(() => {})
    },
    getSign (img) {
      if (
        [
          'workTicketDiscloseUserSignImg',
          'workTicketAcceptUserSignImg',
          'workTicketCheckUserSignImg'
        ].includes(this.type)
      ) {
        this.actionConfirmation(img)
      } else {
        this.workSignOptionRun(img)
      }
      this.isSign = false
    },
    previewPicture (list) {
      this.imageShow = true
      this.imageList = list
    },
    delImg () {
      this.$dialog({
        message: '确定要清除签名吗？',
        showCancelButton: true
      })
        .then(() => {
          this.img = ''
        })
        .catch(() => {})
    },
    handleIsgn (type) {
      const num = []
      const arr = this.workTicketSmOptionRunDTOList.concat(this.addSafetyList)
      arr.forEach((item, index) => {
        if (!item.smOptionState || !item.smOptionName) num.push(index + 1)
      })
      if (num.length) {
        this.$notify({
          type: 'primary',
          message: `第${num.join(',')}项安全措施/是否涉及不能为空！！！`,
          duration: 3000
        })
        return
      }
      this.isSign = true
      this.type = type
    },
    handleOperator (type) {
      this.isSign = true
      this.type = type
    },
    handleCountersign (index, id) {
      this.countersignIndex = index
      this.isSign = true
      this.workSignOptionRunId = id
      this.type = ''
    },
    getDetails () {
      this.workTicketSmOptionRunDTOList = this.workticketData.workTicketSmOptionRunDTOList
      this.workTicketSignOptionRunDTOList = this.workticketData.workTicketSignOptionRunDTOList
      this.workTicketGasAnalysisDTOList = this.workticketData.workTicketGasAnalysisDTOList
      this.workTicketDiscloseUserSignImg = this.workticketData.workTicketDiscloseUserSignImg
      this.workTicketAcceptUserSignImg = this.workticketData.workTicketAcceptUserSignImg
      this.workTicketCheckUserSignImg = this.workticketData.workTicketCheckUserSignImg
    },
    async actionConfirmation (img) {
      if (!img) {
        this.$notify({
          type: 'danger',
          message: '请先签字！',
          duration: 1000
        })
        return
      }
      const signImg = await this.upload(img)
      this[this.type] = signImg
      const request = {
        workTicketDiscloseUserSignImg: checkWorkTicketMeasureV2,
        workTicketAcceptUserSignImg: checkWorkTicketMeasureV2,
        workTicketCheckUserSignImg: acceptance
      }
      let params = {
        workTicketId: this.workticketData.id,
        signImg
      }
      if ([
        'workTicketDiscloseUserSignImg',
        'workTicketAcceptUserSignImg'
      ].includes(this.type)) {
        const workTicketStatus = this.type === 'workTicketDiscloseUserSignImg' ? 10 : 20
        // const isOption = this.addSafetyList.length > 0 ? 1 : 0
        if (this.addSafetyList.length) {
          this.addSafetyList.forEach(item => {
            item.isOption = 1
          })
        }
        const arr = this.workTicketSmOptionRunDTOList.concat(
          this.addSafetyList
        )
        params = {
          ...params,
          workTicketSmOptionRunDTOList: arr,
          workTicketStatus
        }
      }
      const { data } = await request[this.type](params)
      if (data.code === 200) {
        this.$notify({
          type: 'success',
          message: '签字成功',
          duration: 1000
        })
        this.$store.dispatch(
          'dangerList/getWorkticketData',
          this.workticketData.id
        )
        setTimeout(() => {
          this.getDetails()
        }, 100)
        this.addSafetyList = []
      } else {
        this.$notify({
          type: 'danger',
          message: data.msg,
          duration: 1000
        })
        this[this.type] = ''
      }
    },
    async workSignOptionRun (img) {
      const signImg = await this.upload(img)
      this.workTicketSignOptionRunDTOList[
        this.countersignIndex
      ].workSignOptionUserImg = signImg
      const params = {
        workTicketId: this.workticketData.id,
        workSignOptionRunId: this.workSignOptionRunId,
        signImg
      }
      const { data } = await workSignOptionRun(params)
      if (data.code === 200) {
        this.$notify({
          type: 'success',
          message: '签字成功',
          duration: 1000
        })
        this.$store.dispatch(
          'dangerList/getWorkticketData',
          this.workticketData.id
        )
        setTimeout(() => {
          this.getDetails()
        }, 100)
      } else {
        this.$notify({
          type: 'danger',
          message: data.msg,
          duration: 1000
        })
        this.workTicketSignOptionRunDTOList[
          this.countersignIndex
        ].workSignOptionUserImg = ''
      }
    },
    async upload (img) {
      const files = new window.File([this.dataURLtoBlob(img)], '图片.jpg', {
        type: 'jpg'
      }) // 转成file类型
      const formData = new FormData()
      formData.append('file', files)
      const { data } = await upload(formData)
      if (data.code === 200) {
        return data.fileName
      }
    },
    // 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 })
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .van-tabs__content {
  height: calc(100% - 44px);
}
/deep/ .van-tab__pane {
  height: calc(100%);
  overflow: auto;
}
/deep/ .van-tab--disabled {
  color: #646566 !important;
  cursor: not-allowed;
}
.action-confirm {
  padding: 16px;
  .table_content {
    width: 100%;
    height: 100%;
    font-size: 14px;
    // border: #333;
    table {
      width: 100%;
      text-align: center;
      margin: 10px 0px;
      line-height: 30px;
      thead,
      tbody {
        border: #d9d9d9;
      }
      thead {
        background: #1956b5;
        height: 40px;
        color: #fff;
      }
      tbody {
        tr {
          > :nth-child(1) {
            width: 40px;
          }
          > :nth-child(2) {
            padding: 0 8px;
            text-align: left;
          }
          > :nth-child(3) {
            width: 140px;
            padding-left: 8px;
          }
          > :nth-child(4) {
            width: 40px;
          }
        }
      }
    }
  }
}
.sign_facility {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
  div {
    width: 100px;
    display: flex;
    align-items: center;
  }
  :last-child {
    display: flex;
    justify-content: flex-end;
  }
}
.sign-title {
  color: #969799;
  text-align: left;
  margin-bottom: 10px;
}
.sign_img {
  width: 100%;
  height: 153px;
  opacity: 0.5;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 10px;
  border: 1px solid #ccc;
  overflow: hidden;
  margin-bottom: 10px;
  img {
    width: 100%;
    height: 150px;
  }
}
.start {
  padding: 16px;
  font-size: 14px;
  .start-title {
    height: 30px;
    line-height: 30px;
    text-align: left;
    font-weight: 600;
    border-bottom: solid 1px #eee;
    color: #1c4990;
    margin-bottom: 10px;
  }
}
.job-infrom {
  padding: 16px 16px 16px 0px;
  .item-text {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    height: auto;
    .line {
      height: inherit;
      width: 2px;
      background: #eee;
    }
    .text {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: start;
      margin-left: 16px;
      span {
        text-align: left;
      }
      > :nth-child(1) {
        color: #969799;
        margin-bottom: 6px;
        font-size: 14px;
      }
    }
  }
}
.item-button {
  display: flex;
  justify-content: flex-start;
  margin-bottom: 10px;
  .van-button--info {
    background-color: #1c4990;
    border-color: #1c4990;
  }
}
.container1 {
  .time-picker {
    z-index: 2100 !important;
    display: flex;
    align-items: center;
    /deep/ .van-picker {
      width: 100%;
    }
  }
}
</style>
