<template>
  <el-tabs class="page-car-card">
    <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 : 8">
            <el-form-item :rules="REQUIRED" label="组织" prop="organizationId" label-width="72px">
              <CarCompany v-model="queryFormData.organizationId" :default-select-first="true" placeholder="请选择车厂" @change="$refs.querySearchTableRef && $refs.querySearchTableRef.handleSubmit()" />
            </el-form-item>
          </el-col>
          <el-col :span="isTablet ? 12 : 8">
            <el-form-item label="ICCID" label-width="72px" prop="iccid">
              <el-input v-model="queryFormData.iccid" placeholder="请输入ICCID" />
            </el-form-item>
          </el-col>
          <el-col :span="isTablet ? 12 : 8" :style="{ marginTop: isTablet ? '16px' : '0px' }">
            <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 : 8" style="margin-top: 16px;">
            <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="organizationName" label="组织名称" min-width="140px" />
          <el-table-column prop="telecomSupplier" label="通讯运营商" min-width="140px" />
          <el-table-column prop="vin" label="VIN" min-width="170px" />
          <el-table-column prop="iccid" label="ICCID" min-width="190px" />
          <el-table-column prop="brandName" label="品牌名称" min-width="120px" />
          <el-table-column prop="brand" label="车辆品牌" min-width="120px" />
          <el-table-column prop="vehicleModel" label="车型" min-width="120px" />
          <el-table-column prop="vehicleSeries" label="车系" min-width="120px" />
          <el-table-column prop="years" label="年限" min-width="100px" />
          <el-table-column prop="installLocation" label="卡位置" min-width="120px">
            <template slot-scope="scope">
              <span>{{ scope.row.installLocation === 1 ? '车机' : 'tbox' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="是否允许补录" min-width="120px">
            <template slot-scope="scope">
              <span>{{ scope.row.realBySelf ? '允许' : '不允许' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" min-width="170px" />
          <el-table-column label="状态" min-width="100px">
            <template slot-scope="scope">
              <div class="status-wrap">
                <i :class="scope.row.bindStatus == 0 ? 'green' : 'red'" class="status-point" />
                {{ ['已启用', '已禁用'][scope.row.bindStatus] }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="100px">
            <template slot-scope="scope">
              <el-link v-if="scope.row.bindStatus == 0" type="primary" @click="handleUnBind(scope.row)">禁用</el-link>
              <el-link v-else type="primary" @click="handleBind(scope.row)">启用</el-link>
            </template>
          </el-table-column>
        </template>
      </SearchTable>
    </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 : 8">
            <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 : 8">
            <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 : 8" :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>
          <el-col :span="isTablet ? 12 : 8" style="margin-top: 16px;">
            <el-form-item label="操作类型" label-width="72px" prop="status">
              <el-select v-model="importHistoryFormData.fileType" placeholder="请选择操作类型">
                <el-option label="全部" value="" />
                <el-option label="新增" :value="1" />
                <el-option label="启用" :value="4" />
                <el-option label="禁用" :value="5" />
              </el-select>
            </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 prop="fileType" label="操作类型">
            <template slot-scope="scope">
              <div class="status-wrap">
                <i :class="scope.row.fileType == 5 ? 'red' : 'green'" class="status-point" />
                {{ { 1: '新增', 4: '启用', 5: '禁用' }[scope.row.fileType] }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" prop="operation" width="160px">
            <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="请选择组织" @change="handleCarCompanyChange" />
            </el-form-item>
            <el-form-item label="属性" prop="tagUuid">
              <el-select v-model="importFormData.tagUuid" placeholder="请选择属性">
                <el-option v-for="tag in tags" v-bind="tag" :key="tag.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="操作类型" prop="fileType">
              <el-select v-model="importFormData.fileType" placeholder="请选择操作类型">
                <el-option label="新增" :value="1" />
                <el-option label="启用" :value="4" />
                <el-option label="禁用" :value="5" />
              </el-select>
            </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 { querySimVehicleByPage, queryImportHistory, carCardExcelTemplate, downloadFile, importSimVehicle, queryTag, 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: {
        organizationId: '',
        iccid: '',
        vin: '',
        createTime: [dayjs().startOf('day').valueOf(), dayjs().endOf('day').valueOf()]
      },
      // 导入历史的搜索表单数据
      importHistoryFormData: {
        createTime: [],
        fileType: 1,
        status: '',
        orgUuid: ''
      },
      // 上传组件的数据
      upload: {
        data: {
          rootPath: '',
          path: ''
        },
        headers: {
          'Authorization': `bearer ${getToken()}`
        },
        action: postUploadFile
      },
      // 导入弹框的车卡关系数据
      importFormData: {
        fileName: '',
        fileType: 1,
        fileUuid: '',
        orgUuid: '',
        tagUuid: ''
      },
      REQUIRED,
      RULES,
      tags: [],
      fileList: [],
      dialogLoading: false,
      showCarImport: false,
      isTablet: window.OS.isTablet
    }
  },
  methods: {
    /**
     * 禁用
     * @param row 当前行数据
     */
    async handleUnBind(row) {
      await unbindSimVehicle({
        iccid: row.iccid,
        organizationId: row.organizationId,
        vin: row.vin
      })
      // 先给个提示
      this.$message.success('禁用成功')
      // 开始刷新界面
      this.$refs.querySearchTableRef.handleSubmit()
    },

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

    /**
     * 车企改变的方法
     */
    async handleCarCompanyChange(orgUuid) {
      // 列表数据
      const list = await queryTag({ orgUuid })
      // 当前标签
      this.tags = (list || []).map(item => {
        return {
          label: item.tagName,
          value: item.tagCode
        }
      })
    },

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

    /**
     * 重置form表单数据
     */
    handleResetCarCard() {
      // 重置数据
      this.queryFormData.organizationId = ''
      this.queryFormData.iccid = ''
      this.queryFormData.vin = ''
    },

    /**
     * 根据输入的内容查询导入的历史数据
     */
    async handleSubmitImportHistory(formData, callback) {
      // 拷贝一份数据
      const formDataCopy = { ...formData }
      // 如果当前选中了时间
      if (formDataCopy.createTime) {
        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() {
      carCardExcelTemplate({ fileType: this.importFormData.fileType })
    },

    /**
    * 上传前校验
    * @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 importSimVehicle(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-card {
  .el-tabs__header {
    padding: 24px 24px 0;
  }
  .component-search-table {
    padding-top: 0;
  }
  .el-col-6 {
    margin-top: 16px;
  }
  .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;
      }
    }
  }
}
</style>
