<!--
 * @Author: zwq
 * @Date: 2020-12-29 16:37:56
-->
<template>
  <div style="margin:20px">
    <div slot="title" style=" background-color:#02BCFF;font-size:1.5em;color:white;padding:5px 20px;margin:20px">{{ isdetail? 'btn.detail' : !listQuery.equipmentId ? 'btn.add' : 'btn.edit' | i18nFilter }}</div>
    <div style="margin:0 15px">
      <el-form
        ref="dataForm"
        :model="dataForm"
        :rules="rules"
        size="medium"
        label-width="220px"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item :label="$t('module.basicData.equipment.EquipmentName')" prop="name">
              <el-input v-model="dataForm.name" autofocus :disabled="isdetail" :placeholder="$i18nForm(['placeholder.input', $t('module.basicData.equipment.EquipmentName')])" clearable :style="{width: '100%'}" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('module.basicData.equipment.EquipmentCode')" prop="code">
              <el-input v-model="dataForm.code" :disabled="isdetail" :placeholder="$i18nForm(['placeholder.input', $t('module.basicData.equipment.EquipmentCode')])" clearable :style="{width: '100%'}" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('module.basicData.visual.EnglishName')" prop="enName">
              <el-input v-model="dataForm.enName" :disabled="isdetail" :placeholder="$i18nForm(['placeholder.input', $t('module.basicData.visual.EnglishName')])" clearable :style="{width: '100%'}" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item :label="$t('module.basicData.visual.Abbreviation')" prop="abbr">
              <el-input v-model="dataForm.abbr" :disabled="isdetail" :placeholder="$i18nForm(['placeholder.input', $t('module.basicData.visual.Abbreviation')])" clearable :style="{width: '100%'}" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- <el-form-item :label="$t('module.basicData.equipment.EquipmentType')" prop="equipmentType">
              <el-select
                v-model="dataForm.equipmentType"
                :disabled="isdetail"
                :placeholder="$i18nForm(['placeholder.input', $t('module.basicData.equipment.EquipmentType')])"
                clearable
                :style="{width: '100%'}"
              >
                <el-option
                  v-for="(item, index) in equipmentTypeOption"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                  :disabled="item.disabled"
                />
              </el-select>
            </el-form-item> -->
            <!-- <el-form-item :label="$t('module.basicData.equipment.EquipmentType')" prop="equipmentType">
              <el-input v-model="dataForm.equipmentType" :disabled="isdetail" :placeholder="$i18nForm(['placeholder.input', $t('module.basicData.equipment.EquipmentType')])" clearable :style="{width: '100%'}" />
            </el-form-item> -->
            <el-form-item :label="$t('module.basicData.equipment.EquipmentType')" prop="EquipmentType">
              <el-select v-model="dataForm.equipmentType" :placeholder="this.$t('module.basicData.cache.logisticsEquipment')" default>
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('module.basicData.visual.enterTime')" prop="enterTime">
              <el-date-picker
                v-model="dataForm.enterTime"
                :disabled="isdetail"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-ddT00:00:00"
                :style="{width: '100%'}"
                :placeholder="$i18nForm(['placeholder.input', $t('module.basicData.visual.enterTime')])"
                clearable
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8">
            <el-form-item :label="$t('module.basicData.equipment.EquipmentGrouping')" prop="groupId">
              <el-select
                v-model="dataForm.groupId"
                :disabled="isdetail"
                :placeholder="$i18nForm(['placeholder.input', $t('module.basicData.equipment.EquipmentGrouping')])"
                clearable
                :style="{width: '100%'}"
              >
                <el-option
                  v-for="(item, index) in equipmentGroupOption"
                  :key="index"
                  :label="item.groupName"
                  :value="item.id"
                  :disabled="item.disabled"
                />
              </el-select>
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row>
          <!-- <el-col :span="8">
            <el-form-item :label="$t('module.basicData.visual.Specs')" prop="spec">
              <el-input v-model="dataForm.spec" :disabled="isdetail" :placeholder="$i18nForm(['placeholder.input', $t('module.basicData.visual.Specs')])" clearable :style="{width: '100%'}" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('module.basicData.visual.productionTime')" prop="createTime">
              <el-date-picker
                v-model="dataForm.createTime"
                :disabled="isdetail"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                :style="{width: '100%'}"
                :placeholder="$i18nForm(['placeholder.input', $t('module.basicData.visual.productionTime')])"
                clearable
              />
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row>
          <!-- <el-col :span="8">
            <el-form-item :label="$t('module.basicData.visual.debugTime')" prop="debugTime">
              <el-date-picker
                v-model="dataForm.debugTime"
                :disabled="isdetail"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                :style="{width: '100%'}"
                :placeholder="$i18nForm(['placeholder.input', $t('module.basicData.visual.debugTime')])"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('module.basicData.equipment.DebugPeriod')" prop="debugPeriod">
              <el-input v-model="dataForm.debugPeriod" :disabled="isdetail" :placeholder="$i18nForm(['placeholder.input', $t('module.basicData.equipment.DebugPeriod')])" clearable :style="{width: '100%'}" />
            </el-form-item>
          </el-col> -->
          <el-col :span="8">
            <el-form-item :label="$t('module.basicData.visual.Manufacturer')" prop="manufacturer">
              <el-input
                v-model="dataForm.manufacturer"
                :disabled="isdetail"
                :placeholder="$i18nForm(['placeholder.input', $t('module.basicData.visual.Manufacturer')])"
                clearable
                :style="{width: '100%'}"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('module.basicData.visual.Remarks')" prop="remark">
              <el-input v-model="dataForm.remark" :disabled="isdetail" :placeholder="$i18nForm(['placeholder.input', $t('module.basicData.visual.Remarks')])" clearable :style="{width: '100%'}" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('module.basicData.visual.Description')" prop="description">
              <el-input v-model="dataForm.description" :disabled="isdetail" :placeholder="$i18nForm(['placeholder.input', $t('module.basicData.visual.Description')])" clearable :style="{width: '100%'}" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <!-- <el-col :span="8">
            <el-form-item :label="$t('module.basicData.equipment.intellectualProperty')" prop="intellectualProperty">
              <el-input
                v-model="dataForm.intellectualProperty"
                :disabled="isdetail"
                :placeholder="$i18nForm(['placeholder.input', $t('module.basicData.equipment.intellectualProperty')])"
                clearable
                :style="{width: '100%'}"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('module.basicData.equipment.rangeNumber')" prop="rangeNumber">
              <el-input-number
                v-model="dataForm.rangeNumber"
                :disabled="isdetail"
                :step="1"
                :placeholder="$i18nForm(['placeholder.input', $t('module.basicData.equipment.rangeNumber')])"
                clearable
                :style="{width: '100%'}"
              />
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="8">
            <el-form-item :label="$t('module.basicData.equipment.plcVersion')" prop="plcVersion">
              <el-input v-model="dataForm.plcVersion" :disabled="isdetail" :placeholder="$i18nForm(['placeholder.input', $t('module.basicData.equipment.plcVersion')])" clearable :style="{width: '100%'}" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('module.basicData.equipment.eapVersion')" prop="eapVersion">
              <el-input v-model="dataForm.eapVersion" :disabled="isdetail" :placeholder="$i18nForm(['placeholder.input', $t('module.basicData.equipment.eapVersion')])" clearable :style="{width: '100%'}" />
            </el-form-item>
          </el-col> -->
        </el-row>
        <!-- <el-row>
          <el-col :span="8">
            <el-form-item :label="$t('module.basicData.equipment.maintenanceCycle')" prop="maintenanceCycle">
              <el-input v-model="dataForm.maintenanceCycle" :disabled="isdetail" :placeholder="$i18nForm(['placeholder.input', $t('module.basicData.equipment.maintenanceCycle')])" clearable :style="{width: '100%'}" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('module.basicData.equipment.maintenanceTime')" prop="maintenanceTime">
              <el-input v-model="dataForm.maintenanceTime" :disabled="isdetail" :placeholder="$i18nForm(['placeholder.input', $t('module.basicData.equipment.maintenanceTime')])" clearable :style="{width: '100%'}" />
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-row>
          <!-- <el-col :span="4">
            <el-form-item :label="$t('module.basicData.equipment.E10Status')" prop="estatus">
              <el-switch
                v-model="dataForm.estatus"
                :disabled="isdetail"
                :active-value="1"
                :inactive-value="0"
                active-color="#13ce66"
                inactive-color="#AAAAAA"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item :label="$t('module.basicData.equipment.activiation')" prop="activiation">
              <el-switch
                v-model="dataForm.activiation"
                :disabled="isdetail"
                :active-value="1"
                :inactive-value="0"
                active-color="#13ce66"
                inactive-color="#AAAAAA"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item :label="$t('module.basicData.equipment.communication')" prop="communication">
              <el-switch
                v-model="dataForm.communication"
                :disabled="isdetail"
                :active-value="1"
                :inactive-value="0"
                active-color="#13ce66"
                inactive-color="#AAAAAA"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item :label="$t('module.basicData.equipment.controlStatus')" prop="controlStatus">
              <el-switch
                v-model="dataForm.controlStatus"
                :disabled="isdetail"
                :active-value="1"
                :inactive-value="0"
                active-text="远程"
                inactive-text="本地"
                active-color="#13ce66"
                inactive-color="#AAAAAA"
              />
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row>
          <el-col :span="9">
            <!-- <el-form-item v-if="listQuery.equipmentId && !isdetail" :label="$t('module.basicData.equipment.equipmentImg')" prop="eImg">
              <el-upload
                ref="eImg"
                name="files"
                :data="typeCode"
                :file-list="eImgfileList"
                :action="eImgAction"
                :before-upload="eImgBeforeUpload"
                accept="image/*"
                :on-success="saveUpload"
              >
                <el-button size="small" type="primary" icon="el-icon-upload">{{ 'btn.upload' | i18nFilter }}</el-button>
              </el-upload>
            </el-form-item> -->
            <el-form-item v-if="isdetail" :label="$t('module.basicData.equipment.equipmentImg')" prop="upInfo">
              <div v-for="item in imgList" :key="item.id">
                {{ item.fileName }} <el-button size="small" type="primary" icon="el-icon-upload" @click="downloadFile(item.fileId)">{{ 'btn.download' | i18nFilter }}</el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item v-if="listQuery.equipmentId && !isdetail" :label="$t('module.basicData.equipment.equipmentInfo')" prop="eInfo">
              <el-upload
                ref="eInfo"
                :on-success="saveUpload"
                name="files"
                :data="typeCode"
                :file-list="eInfofileList"
                :action="eInfoAction"
                multiple
                :before-upload="eInfoBeforeUpload"
              >
                <el-button size="small" type="primary" icon="el-icon-upload">{{ 'btn.upload' | i18nFilter }}</el-button>
              </el-upload>
            </el-form-item>
            <el-form-item v-if="isdetail" :label="$t('module.basicData.equipment.equipmentInfo')" prop="upInfo">
              <div v-for="item in fileList" :key="item.id">
                {{ item.fileName }} <el-button size="small" type="primary" icon="el-icon-upload" @click="downloadFile(item.fileId)">{{ 'btn.download' | i18nFilter }}</el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style="margin:20px">
        <el-button type="success" @click="goback()">{{ 'btn.back' | i18nFilter }}</el-button>
        <el-button v-if="isdetail" type="primary" @click="goEdit()">{{ 'btn.edit' | i18nFilter }}</el-button>
        <span v-if="!isdetail">
          <el-button type="primary" @click="dataFormSubmit()">{{ 'btn.save' | i18nFilter }}</el-button>
          <el-button v-if="listQuery.equipmentId" type="primary" @click="addNew()">{{ 'btn.addattr' | i18nFilter }}</el-button>
        </span>
      </div>
      <div style="overflow:auto;height:380px">
        <base-table
          :page="listQuery.current"
          :limit="listQuery.size"
          :table-config="tableProps"
          :table-data="list"
          :is-loading="listLoading"
        >
          <method-btn
            v-if="!isdetail"
            slot="handleBtn"
            :method-list="tableBtn"
            @clickBtn="handleClick"
          />
        </base-table>
      </div>
    </div>
    <equipment-info-attr-add v-if="addOrUpdateVisible" ref="addOrUpdate" :equipment-id="listQuery.equipmentId" @refreshDataList="getList" />
  </div>
