<template>
  <a-card :bordered="false" v-show="visible" class="card">
    <a-row :gutter="48" style="position:fixed;bottom:150px;z-index:999;display:flex; justify-content: center;width: 90%;">
      <a-col :md="48" :sm="48">
        <span>
          <a-button type="primary" @click="save()">保存</a-button>
          <a-button style="margin-left: 8px" type="default" @click="handleCancel()">返回</a-button>
        </span>
      </a-col>
    </a-row>
    <div>
      <div class="tables">
        <div style="text-align:center;padding-bottom:10px;font-size:32px;">时代思康检定表</div>
        <div style="display:flex; justify-content: space-between;">
          <div> 检定人：{{ username }}</div>
        </div>
        <table>
          <thead border="1px">
            <tr>
              <th width="100px">序号</th>
              <th width="150px">是否在库</th>
              <th width="150px">设备名称</th>
              <th width="150px">型号</th>
              <th width="150px">出厂编号</th>
              <!-- <th width="150px">是否是子设备</th>-->
              <th width="150px">设备位置</th>
              <th width="350px">选择父设备</th>
              <th width="150px">设备位号</th>
              <th width="150px">检定周期</th>
              <th width="150px">检定日期</th>
              <th width="150px">下次检定日期</th>
              <th width="150px">检定单号</th>
              <th width="150px">检定单位</th>
              <th width="150px">备注</th>
              <th width="150px">操作</th>
            </tr>
          </thead>
          <tbody v-if="ListForm.length>0">
            <tr v-for="(item,i) in ListForm" :key="item.id">
              <td>{{ i+1 }}</td>
              <td> <a-switch v-model="item.sbStatus" >
                <a-icon slot="checkedChildren" type="check" />
                <a-icon slot="unCheckedChildren" type="close" />
              </a-switch></td>
              <td>{{ item.sbName }}</td>
              <td>{{ item.sbModel }}</td>
              <td><div> {{ item.zzh }}</div></td>
              <!--              <td>
                <a-switch v-model="item.isChild" >
                  <a-icon slot="checkedChildren" type="check" />
                  <a-icon slot="unCheckedChildren" type="close" />
                </a-switch>
              </td>-->
              <td>
                <div v-if="item.sbStatus">{{ item.sbPositionName }}</div>
                <a-tree-select
                  v-else
                  style="width: 150px"
                  :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                  :treeData="treeData"
                  :treeNodeFilterProp="'title'"
                  :showSearch="true"
                  v-model="item.sbPositionId"
                  @change="handleSbPosition(item)"
                  placeholder="请选择"
                >
                </a-tree-select>
              </td>
              <td>
                <div v-if="!item.sbStatus" style="width:250px">
                  <a-input
                    disabled
                    style="width: 60%"
                    v-model="item.parentSbName"/>
                  <a-button type="primary" @click="handleSbSelect(item.sbPositionId,i)">选择</a-button>
                </div>
                <div v-else>无</div>
              </td>
              <td>
                <div v-if="item.sbStatus"> {{ item.sbPositionNo }}</div>
                <div v-else style="width:250px">
                  <a-input
                    style="width: 60%"
                    v-model="item.sbPositionNo"/>
                  <a-button v-if="item.isChild === 1" type="primary" @click="handleSbNoSelect(item.sbParentId,i)">选择</a-button>
                </div>
              </td>
              <td><a-input v-model="item.checkPeriod" suffix="月" /></td>
              <td>
                <a-date-picker
                  placeholder="日期"
                  style="width: 150px"
                  :format="BaseTool.Date.PICKER_NORM_DATE_PATTERN"
                  v-model="item.lastDate" />
              </td>
              <td>{{ validity(item.lastDate,item.checkPeriod) }}</td>
              <td><a-input style="width: 150px" v-model="item.no" /></td>
              <td><a-input style="width: 150px" v-model="item.requirement" /></td>
              <td><a-input style="width: 150px" v-model="item.remark" /></td>
              <td>
                <a-button type="link" @click="uploadImg(item,i)">上传图片</a-button>
                <a-button type="link" @click="uploadFile(item,i)">上传文件</a-button>
                <a-modal v-model="uploadVisible" title="上传图片" :footer="null" @cancel="uploadVisible = false">
                  <a-upload
                    :action="uploadUrl"
                    list-type="picture-card"
                    :file-list="defaultApplicationFileList"
                    @change="handleApplicationFileChange"
                    @preview="handlePreview"
                    accept="image/*"
                    :headers="headers"
                  >
                    <div>
                      <a-icon type="plus" />
                      <div class="ant-upload-text">
                        Upload
                      </div>
                    </div>
                  </a-upload>
                </a-modal>
                <a-modal v-model="uploadFiledVisible" title="上传文件" :footer="null" @cancel="uploadFiledVisible = false">
                  <a-upload
                    :action="uploadUrl"
                    :multiple="true"
                    :file-list="defaultCheckFileList"
                    @change="handleCheckFileChange"
                    :headers="headers"
                  >
                    <a-button> <a-icon type="upload" /> 上传 </a-button>
                  </a-upload>
                </a-modal>
                <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false" @ok="previewVisible = false">
                  <img alt="example" style="width: 100%" :src="previewImage" />
                </a-modal>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    <sb-info-select-modal ref="sbInfoSelectModal" @selected="handleSbSelectd"/>
    <sb-position-no-modal ref="sbPositionNoModal" @selected="handleSbNoSelectd"/>

  </a-card>
