<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div>
        <!-- 搜索 -->
        <label class="el-form-item-label">车牌号</label>
        <el-input v-model="query.plateNumber" clearable placeholder="车牌号" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">一卡通卡号</label>
        <el-input v-model="query.cardNumber" clearable placeholder="一卡通卡号" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">姓名</label>
        <el-input v-model="query.userName" clearable placeholder="姓名" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">登记时间</label>
        <el-date-picker
          v-model="buildDate"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          type="daterange"
          value-format="yyyy-MM-dd hh:mm:ss"
          style="width: 300px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-button class="filter-item" size="mini" type="success" icon="el-icon-refresh-left" @click="changeDate">搜索</el-button>
        <el-button class="filter-item" size="mini" type="warning" icon="el-icon-refresh-left" @click="resetDate">重置</el-button>
        <el-button type="primary" @click="toOpen()">是否审核设置</el-button>
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <el-button
        v-if="crud.optShow.add"
        v-permission="permission.add"
        class="filter-item"
        size="mini"
        type="primary"
        icon="el-icon-plus"
        @click="crud.toAdd"
      >
        登记车牌
      </el-button>
      <el-button
        v-if="crud.optShow.download"
        :loading="crud.downloadLoading"
        :disabled="!crud.data.length"
        class="filter-item"
        size="mini"
        type="warning"
        icon="el-icon-download"
        @click="crud.doExport"
      >导出</el-button>
      <!-- 按钮设置 -->
      <el-dialog :close-on-click-modal="false" :visible.sync="detailShow" title="是否审核设置" width="20%">
        <div label="状态" style="margin-bottom: 20px" prop="enabled">
          <el-switch
            v-model="isApprove"
            active-color="#409EFF"
            inactive-color="#F56C6C"
            inactive-text="是否审核开关："
            @change="changeEnabled(isApprove)"
          />
        </div>
        <div style="margin-bottom: 20px">
          <label>1、开启：即 APP端 登记车牌 需要审批</label>
        </div>
        <div>
          <label>2、关闭：即 APP端 登记车牌 不需要审批</label>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="detailShow = false">关闭</el-button>
        </div>
      </el-dialog>
      <!-- 详情 -->
      <el-dialog :close-on-click-modal="false" :visible.sync="detailShowXq" title="车牌登记详情" width="40%">
        <el-descriptions class="margin-top" title="车牌登记信息" :column="2" border>
          <el-descriptions-item>
            <template slot="label">
              车牌号:
            </template>
            {{ detailItem.plateNumber }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              车牌类型:
            </template>
            {{ dict.label.vehicle_type[detailItem.vehicleType] }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              效期状态:
            </template>
            {{ dict.label.effective_state[detailItem.effectiveState] }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              车牌有效期限:
            </template>
            {{ detailItem.startTime }} ~ {{ detailItem.endTime }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              登记状态:
            </template>
            {{ dict.label.registration_status[detailItem.registrationStatus] }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              登记时间:
            </template>
            {{ detailItem.updateTime }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              登记账号:
            </template>
            {{ detailItem.createBy }}
          </el-descriptions-item>
        </el-descriptions>
        <br>
        <el-descriptions class="margin-top" title="车主信息" :column="2" border>
          <el-descriptions-item>
            <template slot="label">
              一卡通卡号:
            </template>
            {{ detailItem.dmCard && detailItem.dmCard.cardNumber }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              一卡通状态:
            </template>
            {{ dict.label.card_status[detailItem.dmCard && detailItem.dmCard.status] }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              姓名:
            </template>
            {{ detailItem.dmCard && detailItem.dmCard.dmUser && detailItem.dmCard.dmUser.name }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              人员种类:
            </template>
            {{ dict.label.user_type[detailItem.dmCard && detailItem.dmCard.dmUser && detailItem.dmCard.dmUser.usertype] }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              手机号:
            </template>
            {{ detailItem.dmCard && detailItem.dmCard.dmUser && detailItem.dmCard.dmUser.contacts }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              职务:
            </template>
            {{ detailItem.dmCard && detailItem.dmCard.dmUser && detailItem.dmCard.dmUser.jobs && detailItem.dmCard.dmUser.jobs[0] && detailItem.dmCard.dmUser.jobs[0].name }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              部门:
            </template>
            {{ detailItem.dmCard && detailItem.dmCard.dmUser && detailItem.dmCard.dmUser.dept && detailItem.dmCard.dmUser.dept.name }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              在职状态:
            </template>
            {{ dict.label.dept_status[detailItem.dmCard && detailItem.dmCard.dmUser && detailItem.dmCard.dmUser.status] }}
          </el-descriptions-item>
        </el-descriptions>
        <br>
        <!-- <el-descriptions class="margin-top" title="审核信息" :column="2" border>
        <el-descriptions-item>
          <template slot="label">
            提交时间:
          </template>
          {{ detailItem.dmCard && detailItem.dmCard.cardNumber }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            审核状态:
          </template>
          {{ dict.label.user_type[detailItem.userType] }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            审核时间:
          </template>
          {{ detailItem.dmUser && detailItem.dmUser.userNumber }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            审核人员:
          </template>
          {{ detailItem.dmUser && detailItem.dmUser.company }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            审核意见:
          </template>
          {{ detailItem.dmUser && detailItem.dmUser.contacts }}
        </el-descriptions-item>
       </el-descriptions> -->
        <label>名下已登记车牌信息</label>
        <el-table :data="dataXq" border>
          <el-table-column prop="plateNumber" label="车牌号" />
          <el-table-column prop="vehicleType" label="车牌类型">
            <template slot-scope="scope">
              {{ dict.label.vehicle_type[scope.row.vehicleType] }}
            </template>
          </el-table-column>
          <el-table-column prop="startTime" label="有效开始时间" />
          <el-table-column prop="endTime" label="有效结束时间" />
          <el-table-column prop="effectiveState" label="效期状态">
            <template slot-scope="scope">
              {{ dict.label.effective_state[scope.row.effectiveState] }}
            </template>
          </el-table-column>
          <el-table-column prop="registrationStatus" label="登记状态">
            <template slot-scope="scope">
              {{ dict.label.registration_status[scope.row.registrationStatus] }}
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="登记时间" />
        </el-table>
      </el-dialog>
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="closeAll" :visible="crud.status.cu > 0" title="登记车牌" width="660px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="100px">
          <el-form-item label="一卡通卡号" prop="cardNumber">
            <!-- <el-input v-model="form.cardNumber" style="width: 370px;" @change="changeDj()"/> -->
            <el-select
              v-model="form.dmCard"
              style="width: 370px"
              filterable
              value-key="cardNumber"
              placeholder="可输入卡号搜索"
              @change="changeDj"
            >
              <el-option
                v-for="item in dmCards"
                :key="item.id"
                :label="item.cardNumber"
                :value="item"
              />
            </el-select>
          </el-form-item>

          <el-descriptions v-show="show" :column="2" style="margin-left: 30px">
            <el-descriptions-item label="人员姓名">{{ dataUser.name }}</el-descriptions-item>
            <el-descriptions-item label="人员种类">
              {{ dict.label.user_type[dataUser.usertype] }}
            </el-descriptions-item>
            <el-descriptions-item label="手机号">{{ dataUser.contacts }}</el-descriptions-item>
            <el-descriptions-item label="在职状态">
              {{ dict.label.dm_enabled[dataUser.enabled] }}
            </el-descriptions-item>
            <el-descriptions-item label="所属部门">{{ dataUser.dept && dataUser.dept.name }}</el-descriptions-item>
            <el-descriptions-item label="当前职务">{{ dataUser.jobs && dataUser.jobs[0] && dataUser.jobs[0].name }}</el-descriptions-item>
          </el-descriptions>

          <el-form-item label="车牌号" prop="plateNumber">
            <el-input v-model="form.plateNumber" placeholder="车牌号" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="车辆类型" prop="vehicleType">
            <el-select v-model="form.vehicleType" clearable placeholder="请选择车辆类型" class="filter-item" style="width: 370px">
              <el-option
                v-for="item in dict.vehicle_type"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="车牌有效期限" prop="buildDate" style="margin-bottom: 20px">
            <el-date-picker
              v-model="form.buildDate"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              type="daterange"
              value-format="yyyy-MM-dd"
              style="width: 370px;"
            />
          </el-form-item>
          <el-form-item style="border-bottom: 1px dashed" />
          <label v-show="show">当前账号已登记车牌：</label>
          <el-table v-show="show" :data="data" border style="width: 483px;margin: 20px 0 20px 0">
            <el-table-column prop="plateNumber" label="车牌号" />
            <el-table-column prop="startTime" label="有效开始时间" />
            <el-table-column prop="endTime" label="有效结束时间" />
            <el-table-column prop="effectiveState" label="效期状态">
              <template slot-scope="scope">
                {{ dict.label.effective_state[scope.row.effectiveState] }}
              </template>
            </el-table-column>
            <el-table-column prop="registrationStatus" label="登记状态">
              <template slot-scope="scope">
                {{ dict.label.registration_status[scope.row.registrationStatus] }}
              </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="登记时间" />
          </el-table>
          <label style="color:red">提示：一个账号只能登记1个车牌，此车牌将替换登记时间最久的车牌“沪A88888”，车牌“沪A88888”将失效，请确认后再操作。</label>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="closeAll">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="userNumber.name" label="用户" />
        <el-table-column prop="userNumber.contacts" label="手机" />
        <el-table-column prop="dmCard.cardNumber" label="一卡通卡号" />
        <el-table-column prop="userNumber.usertype" label="用户种类">
          <template slot-scope="scope">
            {{ scope.row.userNumber ? dict.label.user_type[scope.row.userNumber.usertype] : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="plateNumber" label="车牌号" />
        <el-table-column prop="startTime" label="有效开始时间" />
        <el-table-column prop="endTime" label="有效结束时间" />
        <el-table-column prop="effectiveState" label="效期状态">
          <template slot-scope="scope">
            {{ dict.label.effective_state[scope.row.effectiveState] }}
          </template>
        </el-table-column>
        <el-table-column prop="registrationStatus" label="登记状态">
          <template slot-scope="scope">
            {{ dict.label.registration_status[scope.row.registrationStatus] }}
          </template>
        </el-table-column>
        <el-table-column v-if="checkPer(['admin','dmPlateNumber:edit','dmPlateNumber:del'])" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
              :show-edit="false"
            />
            <el-button slot="reference" type="primary" icon="el-icon-search" size="mini" @click="toDetail(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudDmPlateNumber from '@/api/dmPlateNumber'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import { getAll } from '@/api/dm/card/dmCard'
import { getByUserNumber } from '@/api/dm/user/dmUser'

const defaultForm = { id: null, dmCard: { cardNumber: null }, userNumber: null, plateNumber: null, startTime: null, endTime: null, effectiveState: null, registrationStatus: null, createBy: null, updateBy: null, createTime: null, updateTime: null }
const defaultQuery = { plateNumber: null, cardNumber: null, type: null }
function checkPlateNumber(rule, plateNumber, callback) {
  // 普通车牌
  const plateReg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼][A-HJ-NP-Z][A-HJ-NP-Z0-9]{5}$/
  // 新能源车牌
  const newPlateReg = /^[京津晋冀蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼渝川贵云藏陕甘青宁新][A-HJ-NP-Z](([DF][A-HJ-NP-Z0-9]{5})|([A-HJ-NP-Z0-9]{5}[DF]))$/
  if (!plateNumber) {
    callback(new Error('请输入车牌号'))
  } else if (!(plateReg.test(plateNumber) || newPlateReg.test(plateNumber))) {
    callback(new Error('请输入正确的车牌号'))
  } else {
    callback()
  }
}
export default {
  name: 'DmPlateNumber',
  components: { pagination, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['effective_state', 'vehicle_type', 'registration_status', 'user_type', 'dm_enabled', 'card_status', 'dept_status'],
  cruds() {
    return CRUD({ title: '车牌管理', url: 'api/dmPlateNumber', idField: 'id', sort: 'id,desc', crudMethod: { ...crudDmPlateNumber }, query: defaultQuery })
  },
  data() {
    return {
      isApprove: false,
      data: [],
      dataXq: [],
      dmCards: [],
      dataUser: {},
      buildDate: [],
      cardCount: 0,
      show: false,
      detailShow: false,
      detailItem: {}, // 详情
      detailShowXq: false,
      // app是否审核开关状态
      appStatus: true,
      permission: {
        add: ['admin', 'dmPlateNumber:add'],
        edit: ['admin', 'dmPlateNumber:edit'],
        del: ['admin', 'dmPlateNumber:del']
      },
      rules: {
        vehicleType: [
          { required: true, message: '车辆类型不能为空', trigger: 'blur' }
        ],
        cardNumber: [
          { required: true, message: '卡号不能为空', trigger: 'blur' }
        ],
        plateNumber: [
          { validator: checkPlateNumber, trigger: 'blur' }
        ],
        buildDate: [
          { required: true, message: '车牌有效时间不能为空', trigger: 'blur' }
        ]
      }}
  },
  watch: {
    'form.dmCard': {
      handler: function(dmCard) {
        console.log(dmCard)
        this.form.cardNumber = dmCard && dmCard.cardNumber || ''
        // 添加一个cardNumber字段用于后端
        this.form.dmCard.cardNumber = dmCard && dmCard.cardNumber || ''
      },
      deep: true
    }
  },
  created() {
    this.cards()
    this.plateNumberApprove()
  },
  methods: {
    // 所有一卡通号
    cards() {
      getAll({
        cardNumber: this.form.cardNumber
      }).then(res => {
        this.dmCards = res
      }).catch(() => { })
    },
    plateNumberApprove() {
      crudDmPlateNumber.queryPlateUmberApprove({}).then(res => {
        if (res === '00') {
          this.isApprove = false
        } else if (res === '01') {
          this.isApprove = true
        }
      }).catch(() => { })
    },
    toOpen() {
      this.detailShow = true
    },
    // 详情
    toDetail(row) {
      this.detailItem = row
      this.detailShowXq = true
      crudDmPlateNumber.get({
        cardNumberXq: row.dmCard.cardNumber
        // type: '01'
      }).then(res => {
        this.dataXq = res.content
      }).catch(() => { })
    },
    changeDj(item) {
      // 人员信息
      getByUserNumber({
        userNumber: item.user_number
      }).then(res => {
        console.log(res)
        this.dataUser = res
        this.$forceUpdate()
      }).catch(() => { })
      // 车牌表格
      crudDmPlateNumber.get({
        cardNumber: item.cardNumber
        // , type: '01'
      }).then(res => {
        this.data = res.content
        this.cardCount = res.totalElements
      }).catch(() => { })

      // if (this.cardCount = 3 && this.cardCount > 3) {
      //   this.$message({
      //     message: '一个账号只能登记3个车牌,您已经不能登记',
      //     type: 'success'
      //   })
      //   this.form.cardNumber = ''
      //   // this.closeAll()
      // }else{
      if (this.form.cardNumber !== undefined || this.form.cardNumber !== null) {
        this.show = true
      }
      // }
    },
    // 改变app状态
    changeEnabled(data) {
      this.$confirm('此操作将对App端产生影响, 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let isApprove = ''
        if (data) {
          isApprove = '01'
        } else {
          isApprove = '00'
        }
        crudDmPlateNumber.updatePlateUmberApprove(isApprove).then(res => {
          this.crud.notify('操作成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        })
      })
    },
    changeDate() {
      this.crud.query.updateTime = this.buildDate || ''
      this.crud.query.cardNumber = this.query.cardNumber
      this.crud.query.plateNumber = this.query.plateNumber
      this.crud.toQuery()
    },
    resetDate() {
      this.buildDate = []
      this.query.cardNumber = ''
      this.query.plateNumber = ''
      this.changeDate()
    },
    closeAll() {
      this.show = false
      this.form.cardNumber = ''
      this.form.plateNumber = ''
      this.form.vehicleType = ''
      this.form.buildDate = []
      this.data = {}
      this.dataUser = {}
      this.crud.status.cu = 0
      this.crud.cancelCU()
    },
    [CRUD.HOOK.beforeValidateCU]() {
      this.crud.form.dmCard = {
        id: this.form.cardNumber,
        cardNumber: this.form.cardNumber
      }
      this.crud.form.userNumber = this.dataUser
      this.crud.form.startTime = this.form.buildDate[0]
      this.crud.form.endTime = this.form.buildDate[1]
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    }
  }
}
</script>

<style scoped>

</style>