</template>

<script>import i18n from '@/lang'
import {
  equipmentInfoDetail,
  equipmentInfoUpdate,
  equipmentInfoAdd,
  equipmentInfoCode,
  equipmentInfoFileAdd
} from '@/api/basicData/Equipment/equipmentInfo'
import { equipmentInfoAttrList, equipmentInfoAttrDelete } from '@/api/basicData/Equipment/equipmentInfoAttr'
import BaseTable from '@/components/BaseTable'
import MethodBtn from '@/components/BaseTable/subcomponents/MethodBtn'
import equipmentInfoAttrAdd from './equipmentInfoAttr-add'
import { uploadPath } from '@/api/basic'
import { timeFormatter } from '@/filters'
import { getUrl } from '@/api/file'
const tableBtn = [
  {
    type: 'edit',
    btnName: 'btn.edit'
  },
  {
    type: 'delete',
    btnName: 'btn.delete'
  }
]
const tableProps = [
  {
    prop: 'createTime',
    label: i18n.t('module.basicData.factory.createTime'),
    filter: timeFormatter,
    align: 'center'
  },
  {
    prop: 'attrName',
    label: i18n.t('module.basicData.visual.AttributeName'),
    align: 'center'
  },
  {
    prop: 'attrContent',
    label: i18n.t('module.basicData.visual.AttributeValue'),
    align: 'center'
  }
  // {
  //   prop: 'remark',
  //   label: i18n.t('module.basicData.visual.Remarks'),
  //   align: 'center'
  // }
]

