<template>
  <el-form label-width="110px" :model="editeFormData" ref="editeFormData" :inline="true">
    <el-row>
      <el-col :span="16">
        <el-form-item label-width="110px" label="更多车牌：" style="margin-bottom: 10px;" >
          <el-input v-model="pageParams.carNo" :clearable="true" style="width: 245px;"></el-input>
        </el-form-item>
        <el-form-item style="margin-bottom: 10px;">
          <el-button type="primary" @click="formSearch">查询</el-button>
        </el-form-item>
      </el-col>
      <el-col :span="8" style="text-align: right;padding-right: 16px;" v-if="isEdit">
        <el-button type="primary" @click="addCarNo" style="margin-bottom: 5px;">新增车牌</el-button>
        <el-button @click="isShowImportDialog = true" style="margin-bottom: 5px;">批量导入</el-button>
      </el-col>
    </el-row>
    <div class="table-wrap" style="margin-left: 110px;">
      <el-table :data="editeFormData.addCarNoList" stripe size="small" border style="width: 100%;" max-height="400" :header-cell-style="{'background-color': '#f5f7fa', 'color': '#333333'}">
        <el-table-column
          type="index"
          align="center"
          label="序号"
          width="50">
        </el-table-column>
        <el-table-column
          label="车牌号码"
          prop="editCarNo"
          align="center"
        >
          <template slot-scope="scope">
            <el-form-item
              label=""
              :prop="'addCarNoList.' + scope.$index + '.editCarNo'"
              style="margin-bottom: 0;"
              :rules="[
                {
                  required: true,
                  message: '必填',
                  trigger: ['blur', 'change'],
                },
                // 最长8位
                {
                  max: 8,
                  message: '最长8位',
                  trigger: ['blur', 'change'],
                }
              ]"
            >
              <el-input
                v-if="isEdit && scope.row.currentIsEdit"
                v-model="scope.row.editCarNo"
                placeholder="请输入车牌号"
                style="width: 100%;"
              >
              </el-input>
              <div v-else>{{ scope.row.carNo }}</div>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="260"
        >
          <template slot-scope="scope" v-if="isEdit">
            <div v-loading="btnLoading">
              <a
                class="text-btn-edite tr-action"
                style="margin-right: 16px;"
                @click="doEdite(scope.row, scope.$index)"
                v-if="!scope.row.currentIsEdit"
              >编辑</a>
              <template v-if="scope.row.currentIsEdit">
                <a
                  class="text-btn-edite tr-action"
                  style="margin-right: 16px;"
                  @click="updateCarNo(scope.row)"
                >确定</a>
                <a
                  class="text-btn-cancel tr-action"
                  style="margin-right: 16px;"
                  @click="cancel(scope.row, scope.$index)"
                >取消</a>
              </template>

              <a
                class="text-btn-delete tr-action"
                @click="carNumRemove(scope.row.carGroupId)"
              >删除</a>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next"
          @current-change="currentChange"
          :total="total">
        </el-pagination>
      </div>
    </div>

    <importCar
      ref="importCar"
      v-model="isShowImportDialog"
      :import-template-json="[{ field: 'carNo', title: '车牌号' }]"
      export-template-by-url="/xlsl/sharedCar.xlsx"
      :export-template-json="[{ field: 'carNo', title: '车牌号' }]"
      :export-template-data="[]"
      :import-request-back-info="importRequestBackInfo"
      :rowStart="1"
      type="black-car"
      @dialogChange="carDialogChange"
      @startUpload="startUpload"
    >
    </importCar>
  </el-form>
</template>

