<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 v-show="editor" :loading="confirmLoading" type="primary" @click="save()">保存</a-button>
          <a-button style="margin-left: 8px" type="default" @click="handleCancel()">返回</a-button>
          <a-button
            style="margin-left: 8px"
            type="primary"
            v-show="!editor&&model.status == 2 "
            @click="handleVerify(model)"
          > 审核</a-button>
          <a-button
            v-if="$auth('fill-tasks-dispatch')"
            v-show="!editor&&model.status!== 6&&model.status!== 2"
            style="margin-left: 8px"
            type="primary"
            @click="handleDispatch(model)"
          >转派</a-button>
          <a-button
            v-if="$auth('fill-tasks-overtime')"
            v-show="!editor&&model.status!== 2&&model.status!== 6"
            style="margin-left: 8px"
            type="primary"
            @click="handleOvertime(model)"
          >延时</a-button>

          <a-button
            v-if="$auth('fill-tasks-pause')"
            v-show="!editor && model.status===5&&model.status!== 2&&model.status!== 6"
            style="margin-left: 8px"
            type="primary"
            @click="handlePause(model)"
          >取消暂停</a-button>
          <a-button
            v-if="$auth('fill-tasks-pause')"
            v-show="!editor&& model.status!==5&&model.status!== 2&&model.status!== 6"
            style="margin-left: 8px"
            type="primary"
            @click="handlePause(model)"
          >暂停</a-button>
        </span>
      </a-col>
    </a-row>
    <a-button-group size="large" v-show="!editor" >
      <a-button @click="type=1">
        <a-icon type="left" />巡检记录
      </a-button>
      <a-button @click="type=2">
        任务追踪<a-icon type="right" />
      </a-button>
    </a-button-group>
    <div v-show="type===1">
      <div class="tables">
        <a-radio-group :value="status" @change="handleStatusChange">
          <a-radio-button :value="null">
            全部
          </a-radio-button>
          <a-radio-button :value="0">
            未填报
          </a-radio-button>
          <a-radio-button :value="1">
            已填报
          </a-radio-button>
        </a-radio-group>
        <div style="text-align:center;padding-bottom:10px;font-size:32px;">时代思康巡检记录表</div>
        <div v-show="!editor" style="display:flex; justify-content: space-between;">
          <div> 巡检开始时间：{{ model.createdTime }}</div>
          <div> 巡检要求时间：{{ model.requireHour }}小时</div>
          <div> 巡检预警时间：{{ model.warningHour }}小时</div>
          <div> 巡检完成时间：{{ model.updateTime }}</div>
          <div> 巡检人：{{ model.checkerName }}</div>

        </div>
        <table>
          <thead border="1px">
            <tr>
              <th rowspan="2" width="100px">序号</th>
              <th rowspan="2" width="150px">车间</th>
              <th rowspan="2" width="150px">设备名称</th>
              <th rowspan="2" width="150px">设备编号</th>
              <th rowspan="2" width="150px">填报时间</th>
              <th :colspan="ListForm.length>0?ListForm[0].content.length:1">项目内容项</th>
              <th rowspan="2" width="150px">是否填报</th>
              <th rowspan="2" width="150px" v-if="editor">操作</th>
            </tr>
            <tr v-if="ListForm.length>0">
              <th v-for="item in ListForm[0].content" :key="item.name">{{ item.name }}</th>
            </tr>
          </thead>
          <tbody v-if="ListForm.length>0">
            <tr v-for="(item,i) in ListForm" :key="item.id">
              <td>{{ i+1 }}</td>
              <td>{{ item.positionName }}</td>
              <td>{{ item.sbName }}</td>
              <td>{{ item.sbNo }}</td>
              <td>{{ item.updateTime }}</td>
              <td v-for="li in item.content" :key="li.name">
                <span v-if="!editor" > {{ li.fillValue }}</span>
                <a-input v-else-if="li.type === 1 && editor " v-model="li.fillValue" />
                <a-select v-else-if="li.type === 2 && editor" v-model="li.fillValue" style="min-width:100px;">
                  <a-select-option v-for="val in JSON.parse(li.selectValue)" :key="val.value" :value="val.value">
                    {{ val.value }}
                  </a-select-option>
                </a-select>
                <a-date-picker style="min-width:100px;" v-else-if="li.type === 3 && editor" show-time :format="BaseTool.Date.PICKER_NORM_DATETIME_PATTERN" v-model="li.fillValue" />
              </td>
              <td>
                <a-icon v-show="item.status === 1" type="check" style="color:#87d068;font-size: 26px;" />
              </td>
              <td v-if="editor">
                <a-button type="link" @click="handleRepair(item)">
                  报修
                </a-button>
                <a-button type="link" @click="uploadImg(item,i)">{{ item.images&&item.images.length?'查看图片':'上传图片' }}</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 :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 v-if="ListForm.length===0">
          <a-empty />
        </div>
        <a-pagination style="float:right;margin:10px;" v-model="listPage.pageNum" :total="listPage.total" @change="onChange" />
      </div>
    </div>
    <div v-show="type===2">
      <div style="text-align:center;padding-bottom:10px;font-size:32px;">时代思康仪表任务记录表</div>
      <a-table
        :columns="columns"
        :data-source="updatesInfo"
        bordered
        :pagination="pagination"
        @change="handleTableChange"
        :loading="loading">
        <template v-slot:index="text,record,index">
          {{ index+1 }}
        </template>
        <template v-slot:type="text">
          {{ typeMap[text] }}
        </template>
      </a-table>
    </div>
    <dispatch-form ref="dispatchModal" @ok="handleOk" />
    <overtime-form ref="overtimeModal" @ok="handleOk" />
    <pause-form ref="pauseModal" @ok="handleOk" />
    <verify-form ref="verifyModal" @ok="handleOk" />
    <base-form-repair ref="baseFormRepairModal" @ok="handleOk" />
  </a-card>