</template>

<script>
import { getSbPositionTree } from '@/api/sb/position'
import SbInfoSelectModal from '@/views/sb/info/modules/SbInfoSelectModal'
import SbPositionNoModal from '@/views/sb/location/modules/LocationSelectModal'
import { importMeasureInStore } from '@/api/sb/info'

import { uploadUrl } from '@/api/upms/file'
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'

export default {
  name: 'BaseFillGatherTask',
  components: {
    SbInfoSelectModal,
    SbPositionNoModal
  },
  data () {
    return {
      uploadUrl: uploadUrl,
      defaultApplicationFileList: [],
      defaultCheckFileList: [],
      checkFileList: [], // 文档
      applicationFileList: [],
      headers: {
        Authorization: 'Bearer ' + Vue.ls.get(ACCESS_TOKEN)
      },
      visible: false,
      username: this.$store.getters.userInfo.username,
      uploadVisible: false,
      uploadFiledVisible: false,
      previewVisible: false,
      previewImage: '',
      treeData: [],
      sbParentOPt: 0,
      model: {},
      listPage: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      imgId: '',
      fileId: '',
      ListForm: [],
      id: '',
      updatesInfo: []
      // 下拉框map
    }
  },
  props: {
  },
  created () {
    // 下拉框map

  },
  methods: {
    validity (lastDate, checkPeriod) {
      if (lastDate === '') return ''
      lastDate = this.BaseTool.Date.formatter(lastDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN).split('-')
      lastDate[1] = (parseInt(lastDate[1]) + parseInt(checkPeriod)) % 12
      lastDate[0] = +lastDate[0] + Math.floor((parseInt(lastDate[1]) + parseInt(checkPeriod)) / 12)
      if (lastDate[1] === 0) {
        lastDate[1] = 12
      }
      return lastDate.join('-')
    },
    base (record, type) {
      this.visible = true
      this.model = record
      this.ListForm = record.map(item => {
        const data = {
          sbName: item.name,
          sbModel: item.model,
          checkPeriod: item.checkPeriod || 0,
          isChild: item.isChild,
          parentSbName: item.parentSbName,
          sbParentId: item.parentId,
          sbPositionId: item.positionId,
          sbPositionName: item.positionName,
          no: '',
          lastDate: '',
          sbStatus: false,
          sbPositionNo: item.positionNo,
          requirement: '',
          remark: '',
          name: this.username,
          sbId: item.id,
          type,
          zzh: item.zzh,
          checkImgList: [],
          checkFileList: []
        }
        return data
      })
      getSbPositionTree().then(res => {
        this.treeData = res.data
      })
    },
    handleSbPosition (item) {
      item.parentSbName = ''
      item.sbParentId = ''
      item.sbPositionNo = ''
    },
    handleSbSelect (positionId, i) {
      if (positionId === '' || positionId === null) {
        this.$message.warning('请选择设备位置!')
        return
      }
      this.sbParentOPt = i
      this.$refs.sbInfoSelectModal.base({}, { isChild: this.DictCache.VALUE.SB_IS_CHILD.IS_PARENT, positionId })
    },
    handleSbNoSelect (sbId, i) {
      if (sbId === '' || sbId === null) {
        this.$message.warning('请选择父设备!')
        return
      }
      this.sbParentOPt = i
      this.$refs.sbPositionNoModal.base({ sbId })
    },
    handleSbSelectd (keys, rows) {
      console.log(keys, rows)
      this.ListForm[ this.sbParentOPt ].sbParentId = keys[0]
      this.ListForm[ this.sbParentOPt ].parentSbName = rows[0].name
      this.ListForm[ this.sbParentOPt ].sbPositionNo = ''
    },
    handleSbNoSelectd (keys, rows) {
      console.log(keys, rows)
      this.ListForm[ this.sbParentOPt ].sbPositionNo = rows[0].no
    },
    uploadFile (val, i) {
      this.uploadFiledVisible = true
      this.fileId = i
      console.log(val)
      this.defaultCheckFileList = this.BaseTool.UPLOAD.transImg(val.checkFileList)
    },
    uploadImg (val, i) {
      this.uploadVisible = true
      console.log(val)
      this.imgId = i
      this.defaultApplicationFileList = this.BaseTool.UPLOAD.transImg(val.checkImgList)
    },
    getBase64 (file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => resolve(reader.result)
        reader.onerror = error => reject(error)
      })
    },
    async handlePreview (file) {
      if (!file.url && !file.preview) {
        file.preview = await this.getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleApplicationFileChange (info) {
      this.defaultApplicationFileList = info.fileList
      this.applicationFileList = this.setFileList(info, 11)
      this.ListForm[this.imgId].checkImgList = this.applicationFileList
    },
    handleCheckFileChange (info) {
      this.defaultCheckFileList = info.fileList
      this.checkFileList = this.setFileList(info, 32)

      this.ListForm[this.fileId].checkFileList = this.checkFileList
      console.log(this.checkFileList)
    },
    setFileList (info, type) {
      const file = info.file
      const fileList = info.fileList
      if (file.status === 'done') {
        return this.BaseTool.UPLOAD.getUploadFileDTO(fileList, type)
      } else if (file.status === 'removed') {
        return this.BaseTool.UPLOAD.getUploadFileDTO(fileList, type)
      } else if (file.status === 'error') {
        this.$message.error('上传失败')
        return []
      }
    },
    save () {
      let status = false
      this.ListForm.forEach(item => {
        switch (true) {
          case item.sbStatus || (item.requirement === '' && (item.lastDate === '' || item.lastDate === null)) :
            break
          case item.requirement === '':
            this.$message.warning(item.sbName + '的检定单位不能为空！')
            status = true
            break
          case item.lastDate === '' || item.lastDate === null:
            this.$message.warning(item.sbName + '的检定日期不能为空！')
            status = true
            break
        }
        item.lastDate = item.lastDate !== '' && item.lastDate !== null ? this.BaseTool.Date.formatter(item.lastDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN) : ''
        item.checkFileList.forEach(item => {
          item.id = null
        })
        item.checkImgList.forEach(item => {
          item.id = null
        })
      })
      if (status) return
      const params = {
        sbMeasureLogDTOList: this.ListForm.filter(item => !(!item.sbStatus && item.requirement === '' && item.lastDate === ''))
      }
      console.log(params)
      importMeasureInStore(params).then(res => {
        this.$message.success('检定完成！')
        this.handleCancel()
      })
    },
    handleCancel () {
      this.visible = false
      this.ListForm = []
      this.$emit('ok')
    }
  }
}
</script>
<style lang="less" scoped>
.tables{
  margin: 20px 0px;
  width: 100%;
  overflow-x:auto;
  table {
    min-width:100%;
    margin: 0 auto;
    border: 1px solid #D6D6D6;
    border-collapse: collapse;
    font-size: 16px;
    font-weight: 400;
    table-layout:fixed;
  }
  th{
    background: #fafafa;
    font-weight: 500;

  }
  th,
  td {
    border: 1px solid #D6D6D6;
    text-align: center;
    padding: 5px 10px;
    white-space: nowrap;
  }
}
</style>
