<template>
  <el-tabs class="page-car-info">
    <el-tab-pane label="查询">
      <SearchTable
        ref="querySearchTableRef"
        :immediately="false"
        v-model="queryFormData"
        @reset="handleResetCarCard"
        @submit="handleSubmitCarCard"
      >
        <template slot="slot-form">
          <el-col :span="isTablet ? 12 : 6">
            <el-form-item :rules="REQUIRED" label="组织" prop="orgId" label-width="72px">
              <CarCompany v-model="queryFormData.orgId" :default-select-first="true" placeholder="请选择车厂" @change="$refs.querySearchTableRef && $refs.querySearchTableRef.handleSubmit()" />
            </el-form-item>
          </el-col>
          <el-col :span="isTablet ? 12 : 6">
            <el-form-item label="VIN" label-width="72px" prop="vin">
              <el-input v-model="queryFormData.vin" placeholder="请输入VIN号" />
            </el-form-item>
          </el-col>
          <el-col :span="isTablet ? 24 : 6" :style="{ marginTop: isTablet ? '16px' : '0px' }">
            <el-form-item label="创建时间" label-width="72px" prop="vin">
              <el-date-picker v-model="queryFormData.createTime" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="timestamp" />
            </el-form-item>
          </el-col>
        </template>
        <template #slot-table>
          <el-table-column type="index" label="序号" width="80px" />
          <el-table-column prop="nameVehicleEnterprise" label="生产企业名称" min-width="140px" />
          <el-table-column prop="vin" label="VIN" min-width="140px" />
          <el-table-column prop="licensePlateNumber" label="车辆号码" min-width="100px" />
          <el-table-column prop="vehicleType" label="车辆类型" min-width="170px" />
          <el-table-column prop="placeOfOriginOfVehicle" label="车辆产地" min-width="190px" />
          <el-table-column prop="vehicleDepartment" label="车辆品牌" min-width="120px" />
          <el-table-column prop="vehicleName" label="车辆名称" min-width="120px" />
          <el-table-column prop="vehicleNum" label="车辆型号" min-width="120px" />
          <el-table-column prop="vehicleModel" label="车型通用名称" min-width="120px" />
          <el-table-column prop="bodyColor" label="车身颜色" min-width="120px" />
          <el-table-column prop="fuelType" label="燃料种类" min-width="120px" />
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-link type="primary" @click="handleCarDetail(scope.row)">详情</el-link>
            </template>
          </el-table-column>
        </template>
      </SearchTable>
      <el-dialog class="rnr-dialog" :visible.sync="showCarDetail" title="车辆详情" width="960px">
        <el-form ref="importFormRef" :model="importFormData" :rules="RULES" label-position="top" style="height: 400px; overflow: auto;">
          <el-row>
            <el-col :span="12" class="el-col-mar no-mar-top">
              <el-form-item label="生产企业名称">
                <el-input readonly :value="carDetail.nameVehicleEnterprise" />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="el-col-mar no-mar-top">
              <el-form-item label="VIN">
                <el-input readonly :value="carDetail.vin" />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="el-col-mar">
              <el-form-item label="车辆类型">
                <el-input readonly :value="carDetail.vehicleType" />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="el-col-mar">
              <el-form-item label="车辆产地">
                <el-input readonly :value="carDetail.placeOfOriginOfVehicle" />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="el-col-mar">
              <el-form-item label="车辆品牌">
                <el-input readonly :value="carDetail.vehicleDepartment" />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="el-col-mar">
              <el-form-item label="车辆名称">
                <el-input readonly :value="carDetail.vehicleName" />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="el-col-mar">
              <el-form-item label="车辆型号">
                <el-input readonly :value="carDetail.vehicleNum" />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="el-col-mar">
              <el-form-item label="车型通用名称">
                <el-input readonly :value="carDetail.vehicleModel" />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="el-col-mar">
              <el-form-item label="车身颜色">
                <el-input readonly :value="carDetail.bodyColor" />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="el-col-mar">
              <el-form-item label="燃料种类">
                <el-input readonly :value="carDetail.fuelType" />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="el-col-mar">
              <el-form-item label="发动机号码">
                <el-input readonly :value="carDetail.engineNum" />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="el-col-mar">
              <el-form-item label="电动机序列号">
                <el-input readonly :value="carDetail.motorNum" />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="el-col-mar">
              <el-form-item label="车辆出厂时间">
                <el-input readonly :value="carDetail.vehicleDepartureTime" />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="el-col-mar">
              <el-form-item label="车辆销售时间">
                <el-input readonly :value="carDetail.vehicleSalesTime" />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="el-col-mar">
              <el-form-item label="车辆销售信息变更时间">
                <el-input readonly :value="carDetail.vehicleSalesUpdateTime" />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="el-col-mar">
              <el-form-item label="车牌号码">
                <el-input readonly :value="carDetail.licensePlateNumber" />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="el-col-mar">
              <el-form-item label="车辆销售渠道名称">
                <el-input readonly :value="carDetail.vehicleChannelName" />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="el-col-mar">
              <el-form-item label="车辆销售渠道类型">
                <el-input readonly :value="carDetail.vehicleChannelType" />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="el-col-mar">
              <el-form-item label="车辆销售渠道员工姓名">
                <el-input readonly :value="carDetail.vehicleStaffName" />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="el-col-mar">
              <el-form-item label="车辆销售渠道地址">
                <el-input readonly :value="carDetail.vehicleLogginAddress" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="showCarDetail = false">关 闭</el-button>
        </span>
      </el-dialog>
    </el-tab-pane>
    <el-tab-pane label="车辆导入">
      <SearchTable
        ref="importSearchTableRef"
        v-model="importHistoryFormData"
        :immediately="false"
        @reset="handleResetImportHistory"
        @submit="handleSubmitImportHistory"
      >
        <template slot="slot-form">
          <el-col :span="isTablet ? 12 : 6">
            <el-form-item :rules="REQUIRED" label="车厂" label-width="72px" prop="orgUuid">
              <CarCompany v-model="importHistoryFormData.orgUuid" :default-select-first="true" placeholder="请选择车厂" @change="$refs.importSearchTableRef && $refs.importSearchTableRef.handleSubmit()" />
            </el-form-item>
          </el-col>
          <el-col :span="isTablet ? 12 : 6">
            <el-form-item label="处理结果" label-width="72px" prop="status">
              <el-select v-model="importHistoryFormData.status" placeholder="请选择处理结果">
                <el-option label="所有" value="" />
                <el-option label="成功" value="1" />
                <el-option label="错误" value="2" />
                <el-option label="处理中" value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="isTablet ? 24 : 6" :style="isTablet ? 'margin-top: 16px;' : ''">
            <el-form-item label="处理时间" label-width="72px" prop="createTime">
              <el-date-picker
                v-model="importHistoryFormData.createTime"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="timestamp"
              />
            </el-form-item>
          </el-col>
        </template>
        <template slot="slot-action-bar">
          <el-button type="primary" icon="el-icon-plus" @click="handleShowCarCardImport">车辆信息导入</el-button>
        </template>
        <template #slot-table>
          <el-table-column type="index" label="序号" width="100px" />
          <el-table-column prop="fileName" label="上传文件名称">
            <template slot-scope="scope">
              <el-link @click="handleDownloadExcel(scope.row)">{{ scope.row.fileName }}</el-link>
            </template>
          </el-table-column>
          <el-table-column label="上传状态" width="160px">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status === 1" type="success">成功</el-tag>
              <el-tag v-else-if="scope.row.status === 2" type="danger">错误</el-tag>
              <el-tag v-else type="warning">处理中</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="totalCount" label="上传总数" width="160px" />
          <el-table-column prop="successCount" label="成功数" width="160px" />
          <el-table-column prop="errorCount" label="失败数" width="160px" />
          <el-table-column prop="createTime" label="上传时间" />
          <el-table-column label="操作" prop="operation" width="200px">
            <template slot-scope="scope">
              <el-button v-if="scope.row.status === 2" type="text" @click="handleDownloadErrorExcel(scope.row)">错误信息</el-button>
            </template>
          </el-table-column>
        </template>
      </SearchTable>
      <div class="rnr-dialog">
        <el-dialog :visible.sync="showCarImport" title="车辆信息导入" width="960px">
          <el-form ref="importFormRef" :model="importFormData" :rules="RULES" label-position="top">
            <el-form-item label="车厂" prop="orgUuid">
              <CarCompany v-model="importFormData.orgUuid" placeholder="请选择车厂" />
            </el-form-item>
            <el-form-item label="上传文件" prop="fileUuid">
              <template slot="label">
                <span>上传文件</span>
                <el-link type="primary" icon="el-icon-download" @click="downloadTemplateFile">下载模板</el-link>
              </template>
              <el-upload
                ref="upload"
                :limit="1"
                :data="upload.data"
                :headers="upload.headers"
                :file-list="fileList"
                :action="upload.action"
                :before-upload="onBefore"
                :on-remove="onRemove"
                :on-success	="onSuccess"
                :on-error	="onError"
                :on-exceed="onExceed"
                class="file-uploader"
                accept=".xls,.xlsx"
                name="file"
                multiple>
                <el-button slot="trigger" size="small" type="primary">选择文件</el-button>
                <div slot="tip" class="el-upload__tip">只能上传excel文件，文件大小不超过10MB，记录数不超过5000条</div>
              </el-upload>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="showCarImport = false">取 消</el-button>
            <el-button :loading="dialogLoading" type="primary" @click="handleConfirmImport">确 定</el-button>
          </span>
        </el-dialog>
      </div>
    </el-tab-pane>
  </el-tabs>