</template>

<script>
import { fillGatherTask, getFillGatherTask, getFillUpdates, pauseFillGatherTask } from '@/api/fill/task'
import DispatchForm from './DispatchForm'
import OvertimeForm from './OvertimeForm'
import BaseFormRepair from './BaseFormRepair'

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

export default {
  name: 'BaseFillGatherTask',
  components: {
    PauseForm,
    VerifyForm,
    DispatchForm,
    BaseFormRepair,
    OvertimeForm
  },
  data () {
    return {
      uploadUrl: uploadUrl,
      defaultApplicationFileList: [],
      applicationFileList: [],
      headers: {
        Authorization: 'Bearer ' + Vue.ls.get(ACCESS_TOKEN)
      },
      confirmLoading: false,
      visible: false,
      uploadVisible: false,
      previewVisible: false,
      previewImage: '',
      model: {},
      listPage: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      imgId: '',
      loading: false,
      ListForm: [],
      id: '',
      type: 1,
      typeMap: {},
      status: null,
      updatesInfo: [],
      columns: [
        {
          title: '序号',
          width: 70,
          key: 'index',
          align: 'center',
          scopedSlots: { customRender: 'index' }
        },
        {

          title: '类型',
          width: 100,
          dataIndex: 'type',
          scopedSlots: { customRender: 'type' }
        },
        {
          title: '巡检人',
          width: 150,
          dataIndex: 'checkerName'
        },
        {
          title: '巡检主管',
          width: 150,
          dataIndex: 'leaderName'
        },
        {
          title: '记录时间',
          width: 150,
          dataIndex: 'createdTime'
        },
        {
          title: ' 延时时长',
          width: 150,
          dataIndex: 'lateHour'
        },
        {
          title: '备注',
          width: 150,
          dataIndex: 'remark'
        }
      ]
      // 下拉框map
    }
  },
  props: {
    editor: {
      type: Boolean,
      default: true
    }
  },
  created () {
    // 下拉框map
    this.typeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.FILL_UPDATE_TYPE)
  },
  methods: {
    base (record) {
      this.visible = true
      this.model = record
      this.id = record.id
      this.getInfo()
      this.getFillUpdates()
    },
    getInfo () {
      const params = {
        ...this.listPage,
        taskId: this.id,
        status: this.status
      }
      getFillGatherTask(params).then(res => {
        if (res.data.rows.length === 0) {
          this.ListForm = []
          return
        }
        this.listPage.total = res.data.total
        this.ListForm = res.data.rows.map(item => {
          item.content = JSON.parse(item.content)
          item.content = item.content.map(val => {
            val.fillValue = val.fillValue ? val.fillValue : ''
            return val
          })
          item.images = item.content.filter(item => item.fileFormat)
          item.content = item.content.filter(item => !item.fileFormat)
          return item
        })
        console.log(this.ListForm)
      })
    },
    uploadImg (val, i) {
      this.uploadVisible = true
      console.log(val)
      this.imgId = i
      this.defaultApplicationFileList = this.BaseTool.UPLOAD.transImg(val.images)
      console.log(this.defaultApplicationFileList)
      console.log(this.applicationFileList)
    },
    handleRepair (val) {
      const data = {
        sbId: val.sbId,
        sbName: val.sbName,
        sbCph: val.positionName,
        applicationFileList: val.images,
        defaultApplicationFileList: this.BaseTool.UPLOAD.transImg(val.images),
        treeData: val.content.map((item) => {
          return {
            title: item.name + '：' + item.fillValue,
            value: item.name + '：' + item.fillValue,
            key: item.name + '：' + item.fillValue
          }
        })
      }
      const modal = this.$refs.baseFormRepairModal
      modal.base(data)
    },
    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].images = this.applicationFileList
    },
    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 []
      }
    },
    handleDispatch (record) {
      this.visible = false
      const modal = this.$refs.dispatchModal
      modal.base(record)
    },
    handleVerify (record) {
      const modal = this.$refs.verifyModal
      modal.base(record)
    },
    handleOvertime (record) {
      this.visible = false
      const modal = this.$refs.overtimeModal
      modal.base(record)
    },
    handlePause (record) {
      this.visible = false
      const modal = this.$refs.pauseModal
      modal.base(record)
    },
    getFillUpdates () {
      const params = {
        ...this.pagination,
        taskId: this.id
      }
      getFillUpdates(params).then(res => {
        this.updatesInfo = res.data.rows
        this.pagination.total = res.data.total
      })
    },
    handleStatusChange (e) {
      this.status = e.target.value
      this.getInfo()
    },
    handleTableChange (pagination) {
      console.log(pagination)
      const pager = { ...this.pagination }
      pager.pageNum = pagination.current
      this.pagination = pager
      this.getFillUpdates()
    },
    onChange (page) {
      this.getInfo()
    },
    save () {
      const detail = this.ListForm.map(item => {
        return {
          id: item.id,
          content: JSON.stringify([...item.content, ...item.images])
        }
      })
      const params = {
        id: this.id,
        details: detail,
        applicationFileList: this.applicationFileList

      }
      fillGatherTask(params).then(res => {
        console.log(res)
        this.handleCancel()
      })
    },
    handleConfirm (id) {
      console.log(id)
    },
    handleOk () {
      this.visible = true
    },
    handleCancel () {
      this.visible = false
      this.ListForm = []
      this.type = 1
      this.status = null
      this.$emit('ok')
    }
  }
}
</script>
<style lang="less" scoped>
  // table,table tr th, table tr td { border:1px solid #666; }
  // table {  min-height: 25px; line-height: 25px; text-align: center; border-collapse: collapse;}
  // td {
  //   padding: 5px 10px;
  // }
  .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>