export default {
  components: { BaseTable, MethodBtn, equipmentInfoAttrAdd },
  data() {
    return {
      addOrUpdateVisible: false,
      tableBtn,
      trueWidth: 200,
      tableProps,
      list: [],
      listLoading: false,
      dataForm: {
        name: '',
        code: '',
        enName: '',
        abbr: '',
        equipmentType: this.$t('module.basicData.cache.logisticsEquipment'),
        spec: '',
        createTime: '',
        enterTime: '',
        debugTime: '',
        debugPeriod: '',
        manufacturer: '',
        intellectualProperty: '',
        rangeNumber: '',
        remark: '',
        description: '',
        groupId: '',
        eImg: null,
        eInfo: null,
        communication: 0,
        controlStatus: 0,
        plcVersion: '',
        eapVersion: '',
        activiation: 0,
        estatus: 0,
        maintenanceTime: '',
        maintenanceCycle: ''
      },
      options: [
        {
          value: '1',
          label: this.$t('module.basicData.cache.logisticsEquipment')
        },
        {
          value: '2',
          label: this.$t('module.basicData.cache.processEquipment')
        }
      ],
      rules: {
        name: [{
          required: true,
          message: this.$i18nForm(['placeholder.input', this.$t('module.basicData.equipment.EquipmentName')]),
          trigger: 'blur'
        }],
        code: [{
          required: true,
          message: this.$i18nForm(['placeholder.input', this.$t('module.basicData.equipment.EquipmentCode')]),
          trigger: 'blur'
        }]
        // maintenanceCycle: [{
        //   required: true,
        //   message: this.$i18nForm(['placeholder.input', this.$t('module.basicData.equipment.maintenanceCycle')]),
        //   trigger: 'blur'
        // }],
        // maintenanceTime: [{
        //   required: true,
        //   message: this.$i18nForm(['placeholder.input', this.$t('module.basicData.equipment.maintenanceTime')]),
        //   trigger: 'blur'
        // }]
      },
      typeCode: {},
      eImgAction: uploadPath,
      eImgfileList: [],
      eInfoAction: uploadPath,
      eInfofileList: [],
      equipmentTypeOption: [],
      equipmentGroupOption: [],
      listQuery: {
        current: 1,
        size: 990,
        equipmentId: ''
      },
      isdetail: false,
      downloadList: [],
      fileList: [],
      imgList: []
    }
  },
  created() {
    this.listQuery.equipmentId = this.$route.query.id
    this.init()
    this.getList()
  },
  methods: {
    init() {
      this.isdetail = false
      this.isdetail = Boolean(this.$route.query.isdetail)
      // 设备信息下载接口，暂时未调用
      // if (this.isdetail) {
      //   const data =
      //     {
      //       'equipmentId': this.listQuery.equipmentId
      //     }
      //   getEquipmentInfoFile(data).then(res => {
      //     this.downloadList = res.data
      //     this.downloadList.forEach(item => {
      //       if (item.typeCode === 'equipmentInfoImage') {
      //         this.imgList.push(item)
      //       } else {
      //         this.fileList.push(item)
      //       }
      //     })
      //   })
      // }
      // this.list.splice(0, this.list.length)
      // equipmentTypeList(this.listQuery).then(response => {
      //   this.equipmentTypeOption = response.data.records
      // })
      // equipmentGroupList(this.listQuery).then(response => {
      //   this.equipmentGroupOption = response.data.records
      // })
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.listQuery.equipmentId) {
          this.listLoading = true
          equipmentInfoDetail(this.listQuery.equipmentId).then(res => {
            this.dataForm = res.data
            console.log(this.dataForm)
          })
          equipmentInfoAttrList(this.listQuery).then(response => {
            if (response.data.records) {
              this.list = response.data.records
            } else {
              this.list.splice(0, this.list.length)
            }
            this.listLoading = false
          })
        } else {
          equipmentInfoCode().then(res => {
            this.dataForm.code = res.data
          })
        }
      })
    },
    getList() {
      this.listLoading = true
      // console.log(this.listQuery)
      equipmentInfoAttrList(this.listQuery).then(response => {
        // console.log(response)
        if (response.data.records) {
          this.list = response.data.records
        } else {
          this.list.splice(0, this.list.length)
        }
        this.listLoading = false
      })
    },
    handleClick(raw) {
      if (raw.type === 'delete') {
        this.$confirm(`${this.$t('module.basicData.visual.TipsBefore')}[${raw.data.name}]?`, this.$t('module.basicData.visual.Tips'), {
          confirmButtonText: this.$t('module.basicData.visual.confirmButtonText'),
          cancelButtonText: this.$t('module.basicData.visual.cancelButtonText'),
          type: 'warning'
        }).then(() => {
          equipmentInfoAttrDelete(raw.data.id).then(response => {
            this.$message({
              message: this.$t('module.basicData.visual.success'),
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getList()
              }
            })
          })
        }).catch(() => {})
      } else {
        this.addNew(raw.data.id)
      }
    },
    // 表单提交
    dataFormSubmit() {
      // console.log(this.dataForm)
      // console.log(this.dataForm.eInfo)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const data = this.dataForm
          data.id = this.listQuery.equipmentId
          if (this.listQuery.equipmentId) {
            // console.log(data)
            equipmentInfoUpdate(data).then(res => {
              this.$message({
                message: this.$t('module.basicData.visual.success'),
                type: 'success',
                duration: 1500
              })
            })
          } else {
            equipmentInfoAdd(data).then(res => {
              this.$message({
                message: this.$t('module.basicData.visual.success'),
                type: 'success',
                duration: 1500
              })
              this.listQuery.equipmentId = res.data.id
            })
          }
        }
      })
    },
    // 新增 / 修改
    addNew(id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id)
      })
    },
    goback() {
      this.$router.go(-1)
    },
    goEdit() {
      this.isdetail = false
    },
    eImgBeforeUpload(file) {
      this.typeCode.typeCode = 'equipmentInfoImage'
      const isRightSize = file.size / 1024 / 1024 < 10
      if (!isRightSize) {
        this.$message.error(this.$t('upload.picSizeAlarm'))
      }
      const isAccept = new RegExp('image/*').test(file.type)
      if (!isAccept) {
        this.$message.error(this.$t('upload.picAlarm'))
      }
      return isRightSize && isAccept
    },
    eInfoBeforeUpload(file) {
      this.typeCode.typeCode = 'equipmentInfoFile'
      const isRightSize = file.size / 1024 / 1024 < 10
      if (!isRightSize) {
        this.$message.error(this.$t('upload.picSizeAlarm'))
      }
      return isRightSize
    },
    submitUpload() {
      this.$refs['eInfo'].submit()
    },
    saveUpload(res) {
      const data =
        {
          'equipmentId': this.listQuery.equipmentId,
          'fileId': res.data[0].id,
          'fileName': res.data[0].fileName,
          'fileUrl': res.data[0].fileUrl,
          'typeCode': this.typeCode.typeCode
        }
      // console.log(data)
      equipmentInfoFileAdd(data).then(res => {
        // console.log(res)
      })
    },
    downloadFile(id) {
      getUrl({
        attachmentId: id,
        type: 1
      }).then(response => {
        let fileName = ''
        const contentDisposition = response.headers['content-disposition']
        if (contentDisposition) {
          fileName = contentDisposition.slice(contentDisposition.indexOf('filename=') + 9)
        }
        const blob = new Blob([response.data])
        const reader = new FileReader()
        reader.readAsDataURL(blob)
        reader.onload = (e) => {
          const a = document.createElement('a')
          a.download = fileName
          a.href = e.target.result
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
        }
      })
    }
  }
}
</script>

<style scoped>
.drawer-footer {
  width: 100%;
  margin-top: 50px;
  border-top: 1px solid #e8e8e8;
  border-bottom: 1px solid #e8e8e8;
  padding: 10px 50px;
  text-align: left;
  background: #fff;
}
</style>