</template>

<script>
import { queryCarInfo, queryImportHistory, downloadCarInfoTemplate, downloadFile, importCarInfo, unbindSimVehicle, bindSimVehicle, downloadExcelFile } from '@/api/management'
import dayjs from 'dayjs'
import SearchTable from '@/components/SearchTable'
import CarCompany from '@/components/CarCompany'
import { getToken } from '@/utils/auth'
import { postUploadFile } from '@/api/special-business'
import '../dealer/dialog.scss'

const RULES = {
  orgUuid: {
    required: true, trigger: 'change', message: '请选择车厂'
  },
  fileUuid: {
    required: true, trigger: 'change', message: '请上传文件'
  }
}

// 必填项
const REQUIRED = { required: true, trigger: 'change', message: '请选择车厂' }

export default {
  name: 'CarManagement',
  components: {
    CarCompany,
    SearchTable
  },
  data() {
    return {
      // 查询页面的表单数据
      queryFormData: {
        orgId: '',
        iccid: '',
        vin: '',
        createTime: [dayjs().startOf('day').valueOf(), dayjs().endOf('day').valueOf()]
      },
      // 导入历史的搜索表单数据
      importHistoryFormData: {
        createTime: [],
        fileType: 2,
        status: '',
        orgUuid: ''
      },
      // 上传组件的数据
      upload: {
        data: {
          rootPath: '',
          path: ''
        },
        headers: {
          'Authorization': `bearer ${getToken()}`
        },
        action: postUploadFile
      },
      // 导入弹框的车卡关系数据
      importFormData: {
        fileName: '',
        fileType: 2,
        fileUuid: '',
        orgUuid: '',
        tagUuid: ''
      },
      REQUIRED,
      RULES,
      tags: [],
      fileList: [],
      carDetail: {},
      dialogLoading: false,
      showCarImport: false,
      showCarDetail: false,
      isTablet: window.OS.isTablet
    }
  },
  methods: {
    /**
     * 查询车辆详情
     */
    handleCarDetail(row) {
      // 记录当前点击详情的数据
      this.carDetail = row
      // 展示详情
      this.showCarDetail = true
    },

    /**
     * 禁用
     * @param row 当前行数据
     */
    async handleUnBind(row) {
      await unbindSimVehicle({
        iccid: row.iccid,
        orgId: row.orgId,
        vin: row.vin
      })
      // 先给个提示
      this.$message.success('禁用成功')
      // 开始刷新界面
      this.$refs.querySearchTableRef.handleSubmit()
    },

    /**
     * 启用
     * @param row 当前行数据
     */
    async handleBind(row) {
      await bindSimVehicle({
        iccid: row.iccid,
        orgId: row.orgId,
        vin: row.vin
      })
      // 先给个提示
      this.$message.success('启用成功')
      // 开始刷新界面
      this.$refs.querySearchTableRef.handleSubmit()
    },

    /**
     * 根据输入的内容查询车卡绑定的列表数据
     */
    async handleSubmitCarCard(formData, callback) {
      const formDataCopy = { ...formData }
      // 如果当前选中了时间
      if (formDataCopy.createTime && formDataCopy.createTime.length === 2) {
        formDataCopy['startTime'] = formDataCopy.createTime[0]
        formDataCopy['endTime'] = dayjs(formDataCopy.createTime[1]).endOf('day').valueOf()
      }
      delete formDataCopy.createTime
      // 开始查询数据
      const { list, totalCount } = await queryCarInfo(formDataCopy)
      // 赋值成功数量
      list.forEach(item => {
        item.successCount = item.totalCount - item.errorCount
      })
      // 开始渲染页面
      callback({ list, totalCount })
    },

    /**
     * 重置form表单数据
     */
    handleResetCarCard() {
      // 重置数据
      this.queryFormData.orgId = ''
      this.queryFormData.iccid = ''
      this.queryFormData.vin = ''
      this.queryFormData.createTime = []
      this.queryFormData.fileType = 2
    },

    /**
     * 根据输入的内容查询导入的历史数据
     */
    async handleSubmitImportHistory(formData, callback) {
      // 拷贝一份数据
      const formDataCopy = { ...formData, fileType: 2 }
      // 如果当前选中了时间
      if (formDataCopy.createTime && formDataCopy.createTime.length === 2) {
        formDataCopy['startCreateTime'] = formDataCopy.createTime[0]
        formDataCopy['endCreateTime'] = dayjs(formDataCopy.createTime[1]).endOf('day').valueOf()
      }
      // 如果当前没有选择，即是全部
      if (formDataCopy.status === '') {
        delete formDataCopy.status
      }
      // 先删除数据
      delete formDataCopy.createTime
      // 开始查询数据
      const { list, totalCount } = await queryImportHistory(formDataCopy, callback)
      // 补充成功数
      list.forEach(item => {
        item.successCount = item.totalCount - item.errorCount
      })
      // 开始渲染页面
      callback({ list, totalCount })
    },

    /**
     * 重置导入的历史数据表单数据
     */
    handleResetImportHistory() {
      this.importHistoryFormData.orgUuid = ''
      this.importHistoryFormData.createTime = []
      this.importHistoryFormData.status = ''
    },

    /**
     * 下载模板文件
     */
    downloadTemplateFile() {
      downloadCarInfoTemplate({ fileType: 3 })
    },

    /**
    * 上传前校验
    * @time 2021-12-06 10:02:49
    */
    onBefore(file) {
      const type1 = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      const type2 = 'application/vnd.ms-excel'
      let isExcel = false
      if (file.type === type1 || file.type === type2) {
        isExcel = true
      }
      const isLt10M = file.size / 1024 / 1024 <= 10
      if (!isExcel) {
        this.$message.error('车卡信息文件只支持excel文件')
        return false
      }
      if (!isLt10M) {
        this.$message.error('车卡信息文件大小不能超过10MB')
        return false
      }
    },

    /**
    * 上传错误
    * @param  {Object} err 错误对象
    * @time 2021-12-15 14:14:49
    */
    onError() {
      this.$message.error('文件上传失败')
      this.$refs.upload.clearFiles()
      this.onRemove()
    },

    /**
    * 响应删除文件操作
    * @time 2021-12-09 09:52:56
    */
    onRemove(file, fileList) {
      this.form = {
        fileId: '',
        checkData: {},
        fileList: []
      }
      this.$emit('check', this.form)
    },

    /**
    * 上传数量限制
    * @time 2021-12-06 10:03:10
    */
    onExceed() {
      this.$message.error('最多上传1个excel文件')
    },

    /**
    * 文件上传
    * @time 2021-12-06 10:02:33
    */
    onSuccess(json) {
      if (json.success) {
        this.$message.success('文件上传成功')
        const data = json.data || {}
        // 用于组件展示用
        this.fileList = [{
          name: data.fileName,
          url: data.accessUrl,
          uuid: data.uuid
        }]
        // 开始保存接口请求需要的数据
        this.importFormData.fileName = data.fileName
        this.importFormData.fileUuid = data.uuid
        // 开始校验字段
        this.$refs.importFormRef.validateField('fileUuid')
      }
    },

    /**
     * 下载错误的excel
     * @param row 行数据
     */
    handleDownloadErrorExcel(row) {
      downloadFile({ uuid: row.uuid })
    },

    /**
     * 下载excel文件
     */
    handleDownloadExcel(row) {
      downloadExcelFile({ uuid: row.uuid })
    },

    /**
     * 用户导入的数据开始请求数据
     */
    async handleConfirmImport() {
      try {
        await this.$refs.importFormRef.validate()
      } catch (error) {
        console.log(error)
        return
      }
      this.dialogLoading = true
      try {
        // 开始请求接口
        await importCarInfo(this.importFormData)
        // 关闭弹框，开始查询一遍数据
        this.showCarImport = false
        // 重新刷新页面
        this.$refs.importSearchTableRef.handleSubmit()
      } catch (error) {
        console.error(error)
      }
      this.dialogLoading = false
    },

    /**
     * 展示车卡上传的弹出框
     */
    handleShowCarCardImport() {
      // 清空已经上传的文件列表
      this.fileList = []
      // 展示弹框
      this.showCarImport = true
      // 等页面渲染完成后
      this.$nextTick(() => {
        // 先重置表单
        this.$refs.importFormRef.resetFields()
      })
    }
  }
}
</script>

<style lang="scss">
.page-car-info {
  .el-tabs__header {
    padding: 24px 24px 0;
  }
  .component-search-table {
    padding-top: 0;
  }
  .status-wrap {
    align-items: center;
    display: flex;
    .status-point {
      border-radius: 3px;
      display: inline-block;
      width: 6px;
      height: 6px;
      margin-right: 8px;
      &.green {
        background-color: #25C343;
      }
      &.red {
        background-color: #FF4D4F;
      }
    }
  }
  .el-col-mar {
    padding: 0 12px;
    margin-top: 24px;
  }
  .no-mar-top {
    margin-top: 0px;
  }
}
.tablet-adapter {
  .page-car-info {
    .component-search-table-btn-wrap {
      margin-top: 16px;
    }
  }
}
</style>