<script>
import { findListByCondition, updateCarGroup, addCarGroup, deleteByGroupId, importCarGroup } from '../../api/fixedCar'
import { mapGetters } from 'vuex'
import mixin from "../../mixin/index"
import importCar from '../importCar'
export default {
  name: 'shareCar',
  mixins: [mixin],
  props: {
    isEdit: {
      type: Boolean,
      default: false
    },
    fixedCarId: {
      type: String,
      default: '',
      required: true
    }
  },
  components: {
    importCar
  },
  computed: {
    ...mapGetters([
      'parkGuid'
    ])
  },
  data() {
    return {
      btnLoading: false,
      isShowImportDialog: false,
      importRequestBackInfo: {
        successNum: 0,
        importFixedCarFailVOs: [],
        failNum: 0
      },
      pageParams: {
        fixedCarId: '',
        carNo: '',
        pager: {
          pageSize: 10,
          page: 1,
        }
      },
      total: 0,
      editeFormData: {
        addCarNoList: []
      }
    }
  },
  created() {
    this.getPageList();
  },
  methods: {
    carDialogChange(val) {
      this.isShowImportDialog = val
      if (!val) {
        this.$refs.importCar.resetFields()
        this.importRequestBackInfo = {
          successNum: 0,
          importFixedCarFailVOs: [],
          failNum: 0
        }
      }
    },
    async startUpload(excleData) {
      console.log(excleData)
      if (!excleData || excleData.length < 1) {
        return this.$message.warning('请选择文件')
      }
      // 限制批量上传数量 暂时限制1000条
      if (excleData.length > 1000) {
        return this.$message.warning('批量上传数量不能超过1000条,请分批导入！')
      }
      this.importRequestBackInfo.importFixedCarFailVOs = []
      const params = Object.assign({}, {
        fixedCarId: this.fixedCarId,
        carNoList: excleData.map(el => el.carNo)
      })
      importCarGroup(params).then(res => {
        if (res.errorCode === '0') {
          this.importRequestBackInfo = Object.assign({importFixedCarFailVOs: res.data.resultList || [], successNum: res.data.successNum, failNum: res.data.failNum})
          this.formSearch()
        }
      })
    },
    async getPageList() {
      this.pageParams.fixedCarId = this.fixedCarId
      const res = await findListByCondition(this.pageParams)
      const { errorCode, data: {list, total}} = res;
      if (errorCode === '0') {
        if (list && list.length) {
          const arr = []
          console.log(list, 'list')
          list.forEach(item => {
            arr.push({...item, currentIsEdit: false, editCarNo: item.carNo})
          })
          this.$set(this.editeFormData, 'addCarNoList', arr)
        } else {
          this.editeFormData.addCarNoList = []
        }
        this.total = total || 0
      }
    },
    formSearch() {
      this.pageParams.pager.page = 1
      this.getPageList()
    },
    currentChange(page) {
      this.pageParams.pager.page = page
      this.getPageList()
    },
    async carNumRemove(carGroupId) {
      const res = await deleteByGroupId(carGroupId)
      const { errorCode } = res;
      if (errorCode === '0') {
        
      }
    },
    doEdite(item, index) {
      item.editCarNo = item.carNo
      this.$set(this.editeFormData.addCarNoList[index],'currentIsEdit', true)
    },
    addCarNo() {
      this.editeFormData.addCarNoList.unshift({
        carNo: '',
        currentIsEdit: true,
        editCarNo: ''
      })
    },
    async updateCarNo(item) {
      this.$refs.editeFormData.validate(async (valid) => {
        console.log(valid, 'valid')
        if (valid) {
          this.btnLoading = true
          try {
            let apiMethod;
            let apiParams;
            if(item.carGroupId) {
              apiMethod = updateCarGroup
              apiParams = {
                fixedCarId: item.fixedCarId,
                carNo: item.editCarNo,
                carGroupId: item.carGroupId,
                parkGuid: item.parkGuid
              }
            } else {
              apiMethod = addCarGroup
              apiParams = {
                fixedCarId: this.fixedCarId,
                carNo: item.editCarNo,
                parkGuid: this.parkGuid
              }
            }
            const res = await apiMethod(apiParams)
            const { errorCode, message } = res;
            if (errorCode === '0') {
              this.getPageList()
              this.$emit('reload')
              this.$message.success('修改成功')
            } else {
              this.$message.error(message)
            }
          } finally {
            this.btnLoading = false
          }
        }
      })
    },
    cancel(item, index) {
      if (item.carGroupId) {
        item.currentIsEdit = false
      } else {
        // 本条记录还没入库，取消的话直接在列表中删除
        this.editeFormData.addCarNoList.splice(0, 1)
      }
    },
    carNumRemove(id) {
      this.showConfirm({
        promiseCallBack: async() => {
          this.btnLoading = true;
          try {
            const res = await deleteByGroupId(id)
            const { errorCode, message } = res;
            if (errorCode === '0') {
              this.getPageList()
              this.$message.success('删除成功')
            } else {
              this.$message.error(message)
            }
          } finally {
            this.btnLoading = false
          }
        },
        title: '提示',
        showCancelButton: true,
        confirmButtonText: '确定',
        confirmText: '确定删除该车辆吗？',
        confirmButtonClass: 'self-confirm-warn'
      })
    },
    currentChange(page) {
      this.pageParams.pager.page = page
      this.getPageList()
    }
  }
}

</script>

<style lang="scss" scoped>
  .pagination {
    display: flex;
    justify-content: flex-end;
    margin-top: 5px;
  }
</style>